1
0
mirror of https://github.com/mariadb-corporation/mariadb-columnstore-engine.git synced 2025-07-27 21:01:50 +03:00

clang format apply

This commit is contained in:
Leonid Fedorov
2022-01-21 16:43:49 +00:00
parent 6b6411229f
commit 04752ec546
1376 changed files with 393460 additions and 412662 deletions

View File

@ -18,5 +18,5 @@ DerivePointerAlignment: false
IndentCaseLabels: true IndentCaseLabels: true
NamespaceIndentation: None NamespaceIndentation: None
PointerAlignment: Left PointerAlignment: Left
SortIncludes: true SortIncludes: false
Standard: Auto Standard: Auto

View File

@ -15,12 +15,10 @@
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */ MA 02110-1301, USA. */
#pragma once #pragma once
namespace datatypes namespace datatypes
{ {
/* /*
A subset of SQL Conditions related to data processing. A subset of SQL Conditions related to data processing.
SQLSTATE terminology is used for categories: SQLSTATE terminology is used for categories:
@ -30,7 +28,7 @@ namespace datatypes
*/ */
class DataCondition class DataCondition
{ {
public: public:
enum Code enum Code
{ {
// Code Value SQLSTATE // Code Value SQLSTATE
@ -40,26 +38,29 @@ public:
X_NUMERIC_VALUE_OUT_OF_RANGE = 1 << 17, // 22003 X_NUMERIC_VALUE_OUT_OF_RANGE = 1 << 17, // 22003
X_INVALID_CHARACTER_VALUE_FOR_CAST = 1 << 18, // 22018 X_INVALID_CHARACTER_VALUE_FOR_CAST = 1 << 18, // 22018
}; };
DataCondition() DataCondition() : mError(S_SUCCESS)
:mError(S_SUCCESS)
{ }
DataCondition(Code code)
:mError(code)
{ }
DataCondition & operator|=(Code code)
{ {
mError= (Code) (mError | code); }
DataCondition(Code code) : mError(code)
{
}
DataCondition& operator|=(Code code)
{
mError = (Code)(mError | code);
return *this; return *this;
} }
DataCondition operator&(Code rhs) const DataCondition operator&(Code rhs) const
{ {
return DataCondition((Code) (mError & rhs)); return DataCondition((Code)(mError & rhs));
}
operator Code() const
{
return mError;
} }
operator Code () const { return mError; }
// Adjust a sigened integer of any size to the range [-absMaxVal , +absMaxVal] // Adjust a sigened integer of any size to the range [-absMaxVal , +absMaxVal]
template<typename T> template <typename T>
void adjustSIntXRange(T & val, T absMaxVal) void adjustSIntXRange(T& val, T absMaxVal)
{ {
if (val > absMaxVal) if (val > absMaxVal)
{ {
@ -73,9 +74,8 @@ public:
} }
} }
private: private:
Code mError; Code mError;
}; };
} // namespace datatypes } // namespace datatypes

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -25,13 +25,11 @@
namespace datatypes namespace datatypes
{ {
// Convert a positive floating point value to // Convert a positive floating point value to
// a signed or unsigned integer with rounding // a signed or unsigned integer with rounding
// SRC - a floating point data type (float, double, float128_t) // SRC - a floating point data type (float, double, float128_t)
// DST - a signed or unsigned integer data type (int32_t, uint64_t, int128_t, etc) // DST - a signed or unsigned integer data type (int32_t, uint64_t, int128_t, etc)
template<typename SRC, typename DST> template <typename SRC, typename DST>
DST positiveXFloatToXIntRound(SRC value, DST limit) DST positiveXFloatToXIntRound(SRC value, DST limit)
{ {
SRC tmp = value + 0.5; SRC tmp = value + 0.5;
@ -40,12 +38,11 @@ DST positiveXFloatToXIntRound(SRC value, DST limit)
return static_cast<DST>(tmp); return static_cast<DST>(tmp);
} }
// Convert a negative floating point value to // Convert a negative floating point value to
// a signed integer with rounding // a signed integer with rounding
// SRC - a floating point data type (float, double, float128_t) // SRC - a floating point data type (float, double, float128_t)
// DST - a signed integer data type (int32_t, int64_t, int128_t, etc) // DST - a signed integer data type (int32_t, int64_t, int128_t, etc)
template<typename SRC, typename DST> template <typename SRC, typename DST>
DST negativeXFloatToXIntRound(SRC value, DST limit) DST negativeXFloatToXIntRound(SRC value, DST limit)
{ {
SRC tmp = value - 0.5; SRC tmp = value - 0.5;
@ -54,40 +51,31 @@ DST negativeXFloatToXIntRound(SRC value, DST limit)
return static_cast<DST>(tmp); return static_cast<DST>(tmp);
} }
// Convert a floating point value to ColumnStore int64_t // Convert a floating point value to ColumnStore int64_t
// Magic values cannot be returned. // Magic values cannot be returned.
template<typename SRC> template <typename SRC>
int64_t xFloatToMCSSInt64Round(SRC value) int64_t xFloatToMCSSInt64Round(SRC value)
{ {
if (value > 0) if (value > 0)
return positiveXFloatToXIntRound<SRC, int64_t>( return positiveXFloatToXIntRound<SRC, int64_t>(value, numeric_limits<int64_t>::max());
value,
numeric_limits<int64_t>::max());
if (value < 0) if (value < 0)
return negativeXFloatToXIntRound<SRC, int64_t>( return negativeXFloatToXIntRound<SRC, int64_t>(value, numeric_limits<int64_t>::min() + 2);
value,
numeric_limits<int64_t>::min() + 2);
return 0; return 0;
} }
// Convert a floating point value to ColumnStore uint64_t // Convert a floating point value to ColumnStore uint64_t
// Magic values cannot be returned. // Magic values cannot be returned.
template<typename SRC> template <typename SRC>
uint64_t xFloatToMCSUInt64Round(SRC value) uint64_t xFloatToMCSUInt64Round(SRC value)
{ {
if (value > 0) if (value > 0)
return positiveXFloatToXIntRound<SRC, uint64_t>( return positiveXFloatToXIntRound<SRC, uint64_t>(value, numeric_limits<uint64_t>::max() - 2);
value,
numeric_limits<uint64_t>::max() - 2);
if (value < 0) if (value < 0)
return negativeXFloatToXIntRound<SRC, uint64_t>(value, 0); return negativeXFloatToXIntRound<SRC, uint64_t>(value, 0);
return 0; return 0;
} }
} // end of namespace datatypes
} //end of namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -24,20 +24,12 @@
namespace datatypes namespace datatypes
{ {
template<typename BinaryOperation, template <typename BinaryOperation, typename OpOverflowCheck, typename MultiplicationOverflowCheck>
typename OpOverflowCheck, void addSubtractExecute(const Decimal& l, const Decimal& r, Decimal& result, BinaryOperation op,
typename MultiplicationOverflowCheck> OpOverflowCheck opOverflowCheck, MultiplicationOverflowCheck mulOverflowCheck)
void addSubtractExecute(const Decimal& l, {
const Decimal& r, int128_t lValue = Decimal::isWideDecimalTypeByPrecision(l.precision) ? l.s128Value : l.value;
Decimal& result, int128_t rValue = Decimal::isWideDecimalTypeByPrecision(r.precision) ? r.s128Value : r.value;
BinaryOperation op,
OpOverflowCheck opOverflowCheck,
MultiplicationOverflowCheck mulOverflowCheck)
{
int128_t lValue = Decimal::isWideDecimalTypeByPrecision(l.precision)
? l.s128Value : l.value;
int128_t rValue = Decimal::isWideDecimalTypeByPrecision(r.precision)
? r.s128Value : r.value;
if (result.scale == l.scale && result.scale == r.scale) if (result.scale == l.scale && result.scale == r.scale)
{ {
@ -57,9 +49,8 @@ namespace datatypes
{ {
int128_t scaleMultiplier; int128_t scaleMultiplier;
getScaleDivisor(scaleMultiplier, l.scale - result.scale); getScaleDivisor(scaleMultiplier, l.scale - result.scale);
lValue = (int128_t) (lValue > 0 ? lValue = (int128_t)(lValue > 0 ? (float128_t)lValue / scaleMultiplier + 0.5
(float128_t)lValue / scaleMultiplier + 0.5 : : (float128_t)lValue / scaleMultiplier - 0.5);
(float128_t)lValue / scaleMultiplier - 0.5);
} }
if (result.scale > r.scale) if (result.scale > r.scale)
@ -73,9 +64,8 @@ namespace datatypes
{ {
int128_t scaleMultiplier; int128_t scaleMultiplier;
getScaleDivisor(scaleMultiplier, r.scale - result.scale); getScaleDivisor(scaleMultiplier, r.scale - result.scale);
rValue = (int128_t) (rValue > 0 ? rValue = (int128_t)(rValue > 0 ? (float128_t)rValue / scaleMultiplier + 0.5
(float128_t)rValue / scaleMultiplier + 0.5 : : (float128_t)rValue / scaleMultiplier - 0.5);
(float128_t)rValue / scaleMultiplier - 0.5);
} }
// We assume there is no way that lValue or rValue calculations // We assume there is no way that lValue or rValue calculations
@ -83,20 +73,14 @@ namespace datatypes
opOverflowCheck(lValue, rValue); opOverflowCheck(lValue, rValue);
result.s128Value = op(lValue, rValue); result.s128Value = op(lValue, rValue);
} }
template<typename OpOverflowCheck, template <typename OpOverflowCheck, typename MultiplicationOverflowCheck>
typename MultiplicationOverflowCheck> void divisionExecute(const Decimal& l, const Decimal& r, Decimal& result, OpOverflowCheck opOverflowCheck,
void divisionExecute(const Decimal& l,
const Decimal& r,
Decimal& result,
OpOverflowCheck opOverflowCheck,
MultiplicationOverflowCheck mulOverflowCheck) MultiplicationOverflowCheck mulOverflowCheck)
{ {
int128_t lValue = Decimal::isWideDecimalTypeByPrecision(l.precision) int128_t lValue = Decimal::isWideDecimalTypeByPrecision(l.precision) ? l.s128Value : l.value;
? l.s128Value : l.value; int128_t rValue = Decimal::isWideDecimalTypeByPrecision(r.precision) ? r.s128Value : r.value;
int128_t rValue = Decimal::isWideDecimalTypeByPrecision(r.precision)
? r.s128Value : r.value;
opOverflowCheck(lValue, rValue); opOverflowCheck(lValue, rValue);
if (result.scale >= l.scale - r.scale) if (result.scale >= l.scale - r.scale)
@ -107,9 +91,9 @@ namespace datatypes
// TODO How do we check overflow of (int128_t)((float128_t)lValue / rValue * scaleMultiplier) ? // TODO How do we check overflow of (int128_t)((float128_t)lValue / rValue * scaleMultiplier) ?
result.s128Value = (int128_t)(( (lValue > 0 && rValue > 0) || (lValue < 0 && rValue < 0) ? result.s128Value = (int128_t)(((lValue > 0 && rValue > 0) || (lValue < 0 && rValue < 0)
(float128_t)lValue / rValue * scaleMultiplier + 0.5 : ? (float128_t)lValue / rValue * scaleMultiplier + 0.5
(float128_t)lValue / rValue * scaleMultiplier - 0.5)); : (float128_t)lValue / rValue * scaleMultiplier - 0.5));
} }
else else
{ {
@ -117,24 +101,18 @@ namespace datatypes
getScaleDivisor(scaleMultiplier, (l.scale - r.scale) - result.scale); getScaleDivisor(scaleMultiplier, (l.scale - r.scale) - result.scale);
result.s128Value = (int128_t)(( (lValue > 0 && rValue > 0) || (lValue < 0 && rValue < 0) ? result.s128Value = (int128_t)(((lValue > 0 && rValue > 0) || (lValue < 0 && rValue < 0)
(float128_t)lValue / rValue / scaleMultiplier + 0.5 : ? (float128_t)lValue / rValue / scaleMultiplier + 0.5
(float128_t)lValue / rValue / scaleMultiplier - 0.5)); : (float128_t)lValue / rValue / scaleMultiplier - 0.5));
}
} }
}
template<typename OpOverflowCheck, template <typename OpOverflowCheck, typename MultiplicationOverflowCheck>
typename MultiplicationOverflowCheck> void multiplicationExecute(const Decimal& l, const Decimal& r, Decimal& result,
void multiplicationExecute(const Decimal& l, OpOverflowCheck opOverflowCheck, MultiplicationOverflowCheck mulOverflowCheck)
const Decimal& r, {
Decimal& result, int128_t lValue = Decimal::isWideDecimalTypeByPrecision(l.precision) ? l.s128Value : l.value;
OpOverflowCheck opOverflowCheck, int128_t rValue = Decimal::isWideDecimalTypeByPrecision(r.precision) ? r.s128Value : r.value;
MultiplicationOverflowCheck mulOverflowCheck)
{
int128_t lValue = Decimal::isWideDecimalTypeByPrecision(l.precision)
? l.s128Value : l.value;
int128_t rValue = Decimal::isWideDecimalTypeByPrecision(r.precision)
? r.s128Value : r.value;
if (lValue == 0 || rValue == 0) if (lValue == 0 || rValue == 0)
{ {
@ -160,23 +138,20 @@ namespace datatypes
getScaleDivisor(scaleMultiplierL, diff / 2); getScaleDivisor(scaleMultiplierL, diff / 2);
getScaleDivisor(scaleMultiplierR, diff - (diff / 2)); getScaleDivisor(scaleMultiplierR, diff - (diff / 2));
lValue = (int128_t)(( (lValue > 0) ? lValue = (int128_t)(((lValue > 0) ? (float128_t)lValue / scaleMultiplierL + 0.5
(float128_t)lValue / scaleMultiplierL + 0.5 : : (float128_t)lValue / scaleMultiplierL - 0.5));
(float128_t)lValue / scaleMultiplierL - 0.5));
rValue = (int128_t)(( (rValue > 0) ? rValue = (int128_t)(((rValue > 0) ? (float128_t)rValue / scaleMultiplierR + 0.5
(float128_t)rValue / scaleMultiplierR + 0.5 : : (float128_t)rValue / scaleMultiplierR - 0.5));
(float128_t)rValue / scaleMultiplierR - 0.5));
opOverflowCheck(lValue, rValue, result.s128Value);; opOverflowCheck(lValue, rValue, result.s128Value);
} ;
} }
}
Decimal::Decimal(const char *str, size_t length, DataCondition & convError, Decimal::Decimal(const char* str, size_t length, DataCondition& convError, int8_t s, uint8_t p)
int8_t s, uint8_t p) : scale(s), precision(p)
:scale(s), {
precision(p)
{
literal::Converter<literal::SignedNumericLiteral> conv(str, length, convError); literal::Converter<literal::SignedNumericLiteral> conv(str, length, convError);
// We don't check "convErr" here. Let the caller do it. // We don't check "convErr" here. Let the caller do it.
// Let's just convert what has been parsed. // Let's just convert what has been parsed.
@ -185,20 +160,20 @@ namespace datatypes
conv.normalize(); conv.normalize();
if (isTSInt128ByPrecision()) if (isTSInt128ByPrecision())
{ {
s128Value = conv.toPackedSDecimal<int128_t>((literal::scale_t) scale, convError); s128Value = conv.toPackedSDecimal<int128_t>((literal::scale_t)scale, convError);
int128_t max_number_decimal = mcs_pow_10_128[precision - 19] - 1; int128_t max_number_decimal = mcs_pow_10_128[precision - 19] - 1;
convError.adjustSIntXRange(s128Value, max_number_decimal); convError.adjustSIntXRange(s128Value, max_number_decimal);
} }
else else
{ {
value = conv.toPackedSDecimal<int64_t>((literal::scale_t) scale, convError); value = conv.toPackedSDecimal<int64_t>((literal::scale_t)scale, convError);
int64_t max_number_decimal = (int64_t) mcs_pow_10[precision] - 1; int64_t max_number_decimal = (int64_t)mcs_pow_10[precision] - 1;
convError.adjustSIntXRange(value, max_number_decimal); convError.adjustSIntXRange(value, max_number_decimal);
} }
} }
int Decimal::compare(const Decimal& l, const Decimal& r) int Decimal::compare(const Decimal& l, const Decimal& r)
{ {
int128_t divisorL, divisorR; int128_t divisorL, divisorR;
getScaleDivisor(divisorL, l.scale); getScaleDivisor(divisorL, l.scale);
getScaleDivisor(divisorR, r.scale); getScaleDivisor(divisorR, r.scale);
@ -240,34 +215,31 @@ namespace datatypes
} }
return ret; return ret;
} }
// no overflow check // no overflow check
template<> template <>
void Decimal::addition<int128_t, false>(const Decimal& l, void Decimal::addition<int128_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
std::plus<int128_t> add; std::plus<int128_t> add;
NoOverflowCheck noOverflowCheck; NoOverflowCheck noOverflowCheck;
addSubtractExecute(l, r, result, add, noOverflowCheck, noOverflowCheck); addSubtractExecute(l, r, result, add, noOverflowCheck, noOverflowCheck);
} }
// with overflow check // with overflow check
template<> template <>
void Decimal::addition<int128_t, true>(const Decimal& l, void Decimal::addition<int128_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
std::plus<int128_t> add; std::plus<int128_t> add;
AdditionOverflowCheck overflowCheck; AdditionOverflowCheck overflowCheck;
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
addSubtractExecute(l, r, result, add, overflowCheck, mulOverflowCheck); addSubtractExecute(l, r, result, add, overflowCheck, mulOverflowCheck);
} }
// no overflow check // no overflow check
template<> template <>
void Decimal::addition<int64_t, false>(const Decimal& l, void Decimal::addition<int64_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
if (result.scale == l.scale && result.scale == r.scale) if (result.scale == l.scale && result.scale == r.scale)
{ {
result.value = l.value + r.value; result.value = l.value + r.value;
@ -279,25 +251,22 @@ namespace datatypes
if (result.scale > l.scale) if (result.scale > l.scale)
lValue *= mcs_pow_10[result.scale - l.scale]; lValue *= mcs_pow_10[result.scale - l.scale];
else if (result.scale < l.scale) else if (result.scale < l.scale)
lValue = (int64_t)(lValue > 0 ? lValue = (int64_t)(lValue > 0 ? (double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5
(double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5 : : (double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
(double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
if (result.scale > r.scale) if (result.scale > r.scale)
rValue *= mcs_pow_10[result.scale - r.scale]; rValue *= mcs_pow_10[result.scale - r.scale];
else if (result.scale < r.scale) else if (result.scale < r.scale)
rValue = (int64_t)(rValue > 0 ? rValue = (int64_t)(rValue > 0 ? (double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5
(double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5 : : (double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
(double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
result.value = lValue + rValue; result.value = lValue + rValue;
} }
// with overflow check // with overflow check
template<> template <>
void Decimal::addition<int64_t, true>(const Decimal& l, void Decimal::addition<int64_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
AdditionOverflowCheck additionOverflowCheck; AdditionOverflowCheck additionOverflowCheck;
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
@ -313,47 +282,42 @@ namespace datatypes
if (result.scale > l.scale) if (result.scale > l.scale)
mulOverflowCheck(lValue, mcs_pow_10[result.scale - l.scale], lValue); mulOverflowCheck(lValue, mcs_pow_10[result.scale - l.scale], lValue);
else if (result.scale < l.scale) else if (result.scale < l.scale)
lValue = (int64_t)(lValue > 0 ? lValue = (int64_t)(lValue > 0 ? (double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5
(double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5 : : (double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
(double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
if (result.scale > r.scale) if (result.scale > r.scale)
mulOverflowCheck(rValue, mcs_pow_10[result.scale - r.scale], rValue); mulOverflowCheck(rValue, mcs_pow_10[result.scale - r.scale], rValue);
else if (result.scale < r.scale) else if (result.scale < r.scale)
rValue = (int64_t)(rValue > 0 ? rValue = (int64_t)(rValue > 0 ? (double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5
(double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5 : : (double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
(double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
additionOverflowCheck(lValue, rValue); additionOverflowCheck(lValue, rValue);
result.value = lValue + rValue; result.value = lValue + rValue;
} }
// no overflow check // no overflow check
template<> template <>
void Decimal::subtraction<int128_t, false>(const Decimal& l, void Decimal::subtraction<int128_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
std::minus<int128_t> subtract; std::minus<int128_t> subtract;
NoOverflowCheck noOverflowCheck; NoOverflowCheck noOverflowCheck;
addSubtractExecute(l, r, result, subtract, noOverflowCheck, noOverflowCheck); addSubtractExecute(l, r, result, subtract, noOverflowCheck, noOverflowCheck);
} }
// with overflow check // with overflow check
template<> template <>
void Decimal::subtraction<int128_t, true>(const Decimal& l, void Decimal::subtraction<int128_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
std::minus<int128_t> subtract; std::minus<int128_t> subtract;
SubtractionOverflowCheck overflowCheck; SubtractionOverflowCheck overflowCheck;
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
addSubtractExecute(l, r, result, subtract, overflowCheck, mulOverflowCheck); addSubtractExecute(l, r, result, subtract, overflowCheck, mulOverflowCheck);
} }
// no overflow check // no overflow check
template<> template <>
void Decimal::subtraction<int64_t, false>(const Decimal& l, void Decimal::subtraction<int64_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
if (result.scale == l.scale && result.scale == r.scale) if (result.scale == l.scale && result.scale == r.scale)
{ {
result.value = l.value - r.value; result.value = l.value - r.value;
@ -365,25 +329,22 @@ namespace datatypes
if (result.scale > l.scale) if (result.scale > l.scale)
lValue *= mcs_pow_10[result.scale - l.scale]; lValue *= mcs_pow_10[result.scale - l.scale];
else if (result.scale < l.scale) else if (result.scale < l.scale)
lValue = (int64_t)(lValue > 0 ? lValue = (int64_t)(lValue > 0 ? (double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5
(double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5 : : (double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
(double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
if (result.scale > r.scale) if (result.scale > r.scale)
rValue *= mcs_pow_10[result.scale - r.scale]; rValue *= mcs_pow_10[result.scale - r.scale];
else if (result.scale < r.scale) else if (result.scale < r.scale)
rValue = (int64_t)(rValue > 0 ? rValue = (int64_t)(rValue > 0 ? (double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5
(double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5 : : (double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
(double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
result.value = lValue - rValue; result.value = lValue - rValue;
} }
// with overflow check // with overflow check
template<> template <>
void Decimal::subtraction<int64_t, true>(const Decimal& l, void Decimal::subtraction<int64_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
SubtractionOverflowCheck subtractionOverflowCheck; SubtractionOverflowCheck subtractionOverflowCheck;
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
@ -399,112 +360,108 @@ namespace datatypes
if (result.scale > l.scale) if (result.scale > l.scale)
mulOverflowCheck(lValue, mcs_pow_10[result.scale - l.scale], lValue); mulOverflowCheck(lValue, mcs_pow_10[result.scale - l.scale], lValue);
else if (result.scale < l.scale) else if (result.scale < l.scale)
lValue = (int64_t)(lValue > 0 ? lValue = (int64_t)(lValue > 0 ? (double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5
(double)lValue / mcs_pow_10[l.scale - result.scale] + 0.5 : : (double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
(double)lValue / mcs_pow_10[l.scale - result.scale] - 0.5);
if (result.scale > r.scale) if (result.scale > r.scale)
mulOverflowCheck(rValue, mcs_pow_10[result.scale - r.scale], rValue); mulOverflowCheck(rValue, mcs_pow_10[result.scale - r.scale], rValue);
else if (result.scale < r.scale) else if (result.scale < r.scale)
rValue = (int64_t)(rValue > 0 ? rValue = (int64_t)(rValue > 0 ? (double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5
(double)rValue / mcs_pow_10[r.scale - result.scale] + 0.5 : : (double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
(double)rValue / mcs_pow_10[r.scale - result.scale] - 0.5);
subtractionOverflowCheck(lValue, rValue); subtractionOverflowCheck(lValue, rValue);
result.value = lValue - rValue; result.value = lValue - rValue;
} }
// no overflow check // no overflow check
template<> template <>
void Decimal::division<int128_t, false>(const Decimal& l, void Decimal::division<int128_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
NoOverflowCheck noOverflowCheck; NoOverflowCheck noOverflowCheck;
divisionExecute(l, r, result, noOverflowCheck, noOverflowCheck); divisionExecute(l, r, result, noOverflowCheck, noOverflowCheck);
} }
// With overflow check // With overflow check
template<> template <>
void Decimal::division<int128_t, true>(const Decimal& l, void Decimal::division<int128_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
DivisionOverflowCheck overflowCheck; DivisionOverflowCheck overflowCheck;
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
divisionExecute(l, r, result, overflowCheck, mulOverflowCheck); divisionExecute(l, r, result, overflowCheck, mulOverflowCheck);
} }
// no overflow check // no overflow check
// We rely on the zero check from ArithmeticOperator::execute // We rely on the zero check from ArithmeticOperator::execute
template<> template <>
void Decimal::division<int64_t, false>(const Decimal& l, void Decimal::division<int64_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
if (result.scale >= l.scale - r.scale) if (result.scale >= l.scale - r.scale)
result.value = (int64_t)(( (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0) ? result.value = (int64_t)((
(long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] + 0.5 : (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0)
(long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] - 0.5)); ? (long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] + 0.5
: (long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] - 0.5));
else else
result.value = (int64_t)(( (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0) ? result.value = (int64_t)((
(long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] + 0.5 : (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0)
(long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] - 0.5)); ? (long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] + 0.5
} : (long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] - 0.5));
}
// With overflow check // With overflow check
template<> template <>
void Decimal::division<int64_t, true>(const Decimal& l, void Decimal::division<int64_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
DivisionOverflowCheck divisionOverflowCheck; DivisionOverflowCheck divisionOverflowCheck;
divisionOverflowCheck(l.value, r.value); divisionOverflowCheck(l.value, r.value);
if (result.scale >= l.scale - r.scale) if (result.scale >= l.scale - r.scale)
// TODO How do we check overflow of (int64_t)((long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)]) ? // TODO How do we check overflow of (int64_t)((long double)l.value / r.value * mcs_pow_10[result.scale -
result.value = (int64_t)(( (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0) ? // (l.scale - r.scale)]) ?
(long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] + 0.5 : result.value = (int64_t)((
(long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] - 0.5)); (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0)
? (long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] + 0.5
: (long double)l.value / r.value * mcs_pow_10[result.scale - (l.scale - r.scale)] - 0.5));
else else
result.value = (int64_t)(( (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0) ? result.value = (int64_t)((
(long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] + 0.5 : (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0)
(long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] - 0.5)); ? (long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] + 0.5
} : (long double)l.value / r.value / mcs_pow_10[l.scale - r.scale - result.scale] - 0.5));
}
// no overflow check // no overflow check
template<> template <>
void Decimal::multiplication<int128_t, false>(const Decimal& l, void Decimal::multiplication<int128_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
MultiplicationNoOverflowCheck noOverflowCheck; MultiplicationNoOverflowCheck noOverflowCheck;
multiplicationExecute(l, r, result, noOverflowCheck, noOverflowCheck); multiplicationExecute(l, r, result, noOverflowCheck, noOverflowCheck);
} }
// With overflow check // With overflow check
template<> template <>
void Decimal::multiplication<int128_t, true>(const Decimal& l, void Decimal::multiplication<int128_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
multiplicationExecute(l, r, result, mulOverflowCheck, mulOverflowCheck); multiplicationExecute(l, r, result, mulOverflowCheck, mulOverflowCheck);
} }
// no overflow check // no overflow check
template<> template <>
void Decimal::multiplication<int64_t, false>(const Decimal& l, void Decimal::multiplication<int64_t, false>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
if (result.scale >= l.scale + r.scale) if (result.scale >= l.scale + r.scale)
result.value = l.value * r.value * mcs_pow_10[result.scale - (l.scale + r.scale)]; result.value = l.value * r.value * mcs_pow_10[result.scale - (l.scale + r.scale)];
else else
result.value = (int64_t)(( (l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0) ? result.value =
(double)l.value * r.value / mcs_pow_10[l.scale + r.scale - result.scale] + 0.5 : (int64_t)(((l.value > 0 && r.value > 0) || (l.value < 0 && r.value < 0)
(double)l.value * r.value / mcs_pow_10[l.scale + r.scale - result.scale] - 0.5)); ? (double)l.value * r.value / mcs_pow_10[l.scale + r.scale - result.scale] + 0.5
} : (double)l.value * r.value / mcs_pow_10[l.scale + r.scale - result.scale] - 0.5));
}
// With overflow check // With overflow check
template<> template <>
void Decimal::multiplication<int64_t, true>(const Decimal& l, void Decimal::multiplication<int64_t, true>(const Decimal& l, const Decimal& r, Decimal& result)
const Decimal& r, Decimal& result) {
{
MultiplicationOverflowCheck mulOverflowCheck; MultiplicationOverflowCheck mulOverflowCheck;
if (result.scale >= l.scale + r.scale) if (result.scale >= l.scale + r.scale)
@ -516,17 +473,15 @@ namespace datatypes
{ {
mulOverflowCheck(l.value, r.value, result.value); mulOverflowCheck(l.value, r.value, result.value);
result.value = (int64_t)(( (result.value > 0) ? result.value = (int64_t)((
(double)result.value / mcs_pow_10[l.scale + r.scale - result.scale] + 0.5 : (result.value > 0) ? (double)result.value / mcs_pow_10[l.scale + r.scale - result.scale] + 0.5
(double)result.value / mcs_pow_10[l.scale + r.scale - result.scale] - 0.5)); : (double)result.value / mcs_pow_10[l.scale + r.scale - result.scale] - 0.5));
}
} }
}
// Writes integer part of a Decimal using int128 argument provided // Writes integer part of a Decimal using int128 argument provided
uint8_t Decimal::writeIntPart(const int128_t& x, uint8_t Decimal::writeIntPart(const int128_t& x, char* buf, const uint8_t buflen) const
char* buf, {
const uint8_t buflen) const
{
char* p = buf; char* p = buf;
int128_t intPart = x; int128_t intPart = x;
int128_t high = 0, mid = 0, low = 0; int128_t high = 0, mid = 0, low = 0;
@ -553,26 +508,21 @@ namespace datatypes
mid = intPart % maxUint64divisor; mid = intPart % maxUint64divisor;
high = intPart / maxUint64divisor; high = intPart / maxUint64divisor;
break; break;
default: default: throw logging::QueryDataExcept("Decimal::writeIntPart() bad scale", logging::formatErr);
throw logging::QueryDataExcept("Decimal::writeIntPart() bad scale",
logging::formatErr);
} }
p += printPodParts(p, high, mid, low); p += printPodParts(p, high, mid, low);
uint8_t written = p - buf; uint8_t written = p - buf;
if (buflen <= written) if (buflen <= written)
{ {
throw logging::QueryDataExcept("Decimal::writeIntPart() char buffer overflow.", throw logging::QueryDataExcept("Decimal::writeIntPart() char buffer overflow.", logging::formatErr);
logging::formatErr);
} }
return written; return written;
} }
uint8_t Decimal::writeFractionalPart(const int128_t& x, uint8_t Decimal::writeFractionalPart(const int128_t& x, char* buf, const uint8_t buflen) const
char* buf, {
const uint8_t buflen) const
{
int128_t scaleDivisor = 1; int128_t scaleDivisor = 1;
char* p = buf; char* p = buf;
@ -584,9 +534,8 @@ namespace datatypes
break; break;
case 1: case 1:
scaleDivisor *= datatypes::mcs_pow_10[datatypes::maxPowOf10]; scaleDivisor *= datatypes::mcs_pow_10[datatypes::maxPowOf10];
//fallthrough // fallthrough
case 0: case 0: scaleDivisor *= datatypes::mcs_pow_10[scale % datatypes::maxPowOf10];
scaleDivisor *= datatypes::mcs_pow_10[scale % datatypes::maxPowOf10];
} }
int128_t fractionalPart = x % scaleDivisor; int128_t fractionalPart = x % scaleDivisor;
@ -599,16 +548,17 @@ namespace datatypes
*p++ = '0'; *p++ = '0';
scaleDivisor /= 10; scaleDivisor /= 10;
} }
size_t written = p - buf;; size_t written = p - buf;
;
p += TSInt128::writeIntPart(fractionalPart, p, buflen - written); p += TSInt128::writeIntPart(fractionalPart, p, buflen - written);
return p - buf; return p - buf;
} }
// The method writes Decimal based on TSInt128 with scale provided. // The method writes Decimal based on TSInt128 with scale provided.
// It first writes sign, then extracts integer part // It first writes sign, then extracts integer part
// prints delimiter and then decimal part. // prints delimiter and then decimal part.
std::string Decimal::toStringTSInt128WithScale() const std::string Decimal::toStringTSInt128WithScale() const
{ {
char buf[Decimal::MAXLENGTH16BYTES]; char buf[Decimal::MAXLENGTH16BYTES];
uint8_t left = sizeof(buf); uint8_t left = sizeof(buf);
char* p = buf; char* p = buf;
@ -633,40 +583,37 @@ namespace datatypes
if (sizeof(buf) <= written) if (sizeof(buf) <= written)
{ {
throw logging::QueryDataExcept("Decimal::toString() char buffer overflow.", throw logging::QueryDataExcept("Decimal::toString() char buffer overflow.", logging::formatErr);
logging::formatErr);
} }
*p = '\0'; *p = '\0';
return std::string(buf); return std::string(buf);
} }
std::string Decimal::toStringTSInt64() const std::string Decimal::toStringTSInt64() const
{ {
char buf[Decimal::MAXLENGTH8BYTES]; char buf[Decimal::MAXLENGTH8BYTES];
uint64_t divisor = scaleDivisor<uint64_t>(scale); uint64_t divisor = scaleDivisor<uint64_t>(scale);
uint64_t uvalue = value < 0 ? (uint64_t) -value : (uint64_t) value; uint64_t uvalue = value < 0 ? (uint64_t)-value : (uint64_t)value;
uint64_t intg = uvalue / divisor; uint64_t intg = uvalue / divisor;
uint64_t frac = uvalue % divisor; uint64_t frac = uvalue % divisor;
int nbytes = snprintf(buf, sizeof(buf), "%s%" PRIu64, int nbytes = snprintf(buf, sizeof(buf), "%s%" PRIu64, value < 0 ? "-" : "", intg);
value < 0 ? "-" : "", intg);
if (scale > 0) if (scale > 0)
snprintf(buf + nbytes, sizeof(buf) - nbytes, ".%.*" PRIu64, snprintf(buf + nbytes, sizeof(buf) - nbytes, ".%.*" PRIu64, (int)scale, frac);
(int) scale, frac);
return std::string(buf); return std::string(buf);
} }
// Dispatcher method for toString() implementations // Dispatcher method for toString() implementations
std::string Decimal::toString(bool hasTSInt128) const std::string Decimal::toString(bool hasTSInt128) const
{ {
// There must be no empty at this point though // There must be no empty at this point though
if (isNull()) if (isNull())
{ {
return std::string("NULL"); return std::string("NULL");
} }
if(LIKELY(hasTSInt128 || isTSInt128ByPrecision())) if (LIKELY(hasTSInt128 || isTSInt128ByPrecision()))
{ {
if (scale) if (scale)
{ {
@ -680,11 +627,11 @@ namespace datatypes
return toStringTSInt64(); return toStringTSInt64();
} }
return std::to_string(value); return std::to_string(value);
} }
std::ostream& operator<<(std::ostream& os, const Decimal& dec) std::ostream& operator<<(std::ostream& os, const Decimal& dec)
{ {
os << dec.toString(); os << dec.toString();
return os; return os;
} }
} // end of namespace } // namespace datatypes

View File

@ -31,10 +31,9 @@
#include "branchpred.h" #include "branchpred.h"
#include "mcs_data_condition.h" #include "mcs_data_condition.h"
namespace datatypes namespace datatypes
{ {
class Decimal; class Decimal;
} }
// A class by Fabio Fernandes pulled off of stackoverflow // A class by Fabio Fernandes pulled off of stackoverflow
@ -42,52 +41,85 @@ namespace datatypes
// Ex: int128_t i128 = 12345678901234567890123456789_xxl // Ex: int128_t i128 = 12345678901234567890123456789_xxl
namespace detail_xxl namespace detail_xxl
{ {
constexpr uint8_t hexval(char c) constexpr uint8_t hexval(char c)
{ return c>='a' ? (10+c-'a') : c>='A' ? (10+c-'A') : c-'0'; } {
return c >= 'a' ? (10 + c - 'a') : c >= 'A' ? (10 + c - 'A') : c - '0';
template <int BASE, uint128_t V>
constexpr uint128_t lit_eval() { return V; }
template <int BASE, uint128_t V, char C, char... Cs>
constexpr uint128_t lit_eval() {
static_assert( BASE!=16 || sizeof...(Cs) <= 32-1, "Literal too large for BASE=16");
static_assert( BASE!=10 || sizeof...(Cs) <= 39-1, "Literal too large for BASE=10");
static_assert( BASE!=8 || sizeof...(Cs) <= 44-1, "Literal too large for BASE=8");
static_assert( BASE!=2 || sizeof...(Cs) <= 128-1, "Literal too large for BASE=2");
return lit_eval<BASE, BASE*V + hexval(C), Cs...>();
}
template<char... Cs > struct LitEval
{static constexpr uint128_t eval() {return lit_eval<10,0,Cs...>();} };
template<char... Cs> struct LitEval<'0','x',Cs...>
{static constexpr uint128_t eval() {return lit_eval<16,0,Cs...>();} };
template<char... Cs> struct LitEval<'0','b',Cs...>
{static constexpr uint128_t eval() {return lit_eval<2,0,Cs...>();} };
template<char... Cs> struct LitEval<'0',Cs...>
{static constexpr uint128_t eval() {return lit_eval<8,0,Cs...>();} };
template<char... Cs>
constexpr uint128_t operator "" _xxl() {return LitEval<Cs...>::eval();}
} }
template<char... Cs> template <int BASE, uint128_t V>
constexpr uint128_t operator "" _xxl() {return ::detail_xxl::operator "" _xxl<Cs...>();} constexpr uint128_t lit_eval()
{
return V;
}
template <int BASE, uint128_t V, char C, char... Cs>
constexpr uint128_t lit_eval()
{
static_assert(BASE != 16 || sizeof...(Cs) <= 32 - 1, "Literal too large for BASE=16");
static_assert(BASE != 10 || sizeof...(Cs) <= 39 - 1, "Literal too large for BASE=10");
static_assert(BASE != 8 || sizeof...(Cs) <= 44 - 1, "Literal too large for BASE=8");
static_assert(BASE != 2 || sizeof...(Cs) <= 128 - 1, "Literal too large for BASE=2");
return lit_eval<BASE, BASE * V + hexval(C), Cs...>();
}
template <char... Cs>
struct LitEval
{
static constexpr uint128_t eval()
{
return lit_eval<10, 0, Cs...>();
}
};
template <char... Cs>
struct LitEval<'0', 'x', Cs...>
{
static constexpr uint128_t eval()
{
return lit_eval<16, 0, Cs...>();
}
};
template <char... Cs>
struct LitEval<'0', 'b', Cs...>
{
static constexpr uint128_t eval()
{
return lit_eval<2, 0, Cs...>();
}
};
template <char... Cs>
struct LitEval<'0', Cs...>
{
static constexpr uint128_t eval()
{
return lit_eval<8, 0, Cs...>();
}
};
template <char... Cs>
constexpr uint128_t operator"" _xxl()
{
return LitEval<Cs...>::eval();
}
} // namespace detail_xxl
template <char... Cs>
constexpr uint128_t operator"" _xxl()
{
return ::detail_xxl::operator"" _xxl<Cs...>();
}
namespace datatypes namespace datatypes
{ {
constexpr uint32_t MAXDECIMALWIDTH = 16U; constexpr uint32_t MAXDECIMALWIDTH = 16U;
constexpr uint8_t INT64MAXPRECISION = 18U; constexpr uint8_t INT64MAXPRECISION = 18U;
constexpr uint8_t INT128MAXPRECISION = 38U; constexpr uint8_t INT128MAXPRECISION = 38U;
constexpr uint32_t MAXLEGACYWIDTH = 8U; constexpr uint32_t MAXLEGACYWIDTH = 8U;
constexpr uint8_t MAXSCALEINC4AVG = 4U; constexpr uint8_t MAXSCALEINC4AVG = 4U;
const uint64_t mcs_pow_10[20] = {
const uint64_t mcs_pow_10[20] =
{
1ULL, 1ULL,
10ULL, 10ULL,
100ULL, 100ULL,
@ -109,8 +141,7 @@ const uint64_t mcs_pow_10[20] =
1000000000000000000ULL, 1000000000000000000ULL,
10000000000000000000ULL, 10000000000000000000ULL,
}; };
const int128_t mcs_pow_10_128[20] = const int128_t mcs_pow_10_128[20] = {
{
10000000000000000000_xxl, 10000000000000000000_xxl,
100000000000000000000_xxl, 100000000000000000000_xxl,
1000000000000000000000_xxl, 1000000000000000000000_xxl,
@ -133,38 +164,37 @@ const int128_t mcs_pow_10_128[20] =
100000000000000000000000000000000000000_xxl, 100000000000000000000000000000000000000_xxl,
}; };
constexpr uint32_t maxPowOf10 = sizeof(mcs_pow_10)/sizeof(mcs_pow_10[0])-1; constexpr uint32_t maxPowOf10 = sizeof(mcs_pow_10) / sizeof(mcs_pow_10[0]) - 1;
constexpr int128_t Decimal128Null = TSInt128::NullValue; constexpr int128_t Decimal128Null = TSInt128::NullValue;
constexpr int128_t Decimal128Empty = TSInt128::EmptyValue; constexpr int128_t Decimal128Empty = TSInt128::EmptyValue;
template <typename T>
template<typename T>
T scaleDivisor(const uint32_t scale) T scaleDivisor(const uint32_t scale)
{ {
if (scale < 19) if (scale < 19)
return (T) mcs_pow_10[scale]; return (T)mcs_pow_10[scale];
if (scale > 39) if (scale > 39)
{ {
std::string msg = "scaleDivisor called with a wrong scale: " + std::to_string(scale); std::string msg = "scaleDivisor called with a wrong scale: " + std::to_string(scale);
throw std::invalid_argument(msg); throw std::invalid_argument(msg);
} }
return (T) mcs_pow_10_128[scale - 19]; return (T)mcs_pow_10_128[scale - 19];
} }
// Decomposed Decimal representation // Decomposed Decimal representation
// T - storage data type (int64_t, int128_t) // T - storage data type (int64_t, int128_t)
template<typename T>class DecomposedDecimal template <typename T>
class DecomposedDecimal
{ {
T mDivisor; T mDivisor;
T mIntegral; T mIntegral;
T mFractional; T mFractional;
public:
public:
DecomposedDecimal(T value, uint32_t scale) DecomposedDecimal(T value, uint32_t scale)
:mDivisor(scaleDivisor<T>(scale)), : mDivisor(scaleDivisor<T>(scale)), mIntegral(value / mDivisor), mFractional(value % mDivisor)
mIntegral(value / mDivisor), {
mFractional(value % mDivisor) }
{ }
T toSIntRound() const T toSIntRound() const
{ {
T frac2 = 2 * mFractional; T frac2 = 2 * mFractional;
@ -191,20 +221,18 @@ public:
} }
}; };
template <typename T>
template<typename T> T applySignedScale(const T& val, int32_t scale)
T applySignedScale(const T & val, int32_t scale)
{ {
return scale < 0 ? return scale < 0 ? val / datatypes::scaleDivisor<T>((uint32_t)-scale)
val / datatypes::scaleDivisor<T>((uint32_t) -scale) : : val * datatypes::scaleDivisor<T>((uint32_t)scale);
val * datatypes::scaleDivisor<T>((uint32_t) scale);
} }
/** /**
@brief The function to produce scale multiplier/divisor for @brief The function to produce scale multiplier/divisor for
wide decimals. wide decimals.
*/ */
template<typename T> template <typename T>
inline void getScaleDivisor(T& divisor, const int8_t scale) inline void getScaleDivisor(T& divisor, const int8_t scale)
{ {
if (scale < 0) if (scale < 0)
@ -212,16 +240,19 @@ inline void getScaleDivisor(T& divisor, const int8_t scale)
std::string msg = "getScaleDivisor called with negative scale: " + std::to_string(scale); std::string msg = "getScaleDivisor called with negative scale: " + std::to_string(scale);
throw std::invalid_argument(msg); throw std::invalid_argument(msg);
} }
divisor = scaleDivisor<T>((uint32_t) scale); divisor = scaleDivisor<T>((uint32_t)scale);
} }
struct lldiv_t_128 struct lldiv_t_128
{ {
int128_t quot; int128_t quot;
int128_t rem; int128_t rem;
lldiv_t_128() : quot(0), rem(0) {} lldiv_t_128() : quot(0), rem(0)
lldiv_t_128(const int128_t& a_quot, const int128_t& a_rem) {
: quot(a_quot), rem(a_rem) {} }
lldiv_t_128(const int128_t& a_quot, const int128_t& a_rem) : quot(a_quot), rem(a_rem)
{
}
}; };
inline lldiv_t_128 lldiv128(const int128_t& dividend, const int128_t& divisor) inline lldiv_t_128 lldiv128(const int128_t& dividend, const int128_t& divisor)
@ -232,25 +263,25 @@ inline lldiv_t_128 lldiv128(const int128_t& dividend, const int128_t& divisor)
return lldiv_t_128(dividend / divisor, dividend % divisor); return lldiv_t_128(dividend / divisor, dividend % divisor);
} }
// TODO: derive it from TSInt64 eventually // TODO: derive it from TSInt64 eventually
class TDecimal64 class TDecimal64
{ {
public: public:
int64_t value; int64_t value;
public:
public:
static constexpr uint8_t MAXLENGTH8BYTES = 23; static constexpr uint8_t MAXLENGTH8BYTES = 23;
public: public:
TDecimal64() TDecimal64() : value(0)
:value(0) {
{ } }
explicit TDecimal64(int64_t val) explicit TDecimal64(int64_t val) : value(val)
:value(val) {
{ } }
explicit TDecimal64(const TSInt64 &val) explicit TDecimal64(const TSInt64& val) : value(static_cast<int64_t>(val))
:value(static_cast<int64_t>(val)) {
{ } }
// Divide to the scale divisor with rounding // Divide to the scale divisor with rounding
int64_t toSInt64Round(uint32_t scale) const int64_t toSInt64Round(uint32_t scale) const
{ {
@ -258,9 +289,7 @@ public:
} }
uint64_t toUInt64Round(uint32_t scale) const uint64_t toUInt64Round(uint32_t scale) const
{ {
return value < 0 ? return value < 0 ? 0 : static_cast<uint64_t>(toSInt64Round(scale));
0 :
static_cast<uint64_t>(toSInt64Round(scale));
} }
int64_t toSInt64Floor(uint32_t scale) const int64_t toSInt64Floor(uint32_t scale) const
@ -275,17 +304,16 @@ public:
// Convert to an arbitrary floating point data type, // Convert to an arbitrary floating point data type,
// e.g. float, double, long double // e.g. float, double, long double
template<typename T> template <typename T>
T toXFloat(uint32_t scale) const T toXFloat(uint32_t scale) const
{ {
return (T) value / scaleDivisor<T>(scale); return (T)value / scaleDivisor<T>(scale);
} }
}; };
class TDecimal128 : public TSInt128
class TDecimal128: public TSInt128
{ {
public: public:
static constexpr uint8_t MAXLENGTH16BYTES = TSInt128::maxLength(); static constexpr uint8_t MAXLENGTH16BYTES = TSInt128::maxLength();
static constexpr int128_t minInt128 = TFloat128::minInt128; static constexpr int128_t minInt128 = TFloat128::minInt128;
static constexpr int128_t maxInt128 = TFloat128::maxInt128; static constexpr int128_t maxInt128 = TFloat128::maxInt128;
@ -310,26 +338,26 @@ public:
val = TSInt128::EmptyValue; val = TSInt128::EmptyValue;
} }
public: public:
TDecimal128() TDecimal128()
{ } {
explicit TDecimal128(const int128_t &val) }
:TSInt128(val) explicit TDecimal128(const int128_t& val) : TSInt128(val)
{ } {
explicit TDecimal128(const TSInt128& val) }
:TSInt128(val) explicit TDecimal128(const TSInt128& val) : TSInt128(val)
{ } {
explicit TDecimal128(const int128_t* valPtr) }
:TSInt128(valPtr) explicit TDecimal128(const int128_t* valPtr) : TSInt128(valPtr)
{ } {
}
uint64_t toUInt64Round(uint32_t scale) const uint64_t toUInt64Round(uint32_t scale) const
{ {
if (s128Value <= 0) if (s128Value <= 0)
return 0; return 0;
int128_t intg = DecomposedDecimal<int128_t>(s128Value, scale). int128_t intg = DecomposedDecimal<int128_t>(s128Value, scale).toSIntRoundPositive();
toSIntRoundPositive(); return intg > numeric_limits<uint64_t>::max() ? numeric_limits<uint64_t>::max()
return intg > numeric_limits<uint64_t>::max() ? numeric_limits<uint64_t>::max() : : static_cast<uint64_t>(intg);
static_cast<uint64_t>(intg);
} }
int128_t toSInt128Floor(uint32_t scale) const int128_t toSInt128Floor(uint32_t scale) const
@ -343,13 +371,12 @@ public:
} }
}; };
// @brief The class for Decimal related operations // @brief The class for Decimal related operations
// The methods and operators implemented in this class are // The methods and operators implemented in this class are
// scale and precision aware. // scale and precision aware.
// We should eventually move the members "scale" and "precision" // We should eventually move the members "scale" and "precision"
// into a separate class DecimalMeta and derive Decimal from it. // into a separate class DecimalMeta and derive Decimal from it.
class Decimal: public TDecimal128, public TDecimal64 class Decimal : public TDecimal128, public TDecimal64
{ {
public: public:
/** /**
@ -360,37 +387,29 @@ class Decimal: public TDecimal128, public TDecimal64
@brief Addition template that supports overflow check and @brief Addition template that supports overflow check and
two internal representations of decimal. two internal representations of decimal.
*/ */
template<typename T, bool overflow> template <typename T, bool overflow>
static void addition(const Decimal& l, static void addition(const Decimal& l, const Decimal& r, Decimal& result);
const Decimal& r,
Decimal& result);
/** /**
@brief Subtraction template that supports overflow check and @brief Subtraction template that supports overflow check and
two internal representations of decimal. two internal representations of decimal.
*/ */
template<typename T, bool overflow> template <typename T, bool overflow>
static void subtraction(const Decimal& l, static void subtraction(const Decimal& l, const Decimal& r, Decimal& result);
const Decimal& r,
Decimal& result);
/** /**
@brief Division template that supports overflow check and @brief Division template that supports overflow check and
two internal representations of decimal. two internal representations of decimal.
*/ */
template<typename T, bool overflow> template <typename T, bool overflow>
static void division(const Decimal& l, static void division(const Decimal& l, const Decimal& r, Decimal& result);
const Decimal& r,
Decimal& result);
/** /**
@brief Multiplication template that supports overflow check and @brief Multiplication template that supports overflow check and
two internal representations of decimal. two internal representations of decimal.
*/ */
template<typename T, bool overflow> template <typename T, bool overflow>
static void multiplication(const Decimal& l, static void multiplication(const Decimal& l, const Decimal& r, Decimal& result);
const Decimal& r,
Decimal& result);
/** /**
@brief The method detects whether decimal type is wide @brief The method detects whether decimal type is wide
@ -398,16 +417,13 @@ class Decimal: public TDecimal128, public TDecimal64
*/ */
static inline bool isWideDecimalTypeByPrecision(const int32_t precision) static inline bool isWideDecimalTypeByPrecision(const int32_t precision)
{ {
return precision > INT64MAXPRECISION return precision > INT64MAXPRECISION && precision <= INT128MAXPRECISION;
&& precision <= INT128MAXPRECISION;
} }
/** /**
@brief MDB increases scale by up to 4 digits calculating avg() @brief MDB increases scale by up to 4 digits calculating avg()
*/ */
static inline void setScalePrecision4Avg( static inline void setScalePrecision4Avg(unsigned int& precision, unsigned int& scale)
unsigned int& precision,
unsigned int& scale)
{ {
uint32_t scaleAvailable = INT128MAXPRECISION - scale; uint32_t scaleAvailable = INT128MAXPRECISION - scale;
uint32_t precisionAvailable = INT128MAXPRECISION - precision; uint32_t precisionAvailable = INT128MAXPRECISION - precision;
@ -415,39 +431,29 @@ class Decimal: public TDecimal128, public TDecimal64
precision += (precisionAvailable >= MAXSCALEINC4AVG) ? MAXSCALEINC4AVG : precisionAvailable; precision += (precisionAvailable >= MAXSCALEINC4AVG) ? MAXSCALEINC4AVG : precisionAvailable;
} }
Decimal(): scale(0), precision(0) Decimal() : scale(0), precision(0)
{ {
} }
Decimal(int64_t val, int8_t s, uint8_t p, const int128_t &val128 = 0) : Decimal(int64_t val, int8_t s, uint8_t p, const int128_t& val128 = 0)
TDecimal128(val128), : TDecimal128(val128), TDecimal64(val), scale(s), precision(p)
TDecimal64(val), {
scale(s), }
precision(p)
{ }
Decimal(const TSInt64 &val, int8_t s, uint8_t p) : Decimal(const TSInt64& val, int8_t s, uint8_t p) : TDecimal64(val), scale(s), precision(p)
TDecimal64(val), {
scale(s), }
precision(p)
{ }
Decimal(int64_t unused, int8_t s, uint8_t p, const int128_t* val128Ptr) : Decimal(int64_t unused, int8_t s, uint8_t p, const int128_t* val128Ptr)
TDecimal128(val128Ptr), : TDecimal128(val128Ptr), TDecimal64(unused), scale(s), precision(p)
TDecimal64(unused), {
scale(s), }
precision(p)
{ }
Decimal(const TSInt128& val128, int8_t s, uint8_t p) : Decimal(const TSInt128& val128, int8_t s, uint8_t p) : TDecimal128(val128), scale(s), precision(p)
TDecimal128(val128), {
scale(s), }
precision(p)
{ }
Decimal(const char* str, size_t length, DataCondition& error, int8_t s, uint8_t p);
Decimal(const char *str, size_t length, DataCondition & error,
int8_t s, uint8_t p);
int decimalComp(const Decimal& d) const int decimalComp(const Decimal& d) const
{ {
@ -502,7 +508,7 @@ class Decimal: public TDecimal128, public TDecimal64
{ {
int128_t scaleDivisor; int128_t scaleDivisor;
getScaleDivisor(scaleDivisor, scale); getScaleDivisor(scaleDivisor, scale);
datatypes::TFloat128 tmpval((float128_t) s128Value / scaleDivisor); datatypes::TFloat128 tmpval((float128_t)s128Value / scaleDivisor);
return static_cast<double>(tmpval); return static_cast<double>(tmpval);
} }
@ -515,7 +521,7 @@ class Decimal: public TDecimal128, public TDecimal64
{ {
int128_t scaleDivisor; int128_t scaleDivisor;
getScaleDivisor(scaleDivisor, scale); getScaleDivisor(scaleDivisor, scale);
datatypes::TFloat128 tmpval((float128_t) s128Value / scaleDivisor); datatypes::TFloat128 tmpval((float128_t)s128Value / scaleDivisor);
return static_cast<float>(tmpval); return static_cast<float>(tmpval);
} }
@ -528,7 +534,7 @@ class Decimal: public TDecimal128, public TDecimal64
{ {
int128_t scaleDivisor; int128_t scaleDivisor;
getScaleDivisor(scaleDivisor, scale); getScaleDivisor(scaleDivisor, scale);
datatypes::TFloat128 tmpval((float128_t) s128Value / scaleDivisor); datatypes::TFloat128 tmpval((float128_t)s128Value / scaleDivisor);
return static_cast<long double>(tmpval); return static_cast<long double>(tmpval);
} }
@ -553,23 +559,21 @@ class Decimal: public TDecimal128, public TDecimal64
{ {
int128_t scaleDivisor; int128_t scaleDivisor;
getScaleDivisor(scaleDivisor, scale); getScaleDivisor(scaleDivisor, scale);
return std::make_pair(TSInt128(s128Value / scaleDivisor), return std::make_pair(TSInt128(s128Value / scaleDivisor), TSInt128(s128Value % scaleDivisor));
TSInt128(s128Value % scaleDivisor));
} }
inline std::tuple<TSInt128, TSInt128, TSInt128> getIntegralFractionalAndDivisor() const inline std::tuple<TSInt128, TSInt128, TSInt128> getIntegralFractionalAndDivisor() const
{ {
int128_t scaleDivisor; int128_t scaleDivisor;
getScaleDivisor(scaleDivisor, scale); getScaleDivisor(scaleDivisor, scale);
return std::make_tuple(TSInt128(s128Value / scaleDivisor), return std::make_tuple(TSInt128(s128Value / scaleDivisor), TSInt128(s128Value % scaleDivisor),
TSInt128(s128Value % scaleDivisor),
TSInt128(scaleDivisor)); TSInt128(scaleDivisor));
} }
inline TSInt128 getIntegralPart() const inline TSInt128 getIntegralPart() const
{ {
int128_t scaleDivisor = 0; int128_t scaleDivisor = 0;
if(LIKELY(utils::is_nonnegative(scale))) if (LIKELY(utils::is_nonnegative(scale)))
{ {
return TSInt128(getIntegralPartNonNegativeScale(scaleDivisor)); return TSInt128(getIntegralPartNonNegativeScale(scaleDivisor));
} }
@ -596,73 +600,72 @@ class Decimal: public TDecimal128, public TDecimal64
int64_t decimal64ToSInt64Round() const int64_t decimal64ToSInt64Round() const
{ {
return TDecimal64::toSInt64Round((uint32_t) scale); return TDecimal64::toSInt64Round((uint32_t)scale);
} }
uint64_t decimal64ToUInt64Round() const uint64_t decimal64ToUInt64Round() const
{ {
return TDecimal64::toUInt64Round((uint32_t) scale); return TDecimal64::toUInt64Round((uint32_t)scale);
} }
template<typename T> T decimal64ToXFloat() const template <typename T>
T decimal64ToXFloat() const
{ {
return TDecimal64::toXFloat<T>((uint32_t) scale); return TDecimal64::toXFloat<T>((uint32_t)scale);
} }
int64_t toSInt64Round() const int64_t toSInt64Round() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision) ? static_cast<int64_t>(getPosNegRoundedIntegralPart(4))
static_cast<int64_t>(getPosNegRoundedIntegralPart(4)) : : TDecimal64::toSInt64Round((uint32_t)scale);
TDecimal64::toSInt64Round((uint32_t) scale);
} }
uint64_t toUInt64Round() const uint64_t toUInt64Round() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision) ? TDecimal128::toUInt64Round((uint32_t)scale)
TDecimal128::toUInt64Round((uint32_t) scale) : : TDecimal64::toUInt64Round((uint32_t)scale);
TDecimal64::toUInt64Round((uint32_t) scale);
} }
// FLOOR related routines // FLOOR related routines
int64_t toSInt64Floor() const int64_t toSInt64Floor() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision)
static_cast<int64_t>(TSInt128(TDecimal128::toSInt128Floor((uint32_t) scale))) : ? static_cast<int64_t>(TSInt128(TDecimal128::toSInt128Floor((uint32_t)scale)))
TDecimal64::toSInt64Floor((uint32_t) scale); : TDecimal64::toSInt64Floor((uint32_t)scale);
} }
uint64_t toUInt64Floor() const uint64_t toUInt64Floor() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision)
static_cast<uint64_t>(TSInt128(TDecimal128::toSInt128Floor((uint32_t) scale))) : ? static_cast<uint64_t>(TSInt128(TDecimal128::toSInt128Floor((uint32_t)scale)))
static_cast<uint64_t>(TSInt64(TDecimal64::toSInt64Floor((uint32_t) scale))); : static_cast<uint64_t>(TSInt64(TDecimal64::toSInt64Floor((uint32_t)scale)));
} }
Decimal floor() const Decimal floor() const
{ {
return isWideDecimalTypeByPrecision(precision)? return isWideDecimalTypeByPrecision(precision)
Decimal(TSInt128(TDecimal128::toSInt128Floor((uint32_t) scale)), 0, precision) : ? Decimal(TSInt128(TDecimal128::toSInt128Floor((uint32_t)scale)), 0, precision)
Decimal(TSInt64(TDecimal64::toSInt64Floor((uint32_t) scale)), 0, precision); : Decimal(TSInt64(TDecimal64::toSInt64Floor((uint32_t)scale)), 0, precision);
} }
// CEIL related routines // CEIL related routines
int64_t toSInt64Ceil() const int64_t toSInt64Ceil() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision)
static_cast<int64_t>(TSInt128(TDecimal128::toSInt128Ceil((uint32_t) scale))) : ? static_cast<int64_t>(TSInt128(TDecimal128::toSInt128Ceil((uint32_t)scale)))
static_cast<int64_t>(TSInt64(TDecimal64::toSInt64Ceil((uint32_t) scale))); : static_cast<int64_t>(TSInt64(TDecimal64::toSInt64Ceil((uint32_t)scale)));
} }
uint64_t toUInt64Ceil() const uint64_t toUInt64Ceil() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision)
static_cast<uint64_t>(TSInt128(TDecimal128::toSInt128Ceil((uint32_t) scale))) : ? static_cast<uint64_t>(TSInt128(TDecimal128::toSInt128Ceil((uint32_t)scale)))
static_cast<uint64_t>(TSInt64(TDecimal64::toSInt64Ceil((uint32_t) scale))); : static_cast<uint64_t>(TSInt64(TDecimal64::toSInt64Ceil((uint32_t)scale)));
} }
Decimal ceil() const Decimal ceil() const
{ {
return isWideDecimalTypeByPrecision(precision) ? return isWideDecimalTypeByPrecision(precision)
Decimal(TSInt128(TDecimal128::toSInt128Ceil((uint32_t) scale)), 0, precision) : ? Decimal(TSInt128(TDecimal128::toSInt128Ceil((uint32_t)scale)), 0, precision)
Decimal(TSInt64(TDecimal64::toSInt64Ceil((uint32_t) scale)), 0, precision); : Decimal(TSInt64(TDecimal64::toSInt64Ceil((uint32_t)scale)), 0, precision);
} }
// MOD operator for an integer divisor to be used // MOD operator for an integer divisor to be used
@ -676,58 +679,46 @@ class Decimal: public TDecimal128, public TDecimal64
// Scale the value and calculate // Scale the value and calculate
// (LHS.value % RHS.value) * LHS.scaleMultiplier + LHS.scale_div_remainder // (LHS.value % RHS.value) * LHS.scaleMultiplier + LHS.scale_div_remainder
auto integralFractionalDivisor = getIntegralFractionalAndDivisor(); auto integralFractionalDivisor = getIntegralFractionalAndDivisor();
return (std::get<0>(integralFractionalDivisor) % div.getValue()) * std::get<2>(integralFractionalDivisor) + std::get<1>(integralFractionalDivisor); return (std::get<0>(integralFractionalDivisor) % div.getValue()) *
std::get<2>(integralFractionalDivisor) +
std::get<1>(integralFractionalDivisor);
} }
template<typename Op128, typename Op64> template <typename Op128, typename Op64>
bool cmpOperatorTemplate(const Decimal& rhs) const bool cmpOperatorTemplate(const Decimal& rhs) const
{ {
Op128 op128; Op128 op128;
Op64 op64; Op64 op64;
if (precision > datatypes::INT64MAXPRECISION && if (precision > datatypes::INT64MAXPRECISION && rhs.precision > datatypes::INT64MAXPRECISION)
rhs.precision > datatypes::INT64MAXPRECISION)
{ {
if (scale == rhs.scale) if (scale == rhs.scale)
return op128(s128Value, rhs.s128Value); return op128(s128Value, rhs.s128Value);
else else
return op64(datatypes::Decimal::compare(*this, rhs), 0); return op64(datatypes::Decimal::compare(*this, rhs), 0);
} }
else if (precision > datatypes::INT64MAXPRECISION && else if (precision > datatypes::INT64MAXPRECISION && rhs.precision <= datatypes::INT64MAXPRECISION)
rhs.precision <= datatypes::INT64MAXPRECISION)
{ {
if (scale == rhs.scale) if (scale == rhs.scale)
{ {
return op128(s128Value, (int128_t) rhs.value); return op128(s128Value, (int128_t)rhs.value);
} }
else else
{ {
// comp_op<int64>(compare(l,r),0) // comp_op<int64>(compare(l,r),0)
return op64(datatypes::Decimal::compare( return op64(
*this, datatypes::Decimal::compare(*this, Decimal(TSInt128(rhs.value), rhs.scale, rhs.precision)), 0);
Decimal(TSInt128(rhs.value),
rhs.scale,
rhs.precision)),
0);
} }
} }
else if (precision <= datatypes::INT64MAXPRECISION && else if (precision <= datatypes::INT64MAXPRECISION && rhs.precision > datatypes::INT64MAXPRECISION)
rhs.precision > datatypes::INT64MAXPRECISION)
{ {
if (scale == rhs.scale) if (scale == rhs.scale)
{ {
return op128((int128_t) value, rhs.s128Value); return op128((int128_t)value, rhs.s128Value);
} }
else else
{ {
// comp_op<int64>(compare(l,r),0) // comp_op<int64>(compare(l,r),0)
return op64(datatypes::Decimal::compare( return op64(datatypes::Decimal::compare(Decimal(TSInt128(value), scale, precision), rhs), 0);
Decimal(
TSInt128(value),
scale,
precision),
rhs),
0);
} }
} }
else else
@ -741,20 +732,17 @@ class Decimal: public TDecimal128, public TDecimal64
bool operator==(const Decimal& rhs) const bool operator==(const Decimal& rhs) const
{ {
return cmpOperatorTemplate<std::equal_to<int128_t>, return cmpOperatorTemplate<std::equal_to<int128_t>, std::equal_to<int64_t>>(rhs);
std::equal_to<int64_t>>(rhs);
} }
bool operator>(const Decimal& rhs) const bool operator>(const Decimal& rhs) const
{ {
return cmpOperatorTemplate<std::greater<int128_t>, return cmpOperatorTemplate<std::greater<int128_t>, std::greater<int64_t>>(rhs);
std::greater<int64_t>>(rhs);
} }
bool operator>=(const Decimal& rhs) const bool operator>=(const Decimal& rhs) const
{ {
return cmpOperatorTemplate<std::greater_equal<int128_t>, return cmpOperatorTemplate<std::greater_equal<int128_t>, std::greater_equal<int64_t>>(rhs);
std::greater_equal<int64_t>>(rhs);
} }
bool operator<(const Decimal& rhs) const bool operator<(const Decimal& rhs) const
@ -775,7 +763,7 @@ class Decimal: public TDecimal128, public TDecimal64
Decimal integralWideRound(const int128_t& scaleDivisor = 0) const Decimal integralWideRound(const int128_t& scaleDivisor = 0) const
{ {
int128_t scaleDivisorInt = scaleDivisor; int128_t scaleDivisorInt = scaleDivisor;
if(UNLIKELY(!scaleDivisorInt)) if (UNLIKELY(!scaleDivisorInt))
{ {
datatypes::getScaleDivisor(scaleDivisorInt, scale); datatypes::getScaleDivisor(scaleDivisorInt, scale);
} }
@ -783,21 +771,14 @@ class Decimal: public TDecimal128, public TDecimal64
if (datatypes::abs(div.rem) * 2 >= scaleDivisorInt) if (datatypes::abs(div.rem) * 2 >= scaleDivisorInt)
{ {
return Decimal(value, return Decimal(value, scale, precision, (div.quot < 0) ? div.quot-- : div.quot++);
scale,
precision,
(div.quot < 0) ? div.quot-- : div.quot++);
} }
return Decimal(value, return Decimal(value, scale, precision, div.quot);
scale,
precision,
div.quot);
} }
inline bool isTSInt128ByPrecision() const inline bool isTSInt128ByPrecision() const
{ {
return precision > INT64MAXPRECISION return precision > INT64MAXPRECISION && precision <= INT128MAXPRECISION;
&& precision <= INT128MAXPRECISION;
} }
inline bool isScaled() const inline bool isScaled() const
@ -815,17 +796,22 @@ class Decimal: public TDecimal128, public TDecimal64
uint8_t precision; // 1~38 uint8_t precision; // 1~38
// STRICTLY for unit tests!!! // STRICTLY for unit tests!!!
void setTSInt64Value(const int64_t x) { value = x; } void setTSInt64Value(const int64_t x)
void setTSInt128Value(const int128_t& x) { s128Value = x; } {
void setScale(const uint8_t x) { scale = x; } value = x;
}
void setTSInt128Value(const int128_t& x)
{
s128Value = x;
}
void setScale(const uint8_t x)
{
scale = x;
}
private: private:
uint8_t writeIntPart(const int128_t& x, uint8_t writeIntPart(const int128_t& x, char* buf, const uint8_t buflen) const;
char* buf, uint8_t writeFractionalPart(const int128_t& x, char* buf, const uint8_t buflen) const;
const uint8_t buflen) const;
uint8_t writeFractionalPart(const int128_t& x,
char* buf,
const uint8_t buflen) const;
std::string toStringTSInt128WithScale() const; std::string toStringTSInt128WithScale() const;
std::string toStringTSInt64() const; std::string toStringTSInt64() const;
@ -841,27 +827,26 @@ class Decimal: public TDecimal128, public TDecimal64
// Calls for overflow check // Calls for overflow check
return s128Value * scaleDivisor; return s128Value * scaleDivisor;
} }
}; //end of Decimal }; // end of Decimal
/** /**
@brief The structure contains an overflow check for int128 @brief The structure contains an overflow check for int128
division. division.
*/ */
struct DivisionOverflowCheck { struct DivisionOverflowCheck
{
void operator()(const int128_t& x, const int128_t& y) void operator()(const int128_t& x, const int128_t& y)
{ {
if (x == Decimal::minInt128 && y == -1) if (x == Decimal::minInt128 && y == -1)
{ {
throw logging::OperationOverflowExcept( throw logging::OperationOverflowExcept("Decimal::division<int128_t> produces an overflow.");
"Decimal::division<int128_t> produces an overflow.");
} }
} }
void operator()(const int64_t x, const int64_t y) void operator()(const int64_t x, const int64_t y)
{ {
if (x == std::numeric_limits<int64_t>::min() && y == -1) if (x == std::numeric_limits<int64_t>::min() && y == -1)
{ {
throw logging::OperationOverflowExcept( throw logging::OperationOverflowExcept("Decimal::division<int64_t> produces an overflow.");
"Decimal::division<int64_t> produces an overflow.");
} }
} }
}; };
@ -870,7 +855,8 @@ struct DivisionOverflowCheck {
// @brief The structure contains an overflow check for int128 // @brief The structure contains an overflow check for int128
// and int64_t multiplication. // and int64_t multiplication.
// //
struct MultiplicationOverflowCheck { struct MultiplicationOverflowCheck
{
void operator()(const int128_t& x, const int128_t& y) void operator()(const int128_t& x, const int128_t& y)
{ {
int128_t tempR = 0; int128_t tempR = 0;
@ -913,7 +899,8 @@ produces an overflow.");
@brief The strucuture runs an empty overflow check for int128 @brief The strucuture runs an empty overflow check for int128
multiplication operation. multiplication operation.
*/ */
struct MultiplicationNoOverflowCheck { struct MultiplicationNoOverflowCheck
{
void operator()(const int128_t& x, const int128_t& y, int128_t& r) void operator()(const int128_t& x, const int128_t& y, int128_t& r)
{ {
r = x * y; r = x * y;
@ -924,23 +911,21 @@ struct MultiplicationNoOverflowCheck {
@brief The structure contains an overflow check for int128 @brief The structure contains an overflow check for int128
and int64 addition. and int64 addition.
*/ */
struct AdditionOverflowCheck { struct AdditionOverflowCheck
{
void operator()(const int128_t& x, const int128_t& y) void operator()(const int128_t& x, const int128_t& y)
{ {
if ((y > 0 && x > Decimal::maxInt128 - y) if ((y > 0 && x > Decimal::maxInt128 - y) || (y < 0 && x < Decimal::minInt128 - y))
|| (y < 0 && x < Decimal::minInt128 - y))
{ {
throw logging::OperationOverflowExcept( throw logging::OperationOverflowExcept("Decimal::addition<int128_t> produces an overflow.");
"Decimal::addition<int128_t> produces an overflow.");
} }
} }
void operator()(const int64_t x, const int64_t y) void operator()(const int64_t x, const int64_t y)
{ {
if ((y > 0 && x > std::numeric_limits<int64_t>::max() - y) if ((y > 0 && x > std::numeric_limits<int64_t>::max() - y) ||
|| (y < 0 && x < std::numeric_limits<int64_t>::min() - y)) (y < 0 && x < std::numeric_limits<int64_t>::min() - y))
{ {
throw logging::OperationOverflowExcept( throw logging::OperationOverflowExcept("Decimal::addition<int64_t> produces an overflow.");
"Decimal::addition<int64_t> produces an overflow.");
} }
} }
}; };
@ -949,23 +934,21 @@ struct AdditionOverflowCheck {
@brief The structure contains an overflow check for int128 @brief The structure contains an overflow check for int128
subtraction. subtraction.
*/ */
struct SubtractionOverflowCheck { struct SubtractionOverflowCheck
{
void operator()(const int128_t& x, const int128_t& y) void operator()(const int128_t& x, const int128_t& y)
{ {
if ((y > 0 && x < Decimal::minInt128 + y) if ((y > 0 && x < Decimal::minInt128 + y) || (y < 0 && x > Decimal::maxInt128 + y))
|| (y < 0 && x > Decimal::maxInt128 + y))
{ {
throw logging::OperationOverflowExcept( throw logging::OperationOverflowExcept("Decimal::subtraction<int128_t> produces an overflow.");
"Decimal::subtraction<int128_t> produces an overflow.");
} }
} }
void operator()(const int64_t x, const int64_t y) void operator()(const int64_t x, const int64_t y)
{ {
if ((y > 0 && x < std::numeric_limits<int64_t>::min() + y) if ((y > 0 && x < std::numeric_limits<int64_t>::min() + y) ||
|| (y < 0 && x > std::numeric_limits<int64_t>::max() + y)) (y < 0 && x > std::numeric_limits<int64_t>::max() + y))
{ {
throw logging::OperationOverflowExcept( throw logging::OperationOverflowExcept("Decimal::subtraction<int64_t> produces an overflow.");
"Decimal::subtraction<int64_t> produces an overflow.");
} }
} }
}; };
@ -974,11 +957,12 @@ struct SubtractionOverflowCheck {
@brief The strucuture runs an empty overflow check for int128 @brief The strucuture runs an empty overflow check for int128
operation. operation.
*/ */
struct NoOverflowCheck { struct NoOverflowCheck
{
void operator()(const int128_t& x, const int128_t& y) void operator()(const int128_t& x, const int128_t& y)
{ {
return; return;
} }
}; };
} //end of namespace } // namespace datatypes

View File

@ -22,17 +22,21 @@
namespace datatypes namespace datatypes
{ {
class TDouble class TDouble
{ {
protected: protected:
double mValue; double mValue;
public:
TDouble(): mValue(0) { }
explicit TDouble(double value): mValue(value) { } public:
TDouble() : mValue(0)
{
}
explicit operator double () const explicit TDouble(double value) : mValue(value)
{
}
explicit operator double() const
{ {
return mValue; return mValue;
} }
@ -48,7 +52,6 @@ public:
} }
}; };
} // end of namespace datatypes
} //end of namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -33,7 +33,6 @@ using float128_t = __float128;
namespace datatypes namespace datatypes
{ {
/* Main union type we use to manipulate the floating-point type. */ /* Main union type we use to manipulate the floating-point type. */
typedef union typedef union
{ {
@ -41,12 +40,12 @@ typedef union
struct struct
{ {
unsigned mantissa3:32; unsigned mantissa3 : 32;
unsigned mantissa2:32; unsigned mantissa2 : 32;
unsigned mantissa1:32; unsigned mantissa1 : 32;
unsigned mantissa0:16; unsigned mantissa0 : 16;
unsigned exponent:15; unsigned exponent : 15;
unsigned negative:1; unsigned negative : 1;
} ieee; } ieee;
struct struct
@ -65,73 +64,68 @@ typedef union
struct struct
{ {
unsigned mantissa3:32; unsigned mantissa3 : 32;
unsigned mantissa2:32; unsigned mantissa2 : 32;
unsigned mantissa1:32; unsigned mantissa1 : 32;
unsigned mantissa0:15; unsigned mantissa0 : 15;
unsigned quiet_nan:1; unsigned quiet_nan : 1;
unsigned exponent:15; unsigned exponent : 15;
unsigned negative:1; unsigned negative : 1;
} ieee_nan; } ieee_nan;
} mcs_ieee854_float128; } mcs_ieee854_float128;
/* Get two 64 bit ints from a long double. */ /* Get two 64 bit ints from a long double. */
#define MCS_GET_FLT128_WORDS64(ix0,ix1,d) \ #define MCS_GET_FLT128_WORDS64(ix0, ix1, d) \
do { \ do \
{ \
mcs_ieee854_float128 u; \ mcs_ieee854_float128 u; \
u.value = (d); \ u.value = (d); \
(ix0) = u.words64.high; \ (ix0) = u.words64.high; \
(ix1) = u.words64.low; \ (ix1) = u.words64.low; \
} while (0) } while (0)
/* Set a long double from two 64 bit ints. */ /* Set a long double from two 64 bit ints. */
#define MCS_SET_FLT128_WORDS64(d,ix0,ix1) \ #define MCS_SET_FLT128_WORDS64(d, ix0, ix1) \
do { \ do \
{ \
mcs_ieee854_float128 u; \ mcs_ieee854_float128 u; \
u.words64.high = (ix0); \ u.words64.high = (ix0); \
u.words64.low = (ix1); \ u.words64.low = (ix1); \
(d) = u.value; \ (d) = u.value; \
} while (0) } while (0)
class TSInt128; class TSInt128;
class TFloat128; class TFloat128;
using int128_t = __int128; using int128_t = __int128;
static const float128_t mcs_fl_one = 1.0, mcs_fl_Zero[] = {0.0, -0.0,}; static const float128_t mcs_fl_one = 1.0, mcs_fl_Zero[] = {
0.0,
-0.0,
};
// Copy from boost::multiprecision::float128 // Copy from boost::multiprecision::float128
template<> class numeric_limits<float128_t> { template <>
class numeric_limits<float128_t>
{
public: public:
static constexpr bool is_specialized = true; static constexpr bool is_specialized = true;
static float128_t max() static float128_t max()
{ {
return mcs_ieee854_float128{ .ieee = {0xffffffff, return mcs_ieee854_float128{.ieee = {0xffffffff, 0xffffffff, 0xffffffff, 0xffff, 0x7ffe, 0x0}}.value;
0xffffffff,
0xffffffff,
0xffff,
0x7ffe,
0x0}}.value;
} }
static float128_t min() static float128_t min()
{ {
return mcs_ieee854_float128{ .ieee = {0x0, return mcs_ieee854_float128{.ieee = {0x0, 0x0, 0x0, 0x0, 0x1, 0x0}}.value;
0x0,
0x0,
0x0,
0x1,
0x0}}.value;
} }
static float128_t denorm_min() static float128_t denorm_min()
{ {
return mcs_ieee854_float128{ .ieee = {0x1, return mcs_ieee854_float128{.ieee = {0x1, 0x0, 0x0, 0x0, 0x0, 0x0}}.value;
0x0, }
0x0, static float128_t lowest()
0x0, {
0x0, return -max();
0x0}}.value;
} }
static float128_t lowest() { return -max(); }
static constexpr int digits = 113; static constexpr int digits = 113;
static constexpr int digits10 = 33; static constexpr int digits10 = 33;
static constexpr int max_digits10 = 36; static constexpr int max_digits10 = 36;
@ -139,18 +133,30 @@ template<> class numeric_limits<float128_t> {
static constexpr bool is_integer = false; static constexpr bool is_integer = false;
static constexpr bool is_exact = false; static constexpr bool is_exact = false;
static constexpr int radix = 2; static constexpr int radix = 2;
static float128_t round_error() { return 0.5; } static float128_t round_error()
{
return 0.5;
}
static constexpr int min_exponent = -16381; static constexpr int min_exponent = -16381;
static constexpr int min_exponent10 = min_exponent * 301L / 1000L; static constexpr int min_exponent10 = min_exponent * 301L / 1000L;
static constexpr int max_exponent = 16384; static constexpr int max_exponent = 16384;
static constexpr int max_exponent10 = max_exponent * 301L / 1000L; static constexpr int max_exponent10 = max_exponent * 301L / 1000L;
static constexpr bool has_infinity = true; static constexpr bool has_infinity = true;
static constexpr bool has_quiet_NaN = true; static constexpr bool has_quiet_NaN = true;
static float128_t quiet_NaN() { return 1.0 / 0.0; } static float128_t quiet_NaN()
{
return 1.0 / 0.0;
}
static constexpr bool has_signaling_NaN = false; static constexpr bool has_signaling_NaN = false;
static constexpr bool has_denorm_loss = true; static constexpr bool has_denorm_loss = true;
static float128_t infinity() { return 1.0 / 0.0; } static float128_t infinity()
static float128_t signaling_NaN() { return 0; } {
return 1.0 / 0.0;
}
static float128_t signaling_NaN()
{
return 0;
}
static constexpr bool is_iec559 = true; static constexpr bool is_iec559 = true;
static constexpr bool is_bounded = false; static constexpr bool is_bounded = false;
static constexpr bool is_modulo = false; static constexpr bool is_modulo = false;
@ -161,17 +167,20 @@ template<> class numeric_limits<float128_t> {
// Type defined integral types // Type defined integral types
// for templates // for templates
template <typename T> template <typename T>
struct get_integral_type { struct get_integral_type
{
typedef T type; typedef T type;
}; };
template<> template <>
struct get_integral_type<TFloat128>{ struct get_integral_type<TFloat128>
{
typedef float128_t type; typedef float128_t type;
}; };
template<> template <>
struct get_integral_type<TSInt128>{ struct get_integral_type<TSInt128>
{
typedef int128_t type; typedef int128_t type;
}; };
@ -183,115 +192,178 @@ class TFloat128
static constexpr uint16_t MAXLENGTH16BYTES = 42; static constexpr uint16_t MAXLENGTH16BYTES = 42;
// A variety of ctors for aligned and unaligned arguments // A variety of ctors for aligned and unaligned arguments
TFloat128(): value(0) { } TFloat128() : value(0)
{
}
// aligned argument // aligned argument
TFloat128(const float128_t& x) { value = x; } TFloat128(const float128_t& x)
TFloat128(const int128_t& x) { value = static_cast<float128_t>(x); } {
value = x;
}
TFloat128(const int128_t& x)
{
value = static_cast<float128_t>(x);
}
// fmodq(x,y) taken from libquadmath // fmodq(x,y) taken from libquadmath
// Return x mod y in exact arithmetic // Return x mod y in exact arithmetic
// Method: shift and subtract // Method: shift and subtract
static float128_t fmodq (float128_t& x, float128_t& y) static float128_t fmodq(float128_t& x, float128_t& y)
{ {
int64_t n,hx,hy,hz,ix,iy,sx,i; int64_t n, hx, hy, hz, ix, iy, sx, i;
uint64_t lx,ly,lz; uint64_t lx, ly, lz;
MCS_GET_FLT128_WORDS64(hx,lx,x); MCS_GET_FLT128_WORDS64(hx, lx, x);
MCS_GET_FLT128_WORDS64(hy,ly,y); MCS_GET_FLT128_WORDS64(hy, ly, y);
sx = hx&0x8000000000000000ULL; /* sign of x */ sx = hx & 0x8000000000000000ULL; /* sign of x */
hx ^=sx; /* |x| */ hx ^= sx; /* |x| */
hy &= 0x7fffffffffffffffLL; /* |y| */ hy &= 0x7fffffffffffffffLL; /* |y| */
/* purge off exception values */ /* purge off exception values */
if((hy|ly)==0||(hx>=0x7fff000000000000LL)|| /* y=0,or x not finite */ if ((hy | ly) == 0 || (hx >= 0x7fff000000000000LL) || /* y=0,or x not finite */
((hy|((ly|-ly)>>63))>0x7fff000000000000LL)) /* or y is NaN */ ((hy | ((ly | -ly) >> 63)) > 0x7fff000000000000LL)) /* or y is NaN */
return (x*y)/(x*y); return (x * y) / (x * y);
if(hx<=hy) { if (hx <= hy)
if((hx<hy)||(lx<ly)) return x; /* |x|<|y| return x */ {
if(lx==ly) if ((hx < hy) || (lx < ly))
return mcs_fl_Zero[(uint64_t)sx>>63]; /* |x|=|y| return x*0*/ return x; /* |x|<|y| return x */
if (lx == ly)
return mcs_fl_Zero[(uint64_t)sx >> 63]; /* |x|=|y| return x*0*/
} }
/* determine ix = ilogb(x) */ /* determine ix = ilogb(x) */
if(hx<0x0001000000000000LL) { /* subnormal x */ if (hx < 0x0001000000000000LL)
if(hx==0) { { /* subnormal x */
for (ix = -16431, i=lx; i>0; i<<=1) ix -=1; if (hx == 0)
} else { {
for (ix = -16382, i=hx<<15; i>0; i<<=1) ix -=1; for (ix = -16431, i = lx; i > 0; i <<= 1)
ix -= 1;
} }
} else ix = (hx>>48)-0x3fff; else
{
for (ix = -16382, i = hx << 15; i > 0; i <<= 1)
ix -= 1;
}
}
else
ix = (hx >> 48) - 0x3fff;
/* determine iy = ilogb(y) */ /* determine iy = ilogb(y) */
if(hy<0x0001000000000000LL) { /* subnormal y */ if (hy < 0x0001000000000000LL)
if(hy==0) { { /* subnormal y */
for (iy = -16431, i=ly; i>0; i<<=1) iy -=1; if (hy == 0)
} else { {
for (iy = -16382, i=hy<<15; i>0; i<<=1) iy -=1; for (iy = -16431, i = ly; i > 0; i <<= 1)
iy -= 1;
} }
} else iy = (hy>>48)-0x3fff; else
{
for (iy = -16382, i = hy << 15; i > 0; i <<= 1)
iy -= 1;
}
}
else
iy = (hy >> 48) - 0x3fff;
/* set up {hx,lx}, {hy,ly} and align y to x */ /* set up {hx,lx}, {hy,ly} and align y to x */
if(ix >= -16382) if (ix >= -16382)
hx = 0x0001000000000000LL|(0x0000ffffffffffffLL&hx); hx = 0x0001000000000000LL | (0x0000ffffffffffffLL & hx);
else { /* subnormal x, shift x to normal */ else
n = -16382-ix; { /* subnormal x, shift x to normal */
if(n<=63) { n = -16382 - ix;
hx = (hx<<n)|(lx>>(64-n)); if (n <= 63)
{
hx = (hx << n) | (lx >> (64 - n));
lx <<= n; lx <<= n;
} else { }
hx = lx<<(n-64); else
{
hx = lx << (n - 64);
lx = 0; lx = 0;
} }
} }
if(iy >= -16382) if (iy >= -16382)
hy = 0x0001000000000000LL|(0x0000ffffffffffffLL&hy); hy = 0x0001000000000000LL | (0x0000ffffffffffffLL & hy);
else { /* subnormal y, shift y to normal */ else
n = -16382-iy; { /* subnormal y, shift y to normal */
if(n<=63) { n = -16382 - iy;
hy = (hy<<n)|(ly>>(64-n)); if (n <= 63)
{
hy = (hy << n) | (ly >> (64 - n));
ly <<= n; ly <<= n;
} else { }
hy = ly<<(n-64); else
{
hy = ly << (n - 64);
ly = 0; ly = 0;
} }
} }
/* fix point fmod */ /* fix point fmod */
n = ix - iy; n = ix - iy;
while(n--) { while (n--)
hz=hx-hy;lz=lx-ly; if(lx<ly) hz -= 1; {
if(hz<0){hx = hx+hx+(lx>>63); lx = lx+lx;} hz = hx - hy;
else { lz = lx - ly;
if((hz|lz)==0) /* return sign(x)*0 */ if (lx < ly)
return mcs_fl_Zero[(uint64_t)sx>>63]; hz -= 1;
hx = hz+hz+(lz>>63); lx = lz+lz; if (hz < 0)
{
hx = hx + hx + (lx >> 63);
lx = lx + lx;
}
else
{
if ((hz | lz) == 0) /* return sign(x)*0 */
return mcs_fl_Zero[(uint64_t)sx >> 63];
hx = hz + hz + (lz >> 63);
lx = lz + lz;
} }
} }
hz=hx-hy;lz=lx-ly; if(lx<ly) hz -= 1; hz = hx - hy;
if(hz>=0) {hx=hz;lx=lz;} lz = lx - ly;
if (lx < ly)
hz -= 1;
if (hz >= 0)
{
hx = hz;
lx = lz;
}
/* convert back to floating value and restore the sign */ /* convert back to floating value and restore the sign */
if((hx|lx)==0) /* return sign(x)*0 */ if ((hx | lx) == 0) /* return sign(x)*0 */
return mcs_fl_Zero[(uint64_t)sx>>63]; return mcs_fl_Zero[(uint64_t)sx >> 63];
while(hx<0x0001000000000000LL) { /* normalize x */ while (hx < 0x0001000000000000LL)
hx = hx+hx+(lx>>63); lx = lx+lx; { /* normalize x */
hx = hx + hx + (lx >> 63);
lx = lx + lx;
iy -= 1; iy -= 1;
} }
if(iy>= -16382) { /* normalize output */ if (iy >= -16382)
hx = ((hx-0x0001000000000000LL)|((iy+16383)<<48)); { /* normalize output */
MCS_SET_FLT128_WORDS64(x,hx|sx,lx); hx = ((hx - 0x0001000000000000LL) | ((iy + 16383) << 48));
} else { /* subnormal output */ MCS_SET_FLT128_WORDS64(x, hx | sx, lx);
n = -16382 - iy;
if(n<=48) {
lx = (lx>>n)|((uint64_t)hx<<(64-n));
hx >>= n;
} else if (n<=63) {
lx = (hx<<(64-n))|(lx>>n); hx = sx;
} else {
lx = hx>>(n-64); hx = sx;
} }
MCS_SET_FLT128_WORDS64(x,hx|sx,lx); else
{ /* subnormal output */
n = -16382 - iy;
if (n <= 48)
{
lx = (lx >> n) | ((uint64_t)hx << (64 - n));
hx >>= n;
}
else if (n <= 63)
{
lx = (hx << (64 - n)) | (lx >> n);
hx = sx;
}
else
{
lx = hx >> (n - 64);
hx = sx;
}
MCS_SET_FLT128_WORDS64(x, hx | sx, lx);
x *= mcs_fl_one; /* create necessary signal */ x *= mcs_fl_one; /* create necessary signal */
} }
return x; /* exact output */ return x; /* exact output */
@ -306,16 +378,22 @@ class TFloat128
const bool isinf = ((!isneg) ? bool(+x > (datatypes::numeric_limits<float128_t>::max)()) const bool isinf = ((!isneg) ? bool(+x > (datatypes::numeric_limits<float128_t>::max)())
: bool(-x > (datatypes::numeric_limits<float128_t>::max)())); : bool(-x > (datatypes::numeric_limits<float128_t>::max)()));
if(isnan) { return x; } if (isnan)
{
return x;
}
if(isinf) { return datatypes::numeric_limits<float128_t>::quiet_NaN(); } if (isinf)
{
return datatypes::numeric_limits<float128_t>::quiet_NaN();
}
const bool x_is_neg = (x < 0); const bool x_is_neg = (x < 0);
const float128_t abs_x = (x_is_neg ? -x : x); const float128_t abs_x = (x_is_neg ? -x : x);
if(p < static_cast<int>(0)) if (p < static_cast<int>(0))
{ {
if(abs_x < (datatypes::numeric_limits<float128_t>::min)()) if (abs_x < (datatypes::numeric_limits<float128_t>::min)())
{ {
return (x_is_neg ? -datatypes::numeric_limits<float128_t>::infinity() return (x_is_neg ? -datatypes::numeric_limits<float128_t>::infinity()
: +datatypes::numeric_limits<float128_t>::infinity()); : +datatypes::numeric_limits<float128_t>::infinity());
@ -326,39 +404,52 @@ class TFloat128
} }
} }
if(p == static_cast<int>(0)) if (p == static_cast<int>(0))
{ {
return float128_t(1); return float128_t(1);
} }
else else
{ {
if(p == static_cast<int>(1)) { return x; } if (p == static_cast<int>(1))
{
return x;
}
if(abs_x > (datatypes::numeric_limits<float128_t>::max)()) if (abs_x > (datatypes::numeric_limits<float128_t>::max)())
{ {
return (x_is_neg ? -datatypes::numeric_limits<float128_t>::infinity() return (x_is_neg ? -datatypes::numeric_limits<float128_t>::infinity()
: +datatypes::numeric_limits<float128_t>::infinity()); : +datatypes::numeric_limits<float128_t>::infinity());
} }
if (p == static_cast<int>(2)) { return (x * x); } if (p == static_cast<int>(2))
else if(p == static_cast<int>(3)) { return ((x * x) * x); } {
else if(p == static_cast<int>(4)) { const float128_t x2 = (x * x); return (x2 * x2); } return (x * x);
}
else if (p == static_cast<int>(3))
{
return ((x * x) * x);
}
else if (p == static_cast<int>(4))
{
const float128_t x2 = (x * x);
return (x2 * x2);
}
else else
{ {
// The variable xn stores the binary powers of x. // The variable xn stores the binary powers of x.
float128_t result(((p % int(2)) != int(0)) ? x : float128_t(1)); float128_t result(((p % int(2)) != int(0)) ? x : float128_t(1));
float128_t xn (x); float128_t xn(x);
int p2 = p; int p2 = p;
while(int(p2 /= 2) != int(0)) while (int(p2 /= 2) != int(0))
{ {
// Square xn for each binary power. // Square xn for each binary power.
xn *= xn; xn *= xn;
const bool has_binary_power = (int(p2 % int(2)) != int(0)); const bool has_binary_power = (int(p2 % int(2)) != int(0));
if(has_binary_power) if (has_binary_power)
{ {
// Multiply the result with each binary power contained in the exponent. // Multiply the result with each binary power contained in the exponent.
result *= xn; result *= xn;
@ -378,7 +469,7 @@ class TFloat128
float128_t value = 0; float128_t value = 0;
const char* p = str.c_str(); const char* p = str.c_str();
if((p == static_cast<const char*>(0U)) || (*p == static_cast<char>(0))) if ((p == static_cast<const char*>(0U)) || (*p == static_cast<char>(0)))
{ {
return value; return value;
} }
@ -393,19 +484,20 @@ class TFloat128
constexpr int max_digits10 = datatypes::numeric_limits<float128_t>::max_digits10 + 1; constexpr int max_digits10 = datatypes::numeric_limits<float128_t>::max_digits10 + 1;
if(*p == static_cast<char>('+')) if (*p == static_cast<char>('+'))
{ {
++p; ++p;
} }
else if(*p == static_cast<char>('-')) else if (*p == static_cast<char>('-'))
{ {
is_neg = true; is_neg = true;
++p; ++p;
} }
const bool isnan = ((std::strcmp(p, "nan") == 0) || (std::strcmp(p, "NaN") == 0) || (std::strcmp(p, "NAN") == 0)); const bool isnan =
((std::strcmp(p, "nan") == 0) || (std::strcmp(p, "NaN") == 0) || (std::strcmp(p, "NAN") == 0));
if(isnan) if (isnan)
{ {
value = datatypes::numeric_limits<float128_t>::infinity(); value = datatypes::numeric_limits<float128_t>::infinity();
if (is_neg) if (is_neg)
@ -415,9 +507,10 @@ class TFloat128
return value; return value;
} }
const bool isinf = ((std::strcmp(p, "inf") == 0) || (std::strcmp(p, "Inf") == 0) || (std::strcmp(p, "INF") == 0)); const bool isinf =
((std::strcmp(p, "inf") == 0) || (std::strcmp(p, "Inf") == 0) || (std::strcmp(p, "INF") == 0));
if(isinf) if (isinf)
{ {
value = datatypes::numeric_limits<float128_t>::infinity(); value = datatypes::numeric_limits<float128_t>::infinity();
if (is_neg) if (is_neg)
@ -428,7 +521,7 @@ class TFloat128
} }
// Grab all the leading digits before the decimal point. // Grab all the leading digits before the decimal point.
while(std::isdigit(*p)) while (std::isdigit(*p))
{ {
value *= ten; value *= ten;
value += static_cast<int>(*p - '0'); value += static_cast<int>(*p - '0');
@ -436,42 +529,42 @@ class TFloat128
++digits_seen; ++digits_seen;
} }
if(*p == static_cast<char>('.')) if (*p == static_cast<char>('.'))
{ {
// Grab everything after the point, stop when we've seen // Grab everything after the point, stop when we've seen
// enough digits, even if there are actually more available. // enough digits, even if there are actually more available.
++p; ++p;
while(std::isdigit(*p)) while (std::isdigit(*p))
{ {
value *= ten; value *= ten;
value += static_cast<int>(*p - '0'); value += static_cast<int>(*p - '0');
++p; ++p;
--expon; --expon;
if(++digits_seen > max_digits10) if (++digits_seen > max_digits10)
{ {
break; break;
} }
} }
while(std::isdigit(*p)) while (std::isdigit(*p))
{ {
++p; ++p;
} }
} }
// Parse the exponent. // Parse the exponent.
if((*p == static_cast<char>('e')) || (*p == static_cast<char>('E'))) if ((*p == static_cast<char>('e')) || (*p == static_cast<char>('E')))
{ {
++p; ++p;
if(*p == static_cast<char>('+')) if (*p == static_cast<char>('+'))
{ {
++p; ++p;
} }
else if(*p == static_cast<char>('-')) else if (*p == static_cast<char>('-'))
{ {
is_neg_expon = true; is_neg_expon = true;
++p; ++p;
@ -479,14 +572,14 @@ class TFloat128
int e2 = 0; int e2 = 0;
while(std::isdigit(*p)) while (std::isdigit(*p))
{ {
e2 *= 10; e2 *= 10;
e2 += (*p - '0'); e2 += (*p - '0');
++p; ++p;
} }
if(is_neg_expon) if (is_neg_expon)
{ {
e2 = -e2; e2 = -e2;
} }
@ -494,7 +587,7 @@ class TFloat128
expon += e2; expon += e2;
} }
if(expon) if (expon)
{ {
// Scale by 10^expon. Note that 10^expon can be outside the range // Scale by 10^expon. Note that 10^expon can be outside the range
// of our number type, even though the result is within range. // of our number type, even though the result is within range.
@ -502,7 +595,7 @@ class TFloat128
float128_t t; float128_t t;
t = ten; t = ten;
if(expon > (datatypes::numeric_limits<float128_t>::min_exponent10 + 2)) if (expon > (datatypes::numeric_limits<float128_t>::min_exponent10 + 2))
{ {
t = TFloat128::pown(t, expon); t = TFloat128::pown(t, expon);
value *= t; value *= t;
@ -517,7 +610,7 @@ class TFloat128
} }
} }
if(is_neg) if (is_neg)
{ {
value = -value; value = -value;
} }
@ -624,11 +717,11 @@ class TFloat128
return static_cast<long double>(value); return static_cast<long double>(value);
} }
private: private:
float128_t value; float128_t value;
}; };
} //end of namespace } // namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -24,11 +24,9 @@
namespace datatypes namespace datatypes
{ {
uint8_t TSInt128::printPodParts(char* buf, uint8_t TSInt128::printPodParts(char* buf, const int128_t& high, const int128_t& mid,
const int128_t& high,
const int128_t& mid,
const int128_t& low) const const int128_t& low) const
{ {
char* p = buf; char* p = buf;
// pod[0] is low 8 bytes, pod[1] is high 8 bytes // pod[0] is low 8 bytes, pod[1] is high 8 bytes
const uint64_t* high_pod = reinterpret_cast<const uint64_t*>(&high); const uint64_t* high_pod = reinterpret_cast<const uint64_t*>(&high);
@ -51,13 +49,11 @@ namespace datatypes
p += sprintf(p, "%lu", low_pod[0]); p += sprintf(p, "%lu", low_pod[0]);
} }
return p - buf; return p - buf;
} }
// This method writes unsigned integer representation of TSInt128 // This method writes unsigned integer representation of TSInt128
uint8_t TSInt128::writeIntPart(const int128_t& x, uint8_t TSInt128::writeIntPart(const int128_t& x, char* buf, const uint8_t buflen) const
char* buf, {
const uint8_t buflen) const
{
char* p = buf; char* p = buf;
int128_t high = 0, mid = 0, low = 0; int128_t high = 0, mid = 0, low = 0;
uint64_t maxUint64divisor = 10000000000000000000ULL; uint64_t maxUint64divisor = 10000000000000000000ULL;
@ -71,16 +67,15 @@ namespace datatypes
uint8_t written = p - buf; uint8_t written = p - buf;
if (buflen <= written) if (buflen <= written)
{ {
throw logging::QueryDataExcept("TSInt128::writeIntPart() char buffer overflow.", throw logging::QueryDataExcept("TSInt128::writeIntPart() char buffer overflow.", logging::formatErr);
logging::formatErr);
} }
return written; return written;
} }
// conversion to std::string // conversion to std::string
std::string TSInt128::toString() const std::string TSInt128::toString() const
{ {
if (isNull()) if (isNull())
{ {
return std::string("NULL"); return std::string("NULL");
@ -109,13 +104,13 @@ namespace datatypes
*p = '\0'; *p = '\0';
return std::string(buf); return std::string(buf);
} }
std::ostream& operator<<(std::ostream& os, const TSInt128& x) std::ostream& operator<<(std::ostream& os, const TSInt128& x)
{ {
os << x.toString(); os << x.toString();
return os; return os;
} }
} // end of namespace datatypes } // end of namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -27,100 +27,73 @@
// Inline asm has three argument lists: output, input and clobber list // Inline asm has three argument lists: output, input and clobber list
#ifdef __aarch64__ #ifdef __aarch64__
#define MACRO_VALUE_PTR_128(dst, \ #define MACRO_VALUE_PTR_128(dst, dst_restrictions, src, src_restrictions, clobb) \
dst_restrictions, \
src, \
src_restrictions, \
clobb) \
::memcpy((dst), &(src), sizeof(int128_t)); ::memcpy((dst), &(src), sizeof(int128_t));
#define MACRO_PTR_PTR_128(dst, \ #define MACRO_PTR_PTR_128(dst, dst_restrictions, src, src_restrictions, clobb) \
dst_restrictions, \
src, \
src_restrictions, \
clobb) \
::memcpy((dst), (src), sizeof(int128_t)); ::memcpy((dst), (src), sizeof(int128_t));
#elif defined(__GNUC__) && (__GNUC___ > 7) || defined(__clang__) #elif defined(__GNUC__) && (__GNUC___ > 7) || defined(__clang__)
#define MACRO_VALUE_PTR_128(dst, \ #define MACRO_VALUE_PTR_128(dst, dst_restrictions, src, src_restrictions, clobb) \
dst_restrictions, \ __asm__ volatile("movups %1,%0" : dst_restrictions(*(dst)) : src_restrictions((src)) : clobb);
src, \ #define MACRO_PTR_PTR_128(dst, dst_restrictions, src, src_restrictions, clobb) \
src_restrictions, \
clobb) \
__asm__ volatile("movups %1,%0" \
:dst_restrictions ( *(dst) ) \
:src_restrictions ( (src) ) \
:clobb \
);
#define MACRO_PTR_PTR_128(dst, \
dst_restrictions, \
src, \
src_restrictions, \
clobb) \
::memcpy((dst), (src), sizeof(int128_t)); ::memcpy((dst), (src), sizeof(int128_t));
#else #else
#define MACRO_VALUE_PTR_128(dst, \ #define MACRO_VALUE_PTR_128(dst, dst_restrictions, src, src_restrictions, clobb) \
dst_restrictions, \ __asm__ volatile("movups %1,%0" : dst_restrictions(*(dst)) : src_restrictions((src)) : clobb);
src, \ #define MACRO_PTR_PTR_128(dst, dst_restrictions, src, src_restrictions, clobb) \
src_restrictions, \ __asm__ volatile( \
clobb) \ "movdqu %1,%%xmm0;" \
__asm__ volatile("movups %1,%0" \
:dst_restrictions ( *(dst) ) \
:src_restrictions ( (src) ) \
:clobb \
);
#define MACRO_PTR_PTR_128(dst, \
dst_restrictions, \
src, \
src_restrictions, \
clobb) \
__asm__ volatile("movdqu %1,%%xmm0;" \
"movups %%xmm0,%0;" \ "movups %%xmm0,%0;" \
:dst_restrictions ( *(dst) ) \ : dst_restrictions(*(dst)) \
:src_restrictions ( *(src) ) \ : src_restrictions(*(src)) \
:"memory", clobb \ : "memory", clobb);
);
#endif #endif
namespace datatypes namespace datatypes
{ {
using int128_t = __int128; using int128_t = __int128;
using uint128_t = unsigned __int128; using uint128_t = unsigned __int128;
// Type traits // Type traits
template <typename T> template <typename T>
struct is_allowed_numeric { struct is_allowed_numeric
{
static const bool value = false; static const bool value = false;
}; };
template <> template <>
struct is_allowed_numeric<int> { struct is_allowed_numeric<int>
{
static const bool value = true; static const bool value = true;
}; };
template <> template <>
struct is_allowed_numeric<int128_t> { struct is_allowed_numeric<int128_t>
{
static const bool value = true; static const bool value = true;
}; };
template <typename T> template <typename T>
struct is_int128_t { struct is_int128_t
{
static const bool value = false; static const bool value = false;
}; };
template<> template <>
struct is_int128_t<int128_t> { struct is_int128_t<int128_t>
{
static const bool value = true; static const bool value = true;
}; };
template <typename T> template <typename T>
struct is_uint128_t { struct is_uint128_t
{
static const bool value = false; static const bool value = false;
}; };
template<> template <>
struct is_uint128_t<uint128_t> { struct is_uint128_t<uint128_t>
{
static const bool value = true; static const bool value = true;
}; };
@ -137,10 +110,14 @@ class TSInt128
static constexpr int128_t EmptyValue = (int128_t(0x8000000000000000LL) << 64) + 1; static constexpr int128_t EmptyValue = (int128_t(0x8000000000000000LL) << 64) + 1;
// A variety of ctors for aligned and unaligned arguments // A variety of ctors for aligned and unaligned arguments
TSInt128(): s128Value(0) { } TSInt128() : s128Value(0)
{
}
// Copy ctor // Copy ctor
TSInt128(const TSInt128& other): s128Value(other.s128Value) { } TSInt128(const TSInt128& other) : s128Value(other.s128Value)
{
}
TSInt128& operator=(const TSInt128& other) TSInt128& operator=(const TSInt128& other)
{ {
@ -149,13 +126,22 @@ class TSInt128
} }
// aligned argument // aligned argument
explicit TSInt128(const int128_t& x) { s128Value = x; } explicit TSInt128(const int128_t& x)
{
s128Value = x;
}
// unaligned argument // unaligned argument
explicit TSInt128(const int128_t* x) { assignPtrPtr(&s128Value, x); } explicit TSInt128(const int128_t* x)
{
assignPtrPtr(&s128Value, x);
}
// unaligned argument // unaligned argument
explicit TSInt128(const unsigned char* x) { assignPtrPtr(&s128Value, x); } explicit TSInt128(const unsigned char* x)
{
assignPtrPtr(&s128Value, x);
}
// Method returns max length of a string representation // Method returns max length of a string representation
static constexpr uint8_t maxLength() static constexpr uint8_t maxLength()
@ -191,15 +177,13 @@ class TSInt128
} }
// operators // operators
template<typename T, template <typename T, typename = std::enable_if<is_allowed_numeric<T>::value> >
typename = std::enable_if<is_allowed_numeric<T>::value> >
inline bool operator<(const T& x) const inline bool operator<(const T& x) const
{ {
return s128Value < static_cast<int128_t>(x); return s128Value < static_cast<int128_t>(x);
} }
template<typename T, template <typename T, typename = std::enable_if<is_allowed_numeric<T>::value> >
typename = std::enable_if<is_allowed_numeric<T>::value> >
inline bool operator==(const T& x) const inline bool operator==(const T& x) const
{ {
return s128Value == static_cast<int128_t>(x); return s128Value == static_cast<int128_t>(x);
@ -323,15 +307,10 @@ class TSInt128
} }
// print int128_t parts represented as PODs // print int128_t parts represented as PODs
uint8_t printPodParts(char* buf, uint8_t printPodParts(char* buf, const int128_t& high, const int128_t& mid, const int128_t& low) const;
const int128_t& high,
const int128_t& mid,
const int128_t& low) const;
// writes integer part of dec into a buffer // writes integer part of dec into a buffer
uint8_t writeIntPart(const int128_t& x, uint8_t writeIntPart(const int128_t& x, char* buf, const uint8_t buflen) const;
char* buf,
const uint8_t buflen) const;
// string representation of TSInt128 // string representation of TSInt128
std::string toString() const; std::string toString() const;
@ -339,9 +318,8 @@ class TSInt128
friend std::ostream& operator<<(std::ostream& os, const TSInt128& x); friend std::ostream& operator<<(std::ostream& os, const TSInt128& x);
int128_t s128Value; int128_t s128Value;
}; // end of class }; // end of class
} // end of namespace datatypes
} //end of namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -22,154 +22,161 @@
namespace datatypes namespace datatypes
{ {
class TNullFlag class TNullFlag
{ {
protected: protected:
bool mIsNull; bool mIsNull;
public:
explicit TNullFlag(bool val) :mIsNull(val) { } public:
explicit TNullFlag(bool val) : mIsNull(val)
{
}
bool isNull() const bool isNull() const
{ {
return mIsNull; return mIsNull;
} }
}; };
class TUInt64 class TUInt64
{ {
protected: protected:
uint64_t mValue; uint64_t mValue;
public:
TUInt64(): mValue(0) { }
explicit TUInt64(uint64_t value): mValue(value) { } public:
TUInt64() : mValue(0)
{
}
explicit operator uint64_t () const explicit TUInt64(uint64_t value) : mValue(value)
{
}
explicit operator uint64_t() const
{ {
return mValue; return mValue;
} }
void store(uint8_t* dst) const void store(uint8_t* dst) const
{ {
*(uint64_t*) dst = mValue; *(uint64_t*)dst = mValue;
} }
}; };
class TSInt64 class TSInt64
{ {
protected: protected:
int64_t mValue; int64_t mValue;
public:
TSInt64(): mValue(0) { }
explicit TSInt64(int64_t value): mValue(value) { } public:
TSInt64() : mValue(0)
{
}
explicit operator int64_t () const explicit TSInt64(int64_t value) : mValue(value)
{
}
explicit operator int64_t() const
{ {
return mValue; return mValue;
} }
explicit operator uint64_t () const explicit operator uint64_t() const
{ {
return mValue < 0 ? 0 : static_cast<uint64_t>(mValue); return mValue < 0 ? 0 : static_cast<uint64_t>(mValue);
} }
}; };
class TUInt64Null : public TUInt64, public TNullFlag
class TUInt64Null: public TUInt64, public TNullFlag
{ {
public: public:
TUInt64Null() : TNullFlag(true)
{
}
TUInt64Null(): TNullFlag(true) { } explicit TUInt64Null(uint64_t value, bool isNull = false) : TUInt64(value), TNullFlag(isNull)
{
}
explicit TUInt64Null(uint64_t value, bool isNull = false): explicit operator uint64_t() const
TUInt64(value), TNullFlag(isNull)
{ }
explicit operator uint64_t () const
{ {
idbassert(!mIsNull); idbassert(!mIsNull);
return mValue; return mValue;
} }
uint64_t nullSafeValue(bool & isNullRef) const uint64_t nullSafeValue(bool& isNullRef) const
{ {
return (isNullRef = isNull()) ? 0 : mValue; return (isNullRef = isNull()) ? 0 : mValue;
} }
TUInt64Null operator&(const TUInt64Null &rhs) const TUInt64Null operator&(const TUInt64Null& rhs) const
{ {
return TUInt64Null(mValue & rhs.mValue, mIsNull || rhs.mIsNull); return TUInt64Null(mValue & rhs.mValue, mIsNull || rhs.mIsNull);
} }
TUInt64Null operator|(const TUInt64Null &rhs) const TUInt64Null operator|(const TUInt64Null& rhs) const
{ {
return TUInt64Null(mValue | rhs.mValue, mIsNull || rhs.mIsNull); return TUInt64Null(mValue | rhs.mValue, mIsNull || rhs.mIsNull);
} }
TUInt64Null operator^(const TUInt64Null &rhs) const TUInt64Null operator^(const TUInt64Null& rhs) const
{ {
return TUInt64Null(mValue ^ rhs.mValue, mIsNull || rhs.mIsNull); return TUInt64Null(mValue ^ rhs.mValue, mIsNull || rhs.mIsNull);
} }
TUInt64Null MariaDBShiftLeft(const TUInt64Null &rhs) const TUInt64Null MariaDBShiftLeft(const TUInt64Null& rhs) const
{ {
return TUInt64Null(rhs.mValue >= 64 ? 0 : mValue << rhs.mValue, mIsNull || rhs.mIsNull); return TUInt64Null(rhs.mValue >= 64 ? 0 : mValue << rhs.mValue, mIsNull || rhs.mIsNull);
} }
TUInt64Null MariaDBShiftRight(const TUInt64Null &rhs) const TUInt64Null MariaDBShiftRight(const TUInt64Null& rhs) const
{ {
return TUInt64Null(rhs.mValue >= 64 ? 0 : mValue >> rhs.mValue, mIsNull || rhs.mIsNull); return TUInt64Null(rhs.mValue >= 64 ? 0 : mValue >> rhs.mValue, mIsNull || rhs.mIsNull);
} }
}; };
class TSInt64Null : public TSInt64, public TNullFlag
class TSInt64Null: public TSInt64, public TNullFlag
{ {
public: public:
TSInt64Null() : TNullFlag(true)
{
}
TSInt64Null(): TNullFlag(true) { } explicit TSInt64Null(int64_t value, bool isNull = false) : TSInt64(value), TNullFlag(isNull)
{
}
explicit TSInt64Null(int64_t value, bool isNull = false): explicit operator int64_t() const
TSInt64(value), TNullFlag(isNull)
{ }
explicit operator int64_t () const
{ {
idbassert(!mIsNull); idbassert(!mIsNull);
return mValue; return mValue;
} }
int64_t nullSafeValue(bool & isNullRef) const int64_t nullSafeValue(bool& isNullRef) const
{ {
return (isNullRef = isNull()) ? 0 : mValue; return (isNullRef = isNull()) ? 0 : mValue;
} }
TSInt64Null operator&(const TSInt64Null &rhs) const TSInt64Null operator&(const TSInt64Null& rhs) const
{ {
return TSInt64Null(mValue & rhs.mValue, mIsNull || rhs.mIsNull); return TSInt64Null(mValue & rhs.mValue, mIsNull || rhs.mIsNull);
} }
TSInt64Null operator|(const TSInt64Null &rhs) const TSInt64Null operator|(const TSInt64Null& rhs) const
{ {
return TSInt64Null(mValue | rhs.mValue, mIsNull || rhs.mIsNull); return TSInt64Null(mValue | rhs.mValue, mIsNull || rhs.mIsNull);
} }
TSInt64Null operator^(const TSInt64Null &rhs) const TSInt64Null operator^(const TSInt64Null& rhs) const
{ {
return TSInt64Null(mValue ^ rhs.mValue, mIsNull || rhs.mIsNull); return TSInt64Null(mValue ^ rhs.mValue, mIsNull || rhs.mIsNull);
} }
TSInt64Null MariaDBShiftLeft(const TUInt64Null &rhs) const TSInt64Null MariaDBShiftLeft(const TUInt64Null& rhs) const
{ {
if (isNull() || rhs.isNull()) if (isNull() || rhs.isNull())
return TSInt64Null(); return TSInt64Null();
return TSInt64Null((uint64_t) rhs >= 64 ? 0 : mValue << (uint64_t) rhs, false); return TSInt64Null((uint64_t)rhs >= 64 ? 0 : mValue << (uint64_t)rhs, false);
} }
TSInt64Null MariaDBShiftRight(const TUInt64Null &rhs) const TSInt64Null MariaDBShiftRight(const TUInt64Null& rhs) const
{ {
if (isNull() || rhs.isNull()) if (isNull() || rhs.isNull())
return TSInt64Null(); return TSInt64Null();
return TSInt64Null((uint64_t) rhs >= 64 ? 0 : mValue >> (uint64_t) rhs, false); return TSInt64Null((uint64_t)rhs >= 64 ? 0 : mValue >> (uint64_t)rhs, false);
} }
}; };
} // end of namespace datatypes
} //end of namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -22,17 +22,21 @@
namespace datatypes namespace datatypes
{ {
class TLongDouble class TLongDouble
{ {
protected: protected:
long double mValue; long double mValue;
public:
TLongDouble(): mValue(0) { }
explicit TLongDouble(long double value): mValue(value) { } public:
TLongDouble() : mValue(0)
{
}
explicit operator long double () const explicit TLongDouble(long double value) : mValue(value)
{
}
explicit operator long double() const
{ {
return mValue; return mValue;
} }
@ -48,7 +52,6 @@ public:
} }
}; };
} // end of namespace datatypes
} //end of namespace datatypes
// vim:ts=2 sw=2: // vim:ts=2 sw=2:

View File

@ -21,18 +21,24 @@
namespace datatypes namespace datatypes
{ {
template <typename T> template <typename T>
struct numeric_limits struct numeric_limits
{ {
static constexpr T min() { return std::numeric_limits<T>::min(); } static constexpr T min()
static constexpr T max() { return std::numeric_limits<T>::max(); } {
return std::numeric_limits<T>::min();
}
static constexpr T max()
{
return std::numeric_limits<T>::max();
}
}; };
using int128_t = __int128; using int128_t = __int128;
using uint128_t = unsigned __int128; using uint128_t = unsigned __int128;
template<> struct numeric_limits<int128_t> template <>
struct numeric_limits<int128_t>
{ {
static constexpr int128_t min() static constexpr int128_t min()
{ {
@ -44,7 +50,8 @@ template<> struct numeric_limits<int128_t>
} }
}; };
template<> struct numeric_limits<uint128_t> template <>
struct numeric_limits<uint128_t>
{ {
static constexpr uint128_t min() static constexpr uint128_t min()
{ {
@ -57,4 +64,3 @@ template<> struct numeric_limits<uint128_t>
}; };
} // namespace datatypes } // namespace datatypes

View File

@ -15,7 +15,6 @@
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */ MA 02110-1301, USA. */
#pragma once #pragma once
#include "conststring.h" #include "conststring.h"
@ -23,29 +22,25 @@
namespace datatypes namespace datatypes
{ {
class TCharShort class TCharShort
{ {
int64_t mValue; int64_t mValue;
public:
TCharShort(int64_t value) public:
:mValue(value) TCharShort(int64_t value) : mValue(value)
{ } {
}
utils::ConstString toConstString(uint32_t width) const utils::ConstString toConstString(uint32_t width) const
{ {
utils::ConstString res = utils::ConstString((const char *) &mValue, width); utils::ConstString res = utils::ConstString((const char*)&mValue, width);
return res.rtrimZero(); return res.rtrimZero();
} }
static int strnncollsp(const datatypes::Charset &cs, int64_t a, int64_t b, uint32_t width) static int strnncollsp(const datatypes::Charset& cs, int64_t a, int64_t b, uint32_t width)
{ {
datatypes::TCharShort sa(a); datatypes::TCharShort sa(a);
datatypes::TCharShort sb(b); datatypes::TCharShort sb(b);
return cs.strnncollsp(sa.toConstString(width), return cs.strnncollsp(sa.toConstString(width), sb.toConstString(width));
sb.toConstString(width));
} }
}; };
} // namespace datatypes } // namespace datatypes

View File

@ -15,32 +15,25 @@
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */ MA 02110-1301, USA. */
#pragma once #pragma once
#include "genericparser.h" #include "genericparser.h"
#include "mcs_datatype.h" #include "mcs_datatype.h"
namespace literal namespace literal
{ {
using utils::ConstString;
using genericparser::Parser;
using datatypes::DataCondition; using datatypes::DataCondition;
using genericparser::Parser;
using utils::ConstString;
typedef uint32_t scale_t; typedef uint32_t scale_t;
template <class A>
class Converter : public Parser, public A
template<class A>
class Converter: public Parser,
public A
{ {
public: public:
Converter(const char *str, size_t length, DataCondition & error) Converter(const char* str, size_t length, DataCondition& error)
:Parser(str, length), : Parser(str, length), A(&Parser::skipLeadingSpaces())
A(&Parser::skipLeadingSpaces())
{ {
if (Parser::syntaxError()) if (Parser::syntaxError())
{ {
@ -56,15 +49,14 @@ public:
'1e' - exponent marker was not followed by <exponent>, expect '1e1' '1e' - exponent marker was not followed by <exponent>, expect '1e1'
'1e+' - in <exponent>, <sign> was not followed by a digit, expect '1e+1' '1e+' - in <exponent>, <sign> was not followed by a digit, expect '1e+1'
*/ */
error|=(DataCondition::X_INVALID_CHARACTER_VALUE_FOR_CAST); error |= (DataCondition::X_INVALID_CHARACTER_VALUE_FOR_CAST);
} }
} }
Converter(const std::string & str, DataCondition &error) Converter(const std::string& str, DataCondition& error) : Converter(str.data(), str.length(), error)
:Converter(str.data(), str.length(), error) {
{ } }
}; };
/* /*
SQL Standard definition for <cast specification> SQL Standard definition for <cast specification>
@ -143,70 +135,83 @@ Grammar
*/ */
// //
// Terminal symbols // Terminal symbols
// //
class Period: public ConstString class Period : public ConstString
{ {
public: public:
explicit Period(Parser *p) explicit Period(Parser* p) : ConstString(p->tokenChar('.'))
:ConstString(p->tokenChar('.')) {
{ } }
bool isNull() const { return mStr == nullptr; } bool isNull() const
{
return mStr == nullptr;
}
}; };
class ExponentMarker : public ConstString
class ExponentMarker: public ConstString
{ {
public: public:
explicit ExponentMarker(Parser *p) explicit ExponentMarker(Parser* p) : ConstString(p->tokenAnyCharOf('e', 'E'))
:ConstString(p->tokenAnyCharOf('e', 'E')) {
{ } }
bool isNull() const { return mStr == nullptr; } bool isNull() const
{
return mStr == nullptr;
}
}; };
class Sign : public ConstString
class Sign: public ConstString
{ {
public: public:
explicit Sign(): ConstString(NULL, 0) { } explicit Sign() : ConstString(NULL, 0)
explicit Sign(const ConstString &str) {
:ConstString(str) }
{ } explicit Sign(const ConstString& str) : ConstString(str)
explicit Sign(Parser *p) {
:ConstString(p->tokenAnyCharOf('+', '-')) }
{ } explicit Sign(Parser* p) : ConstString(p->tokenAnyCharOf('+', '-'))
static Sign empty(Parser *p) {
}
static Sign empty(Parser* p)
{ {
return Sign(p->tokStartConstString()); return Sign(p->tokStartConstString());
} }
bool isNull() const { return mStr == nullptr; } bool isNull() const
bool negative() const { return eq('-'); } {
return mStr == nullptr;
}
bool negative() const
{
return eq('-');
}
}; };
class Digits : public ConstString
class Digits: public ConstString
{ {
public: public:
explicit Digits() explicit Digits() : ConstString(NULL, 0)
:ConstString(NULL, 0) {
{ } }
explicit Digits(const char *str, size_t length) explicit Digits(const char* str, size_t length) : ConstString(str, length)
:ConstString(str, length) {
{ } }
explicit Digits(const ConstString &str) explicit Digits(const ConstString& str) : ConstString(str)
:ConstString(str) {
{ } }
explicit Digits(Parser *p) explicit Digits(Parser* p) : ConstString(p->tokenDigits())
:ConstString(p->tokenDigits()) {
{ } }
bool isNull() const { return mStr == nullptr; } bool isNull() const
{
return mStr == nullptr;
}
void skipLeadingZeroDigits() void skipLeadingZeroDigits()
{ {
for ( ; mLength > 0 && mStr[0] == '0'; ) for (; mLength > 0 && mStr[0] == '0';)
{ {
mStr++; mStr++;
mLength--; mLength--;
@ -214,33 +219,32 @@ public:
} }
void skipTrailingZeroDigits() void skipTrailingZeroDigits()
{ {
for ( ; mLength > 0 && mStr[mLength - 1] == '0' ; ) for (; mLength > 0 && mStr[mLength - 1] == '0';)
mLength--; mLength--;
} }
}; };
// //
// Non-terminal symbols // Non-terminal symbols
// //
// <unsigned integer> ::= <digit> ... // <unsigned integer> ::= <digit> ...
class UnsignedInteger: public Digits class UnsignedInteger : public Digits
{ {
public: public:
explicit UnsignedInteger() explicit UnsignedInteger() : Digits()
:Digits() {
{ } }
explicit UnsignedInteger(const char *str, size_t length) explicit UnsignedInteger(const char* str, size_t length) : Digits(str, length)
:Digits(str, length) {
{ } }
explicit UnsignedInteger(const ConstString &str) explicit UnsignedInteger(const ConstString& str) : Digits(str)
:Digits(str) {
{ } }
explicit UnsignedInteger(Parser *p) explicit UnsignedInteger(Parser* p) : Digits(p)
:Digits(p) {
{ } }
static UnsignedInteger empty(const Parser *p) static UnsignedInteger empty(const Parser* p)
{ {
return UnsignedInteger(p->tokStartConstString()); return UnsignedInteger(p->tokStartConstString());
} }
@ -249,182 +253,177 @@ public:
return UnsignedInteger(str(), length() > len ? len : length()); return UnsignedInteger(str(), length() > len ? len : length());
} }
template<typename T> template <typename T>
T toXIntPositiveContinue(T start, DataCondition & error) const T toXIntPositiveContinue(T start, DataCondition& error) const
{ {
const char *e = end(); const char* e = end();
T val = start; T val = start;
for (const char *s= mStr; s < e; s++) for (const char* s = mStr; s < e; s++)
{ {
constexpr T cutoff = datatypes::numeric_limits<T>::max() / 10; constexpr T cutoff = datatypes::numeric_limits<T>::max() / 10;
if (val > cutoff) if (val > cutoff)
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return datatypes::numeric_limits<T>::max(); return datatypes::numeric_limits<T>::max();
} }
val*= 10; val *= 10;
T newval = val + (s[0] - '0'); T newval = val + (s[0] - '0');
if (newval < val) if (newval < val)
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return datatypes::numeric_limits<T>::max(); return datatypes::numeric_limits<T>::max();
} }
val = newval; val = newval;
} }
return val; return val;
} }
template<typename T> template <typename T>
T toXIntPositive(DataCondition & error) const T toXIntPositive(DataCondition& error) const
{ {
return toXIntPositiveContinue<T>(0, error); return toXIntPositiveContinue<T>(0, error);
} }
template<typename T> template <typename T>
T toSIntNegativeContinue(T start, DataCondition & error) const T toSIntNegativeContinue(T start, DataCondition& error) const
{ {
const char *e = end(); const char* e = end();
T val = start; T val = start;
for (const char *s= mStr; s < e; s++) for (const char* s = mStr; s < e; s++)
{ {
constexpr T cutoff = datatypes::numeric_limits<T>::min() / 10; constexpr T cutoff = datatypes::numeric_limits<T>::min() / 10;
if (val < cutoff) if (val < cutoff)
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return datatypes::numeric_limits<T>::min(); return datatypes::numeric_limits<T>::min();
} }
val*= 10; val *= 10;
T newval = val - (s[0] - '0'); T newval = val - (s[0] - '0');
if (newval > val) if (newval > val)
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return datatypes::numeric_limits<T>::min(); return datatypes::numeric_limits<T>::min();
} }
val = newval; val = newval;
} }
return val; return val;
} }
template<typename T> template <typename T>
T toSIntNegative(DataCondition & error) const T toSIntNegative(DataCondition& error) const
{ {
return toSIntNegativeContinue<T>(0, error); return toSIntNegativeContinue<T>(0, error);
} }
template<typename T> template <typename T>
T toXIntPositiveRoundAwayFromZeroContinue(T start, bool round, DataCondition & error) const T toXIntPositiveRoundAwayFromZeroContinue(T start, bool round, DataCondition& error) const
{ {
T val = toXIntPositiveContinue<T>(start, error); T val = toXIntPositiveContinue<T>(start, error);
if (val == datatypes::numeric_limits<T>::max() && round) if (val == datatypes::numeric_limits<T>::max() && round)
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return val; return val;
} }
return val + round; return val + round;
} }
template<typename T> template <typename T>
T toXIntPositiveRoundAwayFromZero(bool round, DataCondition & error) const T toXIntPositiveRoundAwayFromZero(bool round, DataCondition& error) const
{ {
return toXIntPositiveRoundAwayFromZeroContinue<T>(0, round, error); return toXIntPositiveRoundAwayFromZeroContinue<T>(0, round, error);
} }
}; };
// <signed integer> := [<sign>] <unsigned integer> // <signed integer> := [<sign>] <unsigned integer>
class SignedInteger: public Parser::DD2OM<Sign,UnsignedInteger> class SignedInteger : public Parser::DD2OM<Sign, UnsignedInteger>
{ {
public: public:
using DD2OM::DD2OM; using DD2OM::DD2OM;
bool isNull() const { return UnsignedInteger::isNull(); } bool isNull() const
{
return UnsignedInteger::isNull();
}
template<typename T> T abs(DataCondition & error) const template <typename T>
T abs(DataCondition& error) const
{ {
return toXIntPositive<T>(error); return toXIntPositive<T>(error);
} }
template<typename T> T toSInt(DataCondition & error) const template <typename T>
T toSInt(DataCondition& error) const
{ {
return negative() ? return negative() ? toSIntNegative<T>(error) : toXIntPositive<T>(error);
toSIntNegative<T>(error) :
toXIntPositive<T>(error);
} }
}; };
// E <signed integer> // E <signed integer>
class EExponent: public Parser::UD2MM<ExponentMarker, SignedInteger> class EExponent : public Parser::UD2MM<ExponentMarker, SignedInteger>
{ {
public: public:
using UD2MM::UD2MM; using UD2MM::UD2MM;
}; };
// <period> <unsigned integer> // <period> <unsigned integer>
class ExactUnsignedNumericLiteralFractionAlone: public Parser::UD2MM<Period, UnsignedInteger> class ExactUnsignedNumericLiteralFractionAlone : public Parser::UD2MM<Period, UnsignedInteger>
{ {
public: public:
using UD2MM::UD2MM; using UD2MM::UD2MM;
}; };
// <period> [ <unsigned integer> ] // <period> [ <unsigned integer> ]
class PeriodOptUnsignedInteger: public Parser::UD2MO<Period, UnsignedInteger> class PeriodOptUnsignedInteger : public Parser::UD2MO<Period, UnsignedInteger>
{ {
public: public:
using UD2MO::UD2MO; using UD2MO::UD2MO;
static PeriodOptUnsignedInteger empty(Parser *p) static PeriodOptUnsignedInteger empty(Parser* p)
{ {
return PeriodOptUnsignedInteger(UnsignedInteger(p->tokStartConstString())); return PeriodOptUnsignedInteger(UnsignedInteger(p->tokStartConstString()));
} }
const PeriodOptUnsignedInteger & fraction() const const PeriodOptUnsignedInteger& fraction() const
{ {
return *this; return *this;
} }
}; };
// <integral unsigned integer> := <unsigned integer> // <integral unsigned integer> := <unsigned integer>
class IntegralUnsignedInteger: public UnsignedInteger class IntegralUnsignedInteger : public UnsignedInteger
{ {
public: public:
explicit IntegralUnsignedInteger(Parser *p) explicit IntegralUnsignedInteger(Parser* p) : UnsignedInteger(p)
:UnsignedInteger(p) {
{ } }
const UnsignedInteger & integral() const const UnsignedInteger& integral() const
{ {
return *this; return *this;
} }
}; };
// <integral unsigned integer> [ <period> [ <unsigned integer> ] ] // <integral unsigned integer> [ <period> [ <unsigned integer> ] ]
class ExactUnsignedNumericLiteralIntegralOptFraction: class ExactUnsignedNumericLiteralIntegralOptFraction
public Parser::DD2MO<IntegralUnsignedInteger, : public Parser::DD2MO<IntegralUnsignedInteger, PeriodOptUnsignedInteger>
PeriodOptUnsignedInteger>
{ {
public: public:
using DD2MO::DD2MO; using DD2MO::DD2MO;
}; };
// A container for integral and fractional parts // A container for integral and fractional parts
class UnsignedIntegerDecimal class UnsignedIntegerDecimal
{ {
protected: protected:
UnsignedInteger mIntegral; UnsignedInteger mIntegral;
UnsignedInteger mFraction; UnsignedInteger mFraction;
public:
explicit UnsignedIntegerDecimal(const UnsignedInteger &intg, public:
const UnsignedInteger &frac) explicit UnsignedIntegerDecimal(const UnsignedInteger& intg, const UnsignedInteger& frac)
:mIntegral(intg), : mIntegral(intg), mFraction(frac)
mFraction(frac) {
{ } }
explicit UnsignedIntegerDecimal(const ExactUnsignedNumericLiteralFractionAlone &rhs) explicit UnsignedIntegerDecimal(const ExactUnsignedNumericLiteralFractionAlone& rhs) : mFraction(rhs)
:mFraction(rhs) {
{ } }
explicit UnsignedIntegerDecimal(const ExactUnsignedNumericLiteralIntegralOptFraction &rhs) explicit UnsignedIntegerDecimal(const ExactUnsignedNumericLiteralIntegralOptFraction& rhs)
:mIntegral(rhs.integral()), : mIntegral(rhs.integral()), mFraction(rhs.fraction())
mFraction(rhs.fraction()) {
{ } }
size_t IntFracDigits() const size_t IntFracDigits() const
{ {
@ -442,44 +441,48 @@ public:
mFraction.skipTrailingZeroDigits(); mFraction.skipTrailingZeroDigits();
} }
template<typename T> T toXIntPositive(DataCondition & error) const template <typename T>
T toXIntPositive(DataCondition& error) const
{ {
T val = mIntegral.toXIntPositive<T>(error); T val = mIntegral.toXIntPositive<T>(error);
return mFraction.toXIntPositiveContinue<T>(val, error); return mFraction.toXIntPositiveContinue<T>(val, error);
} }
template<typename T> T toXIntPositiveRoundAwayFromZero(bool roundUp, DataCondition & error) const template <typename T>
T toXIntPositiveRoundAwayFromZero(bool roundUp, DataCondition& error) const
{ {
T val = mIntegral.toXIntPositive<T>(error); T val = mIntegral.toXIntPositive<T>(error);
return mFraction.toXIntPositiveRoundAwayFromZeroContinue<T>(val, roundUp, error); return mFraction.toXIntPositiveRoundAwayFromZeroContinue<T>(val, roundUp, error);
} }
template<typename T> T toXIntPositiveScaleUp(size_t scale, DataCondition & error) const template <typename T>
T toXIntPositiveScaleUp(size_t scale, DataCondition& error) const
{ {
T val = toXIntPositive<T>(error); T val = toXIntPositive<T>(error);
if (val == datatypes::numeric_limits<T>::max()) if (val == datatypes::numeric_limits<T>::max())
return val; return val;
for ( ; scale ; scale--) for (; scale; scale--)
{ {
constexpr T cutoff = datatypes::numeric_limits<T>::max() / 10; constexpr T cutoff = datatypes::numeric_limits<T>::max() / 10;
if (val > cutoff) if (val > cutoff)
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return datatypes::numeric_limits<T>::max(); return datatypes::numeric_limits<T>::max();
} }
val*= 10; val *= 10;
} }
return val; return val;
} }
template<typename T> T toXIntPositiveRound(DataCondition & error) const template <typename T>
T toXIntPositiveRound(DataCondition& error) const
{ {
bool roundUp = mFraction.length() && mFraction.str()[0] >= '5'; bool roundUp = mFraction.length() && mFraction.str()[0] >= '5';
return mIntegral.toXIntPositiveRoundAwayFromZero<T>(roundUp, error); return mIntegral.toXIntPositiveRoundAwayFromZero<T>(roundUp, error);
} }
template<typename T> T toXIntPositiveRoundExp(uint64_t absExp, bool negExp, template <typename T>
DataCondition & error) const T toXIntPositiveRoundExp(uint64_t absExp, bool negExp, DataCondition& error) const
{ {
if (absExp == 0) if (absExp == 0)
return toXIntPositiveRound<T>(error); return toXIntPositiveRound<T>(error);
@ -509,42 +512,38 @@ public:
size_t diff = absExp - mFraction.length(); size_t diff = absExp - mFraction.length();
return toXIntPositiveScaleUp<T>(diff, error); return toXIntPositiveScaleUp<T>(diff, error);
} }
}; };
// <exact unsigned numeric literal> := // <exact unsigned numeric literal> :=
// <period> [ <unsigned integer> ] // <period> [ <unsigned integer> ]
// | <unsigned integer> [ <period> [ <unsigned integer> ] ] // | <unsigned integer> [ <period> [ <unsigned integer> ] ]
class ExactUnsignedNumericLiteral: class ExactUnsignedNumericLiteral
public Parser::Choice2<UnsignedIntegerDecimal, : public Parser::Choice2<UnsignedIntegerDecimal, ExactUnsignedNumericLiteralFractionAlone,
ExactUnsignedNumericLiteralFractionAlone,
ExactUnsignedNumericLiteralIntegralOptFraction> ExactUnsignedNumericLiteralIntegralOptFraction>
{ {
public: public:
using Choice2::Choice2; using Choice2::Choice2;
}; };
// <unsigned numeric literal> ::= <exact numeric literal> [ E <exponent> ] // <unsigned numeric literal> ::= <exact numeric literal> [ E <exponent> ]
class UnsignedNumericLiteral: public Parser::DM2MO<ExactUnsignedNumericLiteral,EExponent> class UnsignedNumericLiteral : public Parser::DM2MO<ExactUnsignedNumericLiteral, EExponent>
{ {
public: public:
using DM2MO::DM2MO; using DM2MO::DM2MO;
void normalize() void normalize()
{ {
ExactUnsignedNumericLiteral::normalize(); ExactUnsignedNumericLiteral::normalize();
mB.skipLeadingZeroDigits(); mB.skipLeadingZeroDigits();
} }
const SignedInteger & exponent() const const SignedInteger& exponent() const
{ {
return mB; return mB;
} }
template<typename T> template <typename T>
T toXIntPositiveRound(DataCondition & error) const T toXIntPositiveRound(DataCondition& error) const
{ {
size_t availableDigits = IntFracDigits(); size_t availableDigits = IntFracDigits();
if (!availableDigits) if (!availableDigits)
@ -553,35 +552,36 @@ public:
return ExactUnsignedNumericLiteral::toXIntPositiveRoundExp<T>(absexp, exponent().negative(), error); return ExactUnsignedNumericLiteral::toXIntPositiveRoundExp<T>(absexp, exponent().negative(), error);
} }
template<typename T> template <typename T>
T toPackedDecimalPositive(scale_t scale, DataCondition & error) const T toPackedDecimalPositive(scale_t scale, DataCondition& error) const
{ {
size_t availableDigits = IntFracDigits(); size_t availableDigits = IntFracDigits();
if (!availableDigits) if (!availableDigits)
return 0; return 0;
int64_t exp = exponent().toSInt<int64_t>(error); int64_t exp = exponent().toSInt<int64_t>(error);
if (exp <= datatypes::numeric_limits<int64_t>::max() - scale) if (exp <= datatypes::numeric_limits<int64_t>::max() - scale)
exp+= scale; exp += scale;
if (exp < 0) if (exp < 0)
{ {
if (exp == datatypes::numeric_limits<int64_t>::min()) if (exp == datatypes::numeric_limits<int64_t>::min())
exp++; // Avoid undefined behaviour in the unary minus below: exp++; // Avoid undefined behaviour in the unary minus below:
return ExactUnsignedNumericLiteral::toXIntPositiveRoundExp<T>((uint64_t) -exp, true, error); return ExactUnsignedNumericLiteral::toXIntPositiveRoundExp<T>((uint64_t)-exp, true, error);
} }
return ExactUnsignedNumericLiteral::toXIntPositiveRoundExp<T>((uint64_t) exp, false, error); return ExactUnsignedNumericLiteral::toXIntPositiveRoundExp<T>((uint64_t)exp, false, error);
} }
}; };
// <signed numeric literal> ::= [ <sign> ] <unsigned numeric literal> // <signed numeric literal> ::= [ <sign> ] <unsigned numeric literal>
class SignedNumericLiteral: public Parser::DD2OM<Sign,UnsignedNumericLiteral> class SignedNumericLiteral : public Parser::DD2OM<Sign, UnsignedNumericLiteral>
{ {
public: public:
using DD2OM::DD2OM; using DD2OM::DD2OM;
bool isNull() const { return UnsignedNumericLiteral::isNull(); } bool isNull() const
{
return UnsignedNumericLiteral::isNull();
}
template<typename T> template <typename T>
T toUIntXRound() const T toUIntXRound() const
{ {
if (negative()) if (negative())
@ -589,30 +589,28 @@ public:
return UnsignedNumericLiteral::toXIntPositiveRound<T>(); return UnsignedNumericLiteral::toXIntPositiveRound<T>();
} }
template<typename T> template <typename T>
T toPackedUDecimal(scale_t scale, DataCondition & error) const T toPackedUDecimal(scale_t scale, DataCondition& error) const
{ {
if (negative()) if (negative())
return 0; return 0;
return UnsignedNumericLiteral::toPackedDecimalPositive<T>(scale, error); return UnsignedNumericLiteral::toPackedDecimalPositive<T>(scale, error);
} }
template<typename T> template <typename T>
T toPackedSDecimal(scale_t scale, DataCondition & error) const T toPackedSDecimal(scale_t scale, DataCondition& error) const
{ {
if (!negative()) if (!negative())
return UnsignedNumericLiteral::toPackedDecimalPositive<T>(scale, error); return UnsignedNumericLiteral::toPackedDecimalPositive<T>(scale, error);
typedef typename datatypes::make_unsigned<T>::type UT; typedef typename datatypes::make_unsigned<T>::type UT;
UT absval = UnsignedNumericLiteral::toPackedDecimalPositive<UT>(scale, error); UT absval = UnsignedNumericLiteral::toPackedDecimalPositive<UT>(scale, error);
if (absval >= (UT) datatypes::numeric_limits<T>::min()) if (absval >= (UT)datatypes::numeric_limits<T>::min())
{ {
error|= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE; error |= DataCondition::X_NUMERIC_VALUE_OUT_OF_RANGE;
return datatypes::numeric_limits<T>::min(); return datatypes::numeric_limits<T>::min();
} }
return - (T) absval; return -(T)absval;
} }
}; };
} // namespace literal } // namespace literal

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: altertable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: altertable.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -29,9 +29,8 @@ namespace ddlpackage
{ {
using namespace std; using namespace std;
AlterTableStatement::AlterTableStatement(QualifiedName* qName, AlterTableActionList* ataList): AlterTableStatement::AlterTableStatement(QualifiedName* qName, AlterTableActionList* ataList)
fTableName(qName), : fTableName(qName), fActions(*ataList)
fActions(*ataList)
{ {
delete ataList; delete ataList;
} }
@ -60,8 +59,6 @@ std::ostream& AlterTableStatement::put(std::ostream& os) const
return os; return os;
} }
/** @brief Format to ostream. Diagnostic. */ /** @brief Format to ostream. Diagnostic. */
std::ostream& AlterTableAction::put(std::ostream& os) const std::ostream& AlterTableAction::put(std::ostream& os) const
{ {
@ -76,13 +73,11 @@ std::ostream& operator<<(std::ostream& os, const AlterTableAction& ata)
return ata.put(os); return ata.put(os);
} }
AtaAddColumn::~AtaAddColumn() AtaAddColumn::~AtaAddColumn()
{ {
delete fColumnDef; delete fColumnDef;
} }
/** @brief ostream output */ /** @brief ostream output */
std::ostream& AtaAddColumn::put(std::ostream& os) const std::ostream& AtaAddColumn::put(std::ostream& os) const
{ {
@ -91,22 +86,17 @@ std::ostream& AtaAddColumn::put(std::ostream& os) const
return os; return os;
} }
AtaDropColumn::AtaDropColumn(std::string columnName, DDL_REFERENTIAL_ACTION dropBehavior)
: fColumnName(columnName), fDropBehavior(dropBehavior)
AtaDropColumn::AtaDropColumn(std::string columnName, DDL_REFERENTIAL_ACTION dropBehavior) :
fColumnName(columnName),
fDropBehavior(dropBehavior)
{ {
} }
std::ostream& AtaDropColumn::put(std::ostream& os) const std::ostream& AtaDropColumn::put(std::ostream& os) const
{ {
os << "Drop Column: " << fColumnName << " " os << "Drop Column: " << fColumnName << " " << ReferentialActionStrings[fDropBehavior];
<< ReferentialActionStrings[fDropBehavior];
return os; return os;
} }
AtaModifyColumnType::~AtaModifyColumnType() AtaModifyColumnType::~AtaModifyColumnType()
{ {
delete fColumnType; delete fColumnType;
@ -119,8 +109,6 @@ std::ostream& AtaModifyColumnType::put(std::ostream& os) const
return os; return os;
} }
AtaRenameColumn::~AtaRenameColumn() AtaRenameColumn::~AtaRenameColumn()
{ {
delete fNewType; delete fNewType;
@ -132,33 +120,23 @@ std::ostream& AtaRenameColumn::put(std::ostream& os) const
return os; return os;
} }
AtaSetColumnDefault::AtaSetColumnDefault(const char* colName, ColumnDefaultValue* defaultValue)
: fColumnName(colName), fDefaultValue(defaultValue)
AtaSetColumnDefault::AtaSetColumnDefault(const char* colName, ColumnDefaultValue* defaultValue) :
fColumnName(colName),
fDefaultValue(defaultValue)
{ {
} }
AtaSetColumnDefault::~AtaSetColumnDefault() AtaSetColumnDefault::~AtaSetColumnDefault()
{ {
delete fDefaultValue; delete fDefaultValue;
} }
std::ostream& AtaSetColumnDefault::put(std::ostream& os) const std::ostream& AtaSetColumnDefault::put(std::ostream& os) const
{ {
os << "Set Column Default: " << fColumnName << " " os << "Set Column Default: " << fColumnName << " " << *fDefaultValue << endl;
<< *fDefaultValue << endl;
return os; return os;
} }
AtaDropColumnDefault::AtaDropColumnDefault(const char* colName) : fColumnName(colName)
AtaDropColumnDefault::AtaDropColumnDefault(const char* colName) :
fColumnName(colName)
{ {
} }
@ -168,11 +146,7 @@ std::ostream& AtaDropColumnDefault::put(std::ostream& os) const
return os; return os;
} }
AtaRenameTable::AtaRenameTable(QualifiedName* qualifiedName) : fQualifiedName(qualifiedName)
AtaRenameTable::AtaRenameTable(QualifiedName* qualifiedName) :
fQualifiedName(qualifiedName)
{ {
} }
@ -181,17 +155,13 @@ AtaRenameTable::~AtaRenameTable()
delete fQualifiedName; delete fQualifiedName;
} }
std::ostream& AtaRenameTable::put(std::ostream& os) const std::ostream& AtaRenameTable::put(std::ostream& os) const
{ {
os << "Rename Table: " << *fQualifiedName << endl; os << "Rename Table: " << *fQualifiedName << endl;
return os; return os;
} }
AtaTableComment::AtaTableComment(const char* tableComment) : fTableComment(tableComment)
AtaTableComment::AtaTableComment(const char* tableComment) :
fTableComment(tableComment)
{ {
} }
@ -199,14 +169,12 @@ AtaTableComment::~AtaTableComment()
{ {
} }
std::ostream& AtaTableComment::put(std::ostream& os) const std::ostream& AtaTableComment::put(std::ostream& os) const
{ {
os << "TableComment: " << fTableComment << endl; os << "TableComment: " << fTableComment << endl;
return os; return os;
} }
AtaAddColumns::~AtaAddColumns() AtaAddColumns::~AtaAddColumns()
{ {
ColumnDefList::iterator itr; ColumnDefList::iterator itr;
@ -215,7 +183,6 @@ AtaAddColumns::~AtaAddColumns()
delete *itr; delete *itr;
} }
AtaAddColumns::AtaAddColumns(TableElementList* tableElements) AtaAddColumns::AtaAddColumns(TableElementList* tableElements)
{ {
/* It is convenient to reuse the grammar rules for /* It is convenient to reuse the grammar rules for
@ -226,9 +193,7 @@ AtaAddColumns::AtaAddColumns(TableElementList* tableElements)
ColumnDef* column; ColumnDef* column;
TableElementList::const_iterator itr; TableElementList::const_iterator itr;
for (itr = tableElements->begin(); for (itr = tableElements->begin(); itr != tableElements->end(); ++itr)
itr != tableElements->end();
++itr)
{ {
column = dynamic_cast<ColumnDef*>(*itr); column = dynamic_cast<ColumnDef*>(*itr);
@ -246,9 +211,7 @@ std::ostream& AtaAddColumns::put(std::ostream& os) const
os << "Add Columns: " << endl; os << "Add Columns: " << endl;
ColumnDefList::const_iterator itr; ColumnDefList::const_iterator itr;
for (itr = fColumns.begin(); for (itr = fColumns.begin(); itr != fColumns.end(); ++itr)
itr != fColumns.end();
++itr)
{ {
os << **itr << endl; os << **itr << endl;
} }
@ -261,7 +224,6 @@ AtaDropColumns::~AtaDropColumns()
{ {
} }
AtaDropColumns::AtaDropColumns(ColumnNameList* columnNames) AtaDropColumns::AtaDropColumns(ColumnNameList* columnNames)
{ {
fColumns = *columnNames; fColumns = *columnNames;
@ -273,9 +235,7 @@ std::ostream& AtaDropColumns::put(std::ostream& os) const
os << "Drop Columns: " << endl; os << "Drop Columns: " << endl;
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
for (itr = fColumns.begin(); for (itr = fColumns.begin(); itr != fColumns.end(); ++itr)
itr != fColumns.end();
++itr)
{ {
os << *itr << endl; os << *itr << endl;
} }
@ -283,11 +243,8 @@ std::ostream& AtaDropColumns::put(std::ostream& os) const
return os; return os;
} }
AtaAddTableConstraint::AtaAddTableConstraint(TableConstraintDef* tableConstraint)
: fTableConstraint(tableConstraint)
AtaAddTableConstraint::AtaAddTableConstraint(TableConstraintDef* tableConstraint) :
fTableConstraint(tableConstraint)
{ {
} }
@ -296,7 +253,6 @@ AtaAddTableConstraint::~AtaAddTableConstraint()
delete fTableConstraint; delete fTableConstraint;
} }
std::ostream& AtaAddTableConstraint::put(std::ostream& os) const std::ostream& AtaAddTableConstraint::put(std::ostream& os) const
{ {
os << "Add Table Constraint:" << endl; os << "Add Table Constraint:" << endl;
@ -304,13 +260,9 @@ std::ostream& AtaAddTableConstraint::put(std::ostream& os) const
return os; return os;
} }
AtaDropTableConstraint::AtaDropTableConstraint(const char* constraintName,
DDL_REFERENTIAL_ACTION dropBehavior)
: fConstraintName(constraintName), fDropBehavior(dropBehavior)
AtaDropTableConstraint::AtaDropTableConstraint
(const char* constraintName, DDL_REFERENTIAL_ACTION dropBehavior) :
fConstraintName(constraintName),
fDropBehavior(dropBehavior)
{ {
} }
@ -320,4 +272,4 @@ std::ostream& AtaDropTableConstraint::put(std::ostream& os) const
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: columndef.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: columndef.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <iostream> #include <iostream>
#include <iomanip> #include <iomanip>
@ -30,7 +30,6 @@
namespace ddlpackage namespace ddlpackage
{ {
using namespace std; using namespace std;
ColumnDef::~ColumnDef() ColumnDef::~ColumnDef()
@ -46,10 +45,8 @@ ColumnDef::~ColumnDef()
} }
ColumnDef::ColumnDef(const char* name, ColumnType* columnType, ColumnConstraintList* constraints, ColumnDef::ColumnDef(const char* name, ColumnType* columnType, ColumnConstraintList* constraints,
ColumnDefaultValue* defaultValue, const char* comment ) : ColumnDefaultValue* defaultValue, const char* comment)
SchemaObject(name), : SchemaObject(name), fType(columnType), fDefaultValue(defaultValue)
fType(columnType),
fDefaultValue(defaultValue)
{ {
if (constraints) if (constraints)
{ {
@ -57,24 +54,20 @@ ColumnDef::ColumnDef(const char* name, ColumnType* columnType, ColumnConstraintL
delete constraints; delete constraints;
} }
if ( comment ) if (comment)
fComment = comment; fComment = comment;
} }
ostream& operator<<(ostream& os, const ColumnType& columnType) ostream& operator<<(ostream& os, const ColumnType& columnType)
{ {
os << setw(12) << left << DDLDatatypeString[columnType.fType] os << setw(12) << left << DDLDatatypeString[columnType.fType] << "["
<< "["
<< "L=" << setw(2) << columnType.fLength << "," << "L=" << setw(2) << columnType.fLength << ","
<< "P=" << setw(2) << columnType.fPrecision << "," << "P=" << setw(2) << columnType.fPrecision << ","
<< "S=" << setw(2) << columnType.fScale << "," << "S=" << setw(2) << columnType.fScale << ","
<< "T=" << setw(2) << columnType.fWithTimezone << "T=" << setw(2) << columnType.fWithTimezone << "]";
<< "]";
return os; return os;
} }
ostream& operator<<(ostream& os, const ColumnDef& column) ostream& operator<<(ostream& os, const ColumnDef& column)
{ {
os << "Column: " << column.fName << " " << *column.fType; os << "Column: " << column.fName << " " << *column.fType;
@ -89,35 +82,27 @@ ostream& operator<<(ostream& os, const ColumnDef& column)
os << column.fDefaultValue->fValue; os << column.fDefaultValue->fValue;
} }
os << endl << " " << column.fConstraints.size() os << endl << " " << column.fConstraints.size() << " constraints ";
<< " constraints ";
ColumnConstraintList::const_iterator itr; ColumnConstraintList::const_iterator itr;
for (itr = column.fConstraints.begin(); for (itr = column.fConstraints.begin(); itr != column.fConstraints.end(); ++itr)
itr != column.fConstraints.end();
++itr)
{ {
ColumnConstraintDef* con = *itr; ColumnConstraintDef* con = *itr;
os << *con; os << *con;
} }
return os; return os;
} }
ostream& operator<<(ostream& os, const ColumnConstraintDef& con) ostream& operator<<(ostream& os, const ColumnConstraintDef& con)
{ {
os << " Constraint: " os << " Constraint: " << con.fName << " " << ConstraintString[con.fConstraintType] << " "
<< con.fName << " " << "defer=" << con.fDeferrable << " " << ConstraintAttrStrings[con.fCheckTime] << " ";
<< ConstraintString[con.fConstraintType] << " "
<< "defer=" << con.fDeferrable << " "
<< ConstraintAttrStrings[con.fCheckTime] << " ";
if (!con.fCheck.empty()) if (!con.fCheck.empty())
os << "check=" << "\"" << con.fCheck << "\""; os << "check="
<< "\"" << con.fCheck << "\"";
return os; return os;
} }
@ -134,9 +119,7 @@ std::ostream& operator<<(std::ostream& os, const ColumnDefList& clist)
return os; return os;
} }
ColumnDefaultValue::ColumnDefaultValue(const char* value) : fNull(false)
ColumnDefaultValue::ColumnDefaultValue(const char* value) :
fNull(false)
{ {
if (0 == value) if (0 == value)
fNull = true; fNull = true;
@ -144,7 +127,6 @@ ColumnDefaultValue::ColumnDefaultValue(const char* value) :
fValue = value; fValue = value;
} }
std::ostream& operator<<(std::ostream& os, const ColumnDefaultValue& defaultValue) std::ostream& operator<<(std::ostream& os, const ColumnDefaultValue& defaultValue)
{ {
os << " def="; os << " def=";
@ -157,4 +139,4 @@ std::ostream& operator<<(std::ostream& os, const ColumnDefaultValue& defaultValu
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: createindex.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: createindex.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "ddlpkg.h" #include "ddlpkg.h"
@ -27,20 +27,14 @@ namespace ddlpackage
{ {
using namespace std; using namespace std;
CreateIndexStatement::CreateIndexStatement(): CreateIndexStatement::CreateIndexStatement()
fIndexName(NULL), : fIndexName(NULL), fTableName(NULL), fColumnNames(), fUnique(false)
fTableName(NULL),
fColumnNames(),
fUnique(false)
{ {
} }
CreateIndexStatement::CreateIndexStatement(QualifiedName* indexName, QualifiedName* tableName, CreateIndexStatement::CreateIndexStatement(QualifiedName* indexName, QualifiedName* tableName,
ColumnNameList* columnNames, bool unique) : ColumnNameList* columnNames, bool unique)
fIndexName(indexName), : fIndexName(indexName), fTableName(tableName), fColumnNames(*columnNames), fUnique(unique)
fTableName(tableName),
fColumnNames(*columnNames),
fUnique(unique)
{ {
delete columnNames; delete columnNames;
} }
@ -53,9 +47,8 @@ CreateIndexStatement::~CreateIndexStatement()
std::ostream& CreateIndexStatement::put(std::ostream& os) const std::ostream& CreateIndexStatement::put(std::ostream& os) const
{ {
os << "Create Index: " << *fIndexName << " on " << *fTableName os << "Create Index: " << *fIndexName << " on " << *fTableName << fColumnNames << endl;
<< fColumnNames << endl;
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: createtable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: createtable.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <iostream> #include <iostream>
@ -29,20 +29,16 @@
namespace ddlpackage namespace ddlpackage
{ {
using namespace std; using namespace std;
CreateTableStatement::CreateTableStatement() : CreateTableStatement::CreateTableStatement() : fTableDef(0)
fTableDef(0)
{ {
} }
CreateTableStatement::CreateTableStatement(TableDef* tableDef) : CreateTableStatement::CreateTableStatement(TableDef* tableDef) : fTableDef(tableDef)
fTableDef(tableDef)
{ {
} }
CreateTableStatement::~CreateTableStatement() CreateTableStatement::~CreateTableStatement()
{ {
if (fTableDef) if (fTableDef)
@ -54,8 +50,7 @@ CreateTableStatement::~CreateTableStatement()
/** \brief Put to ostream. */ /** \brief Put to ostream. */
ostream& CreateTableStatement::put(ostream& os) const ostream& CreateTableStatement::put(ostream& os) const
{ {
os << "CreateTable " os << "CreateTable " << *fTableDef;
<< *fTableDef;
return os; return os;
} }
} } // namespace ddlpackage

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,6 @@
This special exception was added by the Free Software Foundation in This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */ version 2.2 of Bison. */
/* Tokens. */ /* Tokens. */
#pragma once #pragma once
/* Put the tokens into the symbol table, so that GDB and other debuggers /* Put the tokens into the symbol table, so that GDB and other debuggers
@ -125,13 +124,9 @@ enum yytokentype
}; };
#endif #endif
#if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE typedef union YYSTYPE
{ {
ddlpackage::AlterTableStatement* alterTableStmt; ddlpackage::AlterTableStatement* alterTableStmt;
ddlpackage::AlterTableAction* ata; ddlpackage::AlterTableAction* ata;
ddlpackage::AlterTableActionList* ataList; ddlpackage::AlterTableActionList* ataList;
@ -160,13 +155,9 @@ typedef union YYSTYPE
ddlpackage::DDL_REFERENTIAL_ACTION refActionCode; ddlpackage::DDL_REFERENTIAL_ACTION refActionCode;
ddlpackage::ReferentialAction* refAction; ddlpackage::ReferentialAction* refAction;
} YYSTYPE; } YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1 #define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */ #define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1 #define YYSTYPE_IS_DECLARED 1
extern YYSTYPE ddllval; extern YYSTYPE ddllval;

File diff suppressed because it is too large Load Diff

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: ddlpkg.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: ddlpkg.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <iostream> #include <iostream>
@ -32,21 +32,16 @@ namespace ddlpackage
{ {
using namespace std; using namespace std;
QualifiedName::QualifiedName(const char* name): QualifiedName::QualifiedName(const char* name) : fName(name)
fName(name)
{ {
} }
QualifiedName::QualifiedName(const char* schema, const char* name): QualifiedName::QualifiedName(const char* schema, const char* name) : fName(name), fSchema(schema)
fName(name),
fSchema(schema)
{ {
} }
QualifiedName::QualifiedName(const char* catalog, const char* schema, const char* name): QualifiedName::QualifiedName(const char* catalog, const char* schema, const char* name)
fCatalog(catalog), : fCatalog(catalog), fName(name), fSchema(schema)
fName(name),
fSchema(schema)
{ {
} }
@ -62,85 +57,58 @@ ostream& operator<<(ostream& os, const QualifiedName& qname)
return os; return os;
} }
ColumnType::ColumnType(int prec, int scale) : ColumnType::ColumnType(int prec, int scale)
fType(DDL_INVALID_DATATYPE), : fType(DDL_INVALID_DATATYPE)
fLength(0), , fLength(0)
fPrecision(prec), , fPrecision(prec)
fScale(scale), , fScale(scale)
fWithTimezone(false), , fWithTimezone(false)
fCharset(NULL), , fCharset(NULL)
fExplicitLength(false) , fExplicitLength(false)
{ {
fLength = utils::widthByPrecision(fPrecision); fLength = utils::widthByPrecision(fPrecision);
} }
ColumnType::ColumnType(int type) : ColumnType::ColumnType(int type)
fType(type), : fType(type), fLength(0), fScale(0), fWithTimezone(false), fCharset(NULL), fExplicitLength(false)
fLength(0),
fScale(0),
fWithTimezone(false),
fCharset(NULL),
fExplicitLength(false)
{ {
switch ( type ) switch (type)
{ {
case DDL_TINYINT: case DDL_TINYINT:
case DDL_UNSIGNED_TINYINT: case DDL_UNSIGNED_TINYINT: fPrecision = 3; break;
fPrecision = 3;
break;
case DDL_SMALLINT: case DDL_SMALLINT:
case DDL_UNSIGNED_SMALLINT: case DDL_UNSIGNED_SMALLINT: fPrecision = 5; break;
fPrecision = 5;
break;
case DDL_MEDINT: case DDL_MEDINT: fPrecision = 7; break;
fPrecision = 7;
break;
case DDL_UNSIGNED_MEDINT: case DDL_UNSIGNED_MEDINT: fPrecision = 8; break;
fPrecision = 8;
break;
case DDL_INT: case DDL_INT:
case DDL_UNSIGNED_INT: case DDL_UNSIGNED_INT: fPrecision = 10; break;
fPrecision = 10;
break;
case DDL_BIGINT: case DDL_BIGINT: fPrecision = 19; break;
fPrecision = 19;
break;
case DDL_UNSIGNED_BIGINT: case DDL_UNSIGNED_BIGINT: fPrecision = 20; break;
fPrecision = 20;
break;
default: default: fPrecision = 10; break;
fPrecision = 10;
break;
} }
} }
ColumnConstraintDef::ColumnConstraintDef(DDL_CONSTRAINTS type) : ColumnConstraintDef::ColumnConstraintDef(DDL_CONSTRAINTS type)
SchemaObject(), : SchemaObject(), fDeferrable(false), fCheckTime(DDL_INITIALLY_IMMEDIATE), fConstraintType(type), fCheck("")
fDeferrable(false),
fCheckTime(DDL_INITIALLY_IMMEDIATE),
fConstraintType(type),
fCheck("")
{ {
} }
ColumnConstraintDef::ColumnConstraintDef(const char* check) : ColumnConstraintDef::ColumnConstraintDef(const char* check)
SchemaObject(), : SchemaObject()
fDeferrable(false), , fDeferrable(false)
fCheckTime(DDL_INITIALLY_IMMEDIATE), , fCheckTime(DDL_INITIALLY_IMMEDIATE)
fConstraintType(DDL_CHECK), , fConstraintType(DDL_CHECK)
fCheck(check) , fCheck(check)
{ {
} }
AtaAddColumn::AtaAddColumn(ColumnDef* columnDef) : fColumnDef(columnDef)
AtaAddColumn::AtaAddColumn(ColumnDef* columnDef) :
fColumnDef(columnDef)
{ {
} }
@ -195,4 +163,4 @@ void ColumnDef::convertDecimal()
fType->fLength = 16; fType->fLength = 16;
} }
} }
} // end of namespace } // namespace ddlpackage

File diff suppressed because it is too large Load Diff

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dropindex.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dropindex.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "ddlpkg.h" #include "ddlpkg.h"
@ -32,8 +32,7 @@ DropIndexStatement::~DropIndexStatement()
delete fIndexName; delete fIndexName;
} }
DropIndexStatement::DropIndexStatement(QualifiedName* qualifiedName) : DropIndexStatement::DropIndexStatement(QualifiedName* qualifiedName) : fIndexName(qualifiedName)
fIndexName(qualifiedName)
{ {
} }
@ -43,4 +42,4 @@ std::ostream& DropIndexStatement::put(std::ostream& os) const
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: markpartition.cpp 6566 2010-04-27 18:02:51Z rdempsey $ * $Id: markpartition.cpp 6566 2010-04-27 18:02:51Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -29,9 +29,7 @@ using namespace std;
namespace ddlpackage namespace ddlpackage
{ {
DropPartitionStatement::DropPartitionStatement(QualifiedName* qualifiedName) : fTableName(qualifiedName)
DropPartitionStatement::DropPartitionStatement(QualifiedName* qualifiedName) :
fTableName(qualifiedName)
{ {
} }
@ -48,4 +46,4 @@ ostream& DropPartitionStatement::put(ostream& os) const
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: droptable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: droptable.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -29,21 +29,19 @@ using namespace std;
namespace ddlpackage namespace ddlpackage
{ {
DropTableStatement::DropTableStatement(QualifiedName* qualifiedName, bool cascade)
DropTableStatement::DropTableStatement(QualifiedName* qualifiedName, bool cascade) : : fTableName(qualifiedName), fCascade(cascade)
fTableName(qualifiedName),
fCascade(cascade)
{ {
} }
ostream& DropTableStatement::put(ostream& os) const ostream& DropTableStatement::put(ostream& os) const
{ {
os << "Drop Table: " << *fTableName << " " << "C=" << fCascade << endl; os << "Drop Table: " << *fTableName << " "
<< "C=" << fCascade << endl;
return os; return os;
} }
TruncTableStatement::TruncTableStatement(QualifiedName* qualifiedName) : TruncTableStatement::TruncTableStatement(QualifiedName* qualifiedName) : fTableName(qualifiedName)
fTableName(qualifiedName)
{ {
} }
@ -53,4 +51,4 @@ ostream& TruncTableStatement::put(ostream& os) const
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -34,26 +34,26 @@ int main(int argc, char* argv[])
string sqlfile; string sqlfile;
int count; int count;
po::options_description desc ("Allowed options"); po::options_description desc("Allowed options");
desc.add_options () desc.add_options()("help", "produce help message")(
("help", "produce help message") "bisond",
("bisond", /* po::value <string>(),*/ "Have bison produce debug output") /* po::value <string>(),*/ "Have bison produce debug output")("count", po::value<int>(),
("count", po::value <int>(), "number of runs") "number of runs")("sql",
("sql", po::value < string > (), "sql file"); po::value<string>(),
"sql file");
po::variables_map vm; po::variables_map vm;
po::store (po::parse_command_line (argc, argv, desc), vm); po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify (vm); po::notify(vm);
if (vm.count ("sql"))
sqlfile = vm["sql"].as <string> ();
if (vm.count("sql"))
sqlfile = vm["sql"].as<string>();
if (vm.count("count")) if (vm.count("count"))
count = vm["count"].as<int>(); count = vm["count"].as<int>();
SqlFileParser parser; SqlFileParser parser;
if (vm.count ("bisond")) if (vm.count("bisond"))
parser.SetDebug(true); parser.SetDebug(true);
parser.Parse(sqlfile); parser.Parse(sqlfile);
@ -63,7 +63,8 @@ int main(int argc, char* argv[])
const ParseTree& ptree = parser.GetParseTree(); const ParseTree& ptree = parser.GetParseTree();
cout << "Parser succeeded." << endl; cout << "Parser succeeded." << endl;
cout << ptree.fList.size() << " " << "SQL statements" << endl; cout << ptree.fList.size() << " "
<< "SQL statements" << endl;
cout << ptree; cout << ptree;
cout << endl; cout << endl;
} }
@ -74,5 +75,3 @@ int main(int argc, char* argv[])
return parser.Good() ? 0 : -1; return parser.Good() ? 0 : -1;
} }

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: markpartition.cpp 6566 2010-04-27 18:02:51Z rdempsey $ * $Id: markpartition.cpp 6566 2010-04-27 18:02:51Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -29,9 +29,7 @@ using namespace std;
namespace ddlpackage namespace ddlpackage
{ {
MarkPartitionStatement::MarkPartitionStatement(QualifiedName* qualifiedName) : fTableName(qualifiedName)
MarkPartitionStatement::MarkPartitionStatement(QualifiedName* qualifiedName) :
fTableName(qualifiedName)
{ {
} }
@ -48,4 +46,4 @@ ostream& MarkPartitionStatement::put(ostream& os) const
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -41,7 +41,6 @@
#include "dropobjectddlpackage.h" #include "dropobjectddlpackage.h"
#include "messagequeue.h" #include "messagequeue.h"
using namespace std; using namespace std;
using namespace ddlpackage; using namespace ddlpackage;
using namespace messageqcpp; using namespace messageqcpp;
@ -52,80 +51,73 @@ std::string itoa(const int i);
class DDLWriteReadTest : public CppUnit::TestFixture class DDLWriteReadTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DDLWriteReadTest);
CPPUNIT_TEST_SUITE( DDLWriteReadTest ); CPPUNIT_TEST(test_write_read_create_table_object);
CPPUNIT_TEST(test_write_read_create_index_object);
CPPUNIT_TEST( test_write_read_create_table_object ); CPPUNIT_TEST(test_write_read_alter_table_object);
CPPUNIT_TEST( test_write_read_create_index_object ); CPPUNIT_TEST(test_write_read_drop_table_object);
CPPUNIT_TEST( test_write_read_alter_table_object ); CPPUNIT_TEST(test_write_read_drop_index_object);
CPPUNIT_TEST( test_write_read_drop_table_object );
CPPUNIT_TEST( test_write_read_drop_index_object );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
public:
void setUp() void setUp()
{ {
} }
void tearDown() void tearDown()
{ {
} }
// CREATE TABLE // CREATE TABLE
void test_write_read_create_table_object() void test_write_read_create_table_object()
{ {
ByteStream bytestream; ByteStream bytestream;
std::string ddl_statement = "CREATE TABLE calpont.PART(p_partkey int not null, p_a varchar(55), p_b decimal(8,2) unique, p_c int default 1, p_d varchar(25) default 'unknown' check (varchar = 'a' ), foreign key (p_partkey) references Customers(p_partkey)) engine=infinidb;"; std::string ddl_statement =
"CREATE TABLE calpont.PART(p_partkey int not null, p_a varchar(55), p_b decimal(8,2) unique, p_c int "
"default 1, p_d varchar(25) default 'unknown' check (varchar = 'a' ), foreign key (p_partkey) "
"references Customers(p_partkey)) engine=infinidb;";
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
CPPUNIT_ASSERT( 0 != pDDLStatement ); CPPUNIT_ASSERT(0 != pDDLStatement);
pDDLStatement->populateFromDDLStatement( ddl_statement ); pDDLStatement->populateFromDDLStatement(ddl_statement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
CPPUNIT_ASSERT( 0 != pDDLPackage ); CPPUNIT_ASSERT(0 != pDDLPackage);
// parse the data // parse the data
pDDLPackage->Parse(); pDDLPackage->Parse();
write_create_table_object( bytestream, pDDLPackage ); write_create_table_object(bytestream, pDDLPackage);
delete pDDLStatement; delete pDDLStatement;
delete pDDLPackage; delete pDDLPackage;
read_create_table_object( bytestream ); read_create_table_object(bytestream);
} }
void write_create_table_object( ByteStream& bs, CalpontDDLPackage* pDDLPackage ) void write_create_table_object(ByteStream& bs, CalpontDDLPackage* pDDLPackage)
{ {
pDDLPackage->Write(bs);
pDDLPackage->Write( bs );
} }
void read_create_table_object( ByteStream& bs ) void read_create_table_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DDL_CREATE == package_type ); CPPUNIT_ASSERT(DDL_CREATE == package_type);
CreateObjectDDLPackage* pObject = new CreateObjectDDLPackage(); CreateObjectDDLPackage* pObject = new CreateObjectDDLPackage();
pObject->Read( bs ); pObject->Read(bs);
delete pObject; delete pObject;
} }
// CREATE INDEX // CREATE INDEX
@ -137,46 +129,42 @@ public:
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
CPPUNIT_ASSERT( 0 != pDDLStatement ); CPPUNIT_ASSERT(0 != pDDLStatement);
pDDLStatement->populateFromDDLStatement( ddl_statement ); pDDLStatement->populateFromDDLStatement(ddl_statement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
CPPUNIT_ASSERT( 0 != pDDLPackage ); CPPUNIT_ASSERT(0 != pDDLPackage);
// parse the data // parse the data
pDDLPackage->Parse(); pDDLPackage->Parse();
write_create_index_object( bytestream, pDDLPackage ); write_create_index_object(bytestream, pDDLPackage);
delete pDDLStatement; delete pDDLStatement;
delete pDDLPackage; delete pDDLPackage;
read_create_index_object( bytestream ); read_create_index_object(bytestream);
} }
void write_create_index_object( ByteStream& bs, CalpontDDLPackage* pDDLPackage ) void write_create_index_object(ByteStream& bs, CalpontDDLPackage* pDDLPackage)
{ {
pDDLPackage->Write(bs);
pDDLPackage->Write( bs );
} }
void read_create_index_object( ByteStream& bs ) void read_create_index_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DDL_CREATE == package_type ); CPPUNIT_ASSERT(DDL_CREATE == package_type);
CreateObjectDDLPackage* pObject = new CreateObjectDDLPackage(); CreateObjectDDLPackage* pObject = new CreateObjectDDLPackage();
pObject->Read( bs ); pObject->Read(bs);
delete pObject; delete pObject;
} }
// ALTER TABLE // ALTER TABLE
@ -188,46 +176,42 @@ public:
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
CPPUNIT_ASSERT( 0 != pDDLStatement ); CPPUNIT_ASSERT(0 != pDDLStatement);
pDDLStatement->populateFromDDLStatement( ddl_statement ); pDDLStatement->populateFromDDLStatement(ddl_statement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
CPPUNIT_ASSERT( 0 != pDDLPackage ); CPPUNIT_ASSERT(0 != pDDLPackage);
// parse the data // parse the data
pDDLPackage->Parse(); pDDLPackage->Parse();
write_alter_table_object( bytestream, pDDLPackage ); write_alter_table_object(bytestream, pDDLPackage);
delete pDDLStatement; delete pDDLStatement;
delete pDDLPackage; delete pDDLPackage;
read_alter_table_object( bytestream ); read_alter_table_object(bytestream);
} }
void write_alter_table_object( ByteStream& bs, CalpontDDLPackage* pDDLPackage ) void write_alter_table_object(ByteStream& bs, CalpontDDLPackage* pDDLPackage)
{ {
pDDLPackage->Write(bs);
pDDLPackage->Write( bs );
} }
void read_alter_table_object( ByteStream& bs ) void read_alter_table_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DDL_ALTER == package_type ); CPPUNIT_ASSERT(DDL_ALTER == package_type);
AlterObjectDDLPackage* pObject = new AlterObjectDDLPackage(); AlterObjectDDLPackage* pObject = new AlterObjectDDLPackage();
pObject->Read( bs ); pObject->Read(bs);
delete pObject; delete pObject;
} }
// DROP TABLE // DROP TABLE
@ -239,46 +223,42 @@ public:
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
CPPUNIT_ASSERT( 0 != pDDLStatement ); CPPUNIT_ASSERT(0 != pDDLStatement);
pDDLStatement->populateFromDDLStatement( ddl_statement ); pDDLStatement->populateFromDDLStatement(ddl_statement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
CPPUNIT_ASSERT( 0 != pDDLPackage ); CPPUNIT_ASSERT(0 != pDDLPackage);
// parse the data // parse the data
pDDLPackage->Parse(); pDDLPackage->Parse();
write_drop_table_object( bytestream, pDDLPackage ); write_drop_table_object(bytestream, pDDLPackage);
delete pDDLStatement; delete pDDLStatement;
delete pDDLPackage; delete pDDLPackage;
read_drop_table_object( bytestream ); read_drop_table_object(bytestream);
} }
void write_drop_table_object( ByteStream& bs, CalpontDDLPackage* pDDLPackage ) void write_drop_table_object(ByteStream& bs, CalpontDDLPackage* pDDLPackage)
{ {
pDDLPackage->Write(bs);
pDDLPackage->Write( bs );
} }
void read_drop_table_object( ByteStream& bs ) void read_drop_table_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DDL_DROP == package_type ); CPPUNIT_ASSERT(DDL_DROP == package_type);
DropObjectDDLPackage* pObject = new DropObjectDDLPackage(); DropObjectDDLPackage* pObject = new DropObjectDDLPackage();
pObject->Read( bs ); pObject->Read(bs);
delete pObject; delete pObject;
} }
// DROP INDEX // DROP INDEX
@ -290,65 +270,57 @@ public:
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
CPPUNIT_ASSERT( 0 != pDDLStatement ); CPPUNIT_ASSERT(0 != pDDLStatement);
pDDLStatement->populateFromDDLStatement( ddl_statement ); pDDLStatement->populateFromDDLStatement(ddl_statement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
CPPUNIT_ASSERT( 0 != pDDLPackage ); CPPUNIT_ASSERT(0 != pDDLPackage);
// parse the data // parse the data
pDDLPackage->Parse(); pDDLPackage->Parse();
write_drop_index_object( bytestream, pDDLPackage ); write_drop_index_object(bytestream, pDDLPackage);
delete pDDLStatement; delete pDDLStatement;
delete pDDLPackage; delete pDDLPackage;
read_drop_index_object( bytestream ); read_drop_index_object(bytestream);
} }
void write_drop_index_object( ByteStream& bs, CalpontDDLPackage* pDDLPackage ) void write_drop_index_object(ByteStream& bs, CalpontDDLPackage* pDDLPackage)
{ {
pDDLPackage->Write(bs);
pDDLPackage->Write( bs );
} }
void read_drop_index_object( ByteStream& bs ) void read_drop_index_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DDL_DROP == package_type ); CPPUNIT_ASSERT(DDL_DROP == package_type);
DropObjectDDLPackage* pObject = new DropObjectDDLPackage(); DropObjectDDLPackage* pObject = new DropObjectDDLPackage();
pObject->Read( bs ); pObject->Read(bs);
delete pObject; delete pObject;
} }
}; };
// PARSE STATEMENT TESTS // PARSE STATEMENT TESTS
class DDLCreateTableParserTest : public CppUnit::TestFixture class DDLCreateTableParserTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DDLCreateTableParserTest);
CPPUNIT_TEST_SUITE( DDLCreateTableParserTest ); CPPUNIT_TEST(create_t1);
CPPUNIT_TEST( create_t1 );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
public:
void setUp() void setUp()
{ {
} }
@ -361,7 +333,7 @@ public:
{ {
ifstream fin("sql/examples/create-table.sql"); ifstream fin("sql/examples/create-table.sql");
CPPUNIT_ASSERT( fin != NULL ); CPPUNIT_ASSERT(fin != NULL);
// read CREATE TABLE statements from buffer and parse // read CREATE TABLE statements from buffer and parse
for (;;) for (;;)
@ -370,14 +342,14 @@ public:
char Buffer[64000]; char Buffer[64000];
string::size_type pos_begin; string::size_type pos_begin;
fin.getline (Buffer, 64000, ';'); fin.getline(Buffer, 64000, ';');
fileBuffer = Buffer; fileBuffer = Buffer;
string::size_type pos = fileBuffer.find ("create ", 0); string::size_type pos = fileBuffer.find("create ", 0);
string::size_type pos1 = fileBuffer.find ("CREATE ", 0); string::size_type pos1 = fileBuffer.find("CREATE ", 0);
if (pos == string::npos && pos1 == string::npos ) if (pos == string::npos && pos1 == string::npos)
// end of file // end of file
break; break;
@ -386,13 +358,13 @@ public:
else else
pos_begin = pos1; pos_begin = pos1;
std::string DDLStatement = fileBuffer.substr (pos_begin, 64000); std::string DDLStatement = fileBuffer.substr(pos_begin, 64000);
fileBuffer.append(";"); fileBuffer.append(";");
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
pDDLStatement->populateFromDDLStatement( DDLStatement ); pDDLStatement->populateFromDDLStatement(DDLStatement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
@ -410,16 +382,14 @@ public:
class DDLCreateIndexParserTest : public CppUnit::TestFixture class DDLCreateIndexParserTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DDLCreateIndexParserTest);
CPPUNIT_TEST_SUITE( DDLCreateIndexParserTest ); CPPUNIT_TEST(createIndex_t1);
CPPUNIT_TEST( createIndex_t1 );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
public:
void setUp() void setUp()
{ {
} }
@ -432,7 +402,7 @@ public:
{ {
ifstream fin("sql/examples/create-index.sql"); ifstream fin("sql/examples/create-index.sql");
CPPUNIT_ASSERT( fin != NULL ); CPPUNIT_ASSERT(fin != NULL);
// read CREATE INDEX statements from buffer and parse // read CREATE INDEX statements from buffer and parse
for (;;) for (;;)
@ -441,14 +411,14 @@ public:
char Buffer[64000]; char Buffer[64000];
string::size_type pos_begin; string::size_type pos_begin;
fin.getline (Buffer, 64000, ';'); fin.getline(Buffer, 64000, ';');
fileBuffer = Buffer; fileBuffer = Buffer;
string::size_type pos = fileBuffer.find ("create ", 0); string::size_type pos = fileBuffer.find("create ", 0);
string::size_type pos1 = fileBuffer.find ("CREATE ", 0); string::size_type pos1 = fileBuffer.find("CREATE ", 0);
if (pos == string::npos && pos1 == string::npos ) if (pos == string::npos && pos1 == string::npos)
// end of file // end of file
break; break;
@ -457,13 +427,13 @@ public:
else else
pos_begin = pos1; pos_begin = pos1;
std::string DDLStatement = fileBuffer.substr (pos_begin, 64000); std::string DDLStatement = fileBuffer.substr(pos_begin, 64000);
fileBuffer.append(";"); fileBuffer.append(";");
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
pDDLStatement->populateFromDDLStatement( DDLStatement ); pDDLStatement->populateFromDDLStatement(DDLStatement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
@ -477,22 +447,18 @@ public:
fin.close(); fin.close();
} }
}; };
class DDLAlterTableParserTest : public CppUnit::TestFixture class DDLAlterTableParserTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DDLAlterTableParserTest);
CPPUNIT_TEST_SUITE( DDLAlterTableParserTest ); CPPUNIT_TEST(alter_t1);
CPPUNIT_TEST( alter_t1 );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
public:
void setUp() void setUp()
{ {
} }
@ -505,7 +471,7 @@ public:
{ {
ifstream fin("sql/examples/alter-table.sql"); ifstream fin("sql/examples/alter-table.sql");
CPPUNIT_ASSERT( fin != NULL ); CPPUNIT_ASSERT(fin != NULL);
// read ALTER TABLE statements from buffer and parse // read ALTER TABLE statements from buffer and parse
for (;;) for (;;)
@ -514,14 +480,14 @@ public:
char Buffer[64000]; char Buffer[64000];
string::size_type pos_begin; string::size_type pos_begin;
fin.getline (Buffer, 64000, ';'); fin.getline(Buffer, 64000, ';');
fileBuffer = Buffer; fileBuffer = Buffer;
string::size_type pos = fileBuffer.find ("alter ", 0); string::size_type pos = fileBuffer.find("alter ", 0);
string::size_type pos1 = fileBuffer.find ("ALTER ", 0); string::size_type pos1 = fileBuffer.find("ALTER ", 0);
if (pos == string::npos && pos1 == string::npos ) if (pos == string::npos && pos1 == string::npos)
// end of file // end of file
break; break;
@ -530,13 +496,13 @@ public:
else else
pos_begin = pos1; pos_begin = pos1;
std::string DDLStatement = fileBuffer.substr (pos_begin, 64000); std::string DDLStatement = fileBuffer.substr(pos_begin, 64000);
fileBuffer.append(";"); fileBuffer.append(";");
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
pDDLStatement->populateFromDDLStatement( DDLStatement ); pDDLStatement->populateFromDDLStatement(DDLStatement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
@ -552,22 +518,18 @@ public:
} }
}; };
class DDLDropTableParserTest : public CppUnit::TestFixture class DDLDropTableParserTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DDLDropTableParserTest);
CPPUNIT_TEST_SUITE( DDLDropTableParserTest ); CPPUNIT_TEST(drop_t1);
CPPUNIT_TEST( drop_t1 );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
public:
void setUp() void setUp()
{ {
} }
void tearDown() void tearDown()
@ -578,7 +540,7 @@ public:
{ {
ifstream fin("sql/examples/drop-table.sql"); ifstream fin("sql/examples/drop-table.sql");
CPPUNIT_ASSERT( fin != NULL ); CPPUNIT_ASSERT(fin != NULL);
// read DROP TABLE statements from buffer and parse // read DROP TABLE statements from buffer and parse
for (;;) for (;;)
@ -587,14 +549,14 @@ public:
char Buffer[64000]; char Buffer[64000];
string::size_type pos_begin; string::size_type pos_begin;
fin.getline (Buffer, 64000, ';'); fin.getline(Buffer, 64000, ';');
fileBuffer = Buffer; fileBuffer = Buffer;
string::size_type pos = fileBuffer.find ("drop ", 0); string::size_type pos = fileBuffer.find("drop ", 0);
string::size_type pos1 = fileBuffer.find ("DROP ", 0); string::size_type pos1 = fileBuffer.find("DROP ", 0);
if (pos == string::npos && pos1 == string::npos ) if (pos == string::npos && pos1 == string::npos)
// end of file // end of file
break; break;
@ -603,13 +565,13 @@ public:
else else
pos_begin = pos1; pos_begin = pos1;
std::string DDLStatement = fileBuffer.substr (pos_begin, 64000); std::string DDLStatement = fileBuffer.substr(pos_begin, 64000);
fileBuffer.append(";"); fileBuffer.append(";");
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
pDDLStatement->populateFromDDLStatement( DDLStatement ); pDDLStatement->populateFromDDLStatement(DDLStatement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
@ -623,22 +585,20 @@ public:
fin.close(); fin.close();
} }
}; };
class DDLDropIndexParserTest : public CppUnit::TestFixture class DDLDropIndexParserTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DDLDropIndexParserTest);
CPPUNIT_TEST_SUITE( DDLDropIndexParserTest ); CPPUNIT_TEST(dropIndex_t1);
CPPUNIT_TEST( dropIndex_t1 );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
std::string fDDLStatement; std::string fDDLStatement;
public: public:
void setUp() void setUp()
{ {
} }
@ -651,7 +611,7 @@ public:
{ {
ifstream fin("sql/examples/drop-index.sql"); ifstream fin("sql/examples/drop-index.sql");
CPPUNIT_ASSERT( fin != NULL ); CPPUNIT_ASSERT(fin != NULL);
// read DROP INDEX statements from buffer and parse // read DROP INDEX statements from buffer and parse
for (;;) for (;;)
@ -660,14 +620,14 @@ public:
char Buffer[64000]; char Buffer[64000];
string::size_type pos_begin; string::size_type pos_begin;
fin.getline (Buffer, 64000, ';'); fin.getline(Buffer, 64000, ';');
fileBuffer = Buffer; fileBuffer = Buffer;
string::size_type pos = fileBuffer.find ("drop ", 0); string::size_type pos = fileBuffer.find("drop ", 0);
string::size_type pos1 = fileBuffer.find ("DROP ", 0); string::size_type pos1 = fileBuffer.find("DROP ", 0);
if (pos == string::npos && pos1 == string::npos ) if (pos == string::npos && pos1 == string::npos)
// end of file // end of file
break; break;
@ -676,13 +636,13 @@ public:
else else
pos_begin = pos1; pos_begin = pos1;
std::string DDLStatement = fileBuffer.substr (pos_begin, 64000); std::string DDLStatement = fileBuffer.substr(pos_begin, 64000);
fileBuffer.append(";"); fileBuffer.append(";");
MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement(); MySQLDDLStatement* pDDLStatement = new MySQLDDLStatement();
pDDLStatement->populateFromDDLStatement( DDLStatement ); pDDLStatement->populateFromDDLStatement(DDLStatement);
CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement); CalpontDDLPackage* pDDLPackage = CalpontDDLFactory::makeCalpontDDLPackage(*pDDLStatement);
@ -696,29 +656,26 @@ public:
fin.close(); fin.close();
} }
}; };
CPPUNIT_TEST_SUITE_REGISTRATION( DDLDropIndexParserTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DDLDropIndexParserTest);
CPPUNIT_TEST_SUITE_REGISTRATION( DDLDropTableParserTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DDLDropTableParserTest);
// DOESN'T NOT PARSE CPPUNIT_TEST_SUITE_REGISTRATION( DDLAlterTableParserTest ); // DOESN'T NOT PARSE CPPUNIT_TEST_SUITE_REGISTRATION( DDLAlterTableParserTest );
CPPUNIT_TEST_SUITE_REGISTRATION( DDLCreateIndexParserTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DDLCreateIndexParserTest);
CPPUNIT_TEST_SUITE_REGISTRATION( DDLCreateTableParserTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DDLCreateTableParserTest);
CPPUNIT_TEST_SUITE_REGISTRATION( DDLWriteReadTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DDLWriteReadTest);
#include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h> #include <cppunit/ui/text/TestRunner.h>
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
CppUnit::TextUi::TestRunner runner; CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() ); runner.addTest(registry.makeTest());
bool wasSuccessful = runner.run( "", false ); bool wasSuccessful = runner.run("", false);
return (wasSuccessful ? 0 : 1); return (wasSuccessful ? 0 : 1);
} }
string itoa(const int i) string itoa(const int i)
@ -727,4 +684,3 @@ string itoa(const int i)
ss << i; ss << i;
return ss.str(); return ss.str();
} }

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: markpartition.cpp 6566 2010-04-27 18:02:51Z rdempsey $ * $Id: markpartition.cpp 6566 2010-04-27 18:02:51Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -29,9 +29,7 @@ using namespace std;
namespace ddlpackage namespace ddlpackage
{ {
RestorePartitionStatement::RestorePartitionStatement(QualifiedName* qualifiedName) : fTableName(qualifiedName)
RestorePartitionStatement::RestorePartitionStatement(QualifiedName* qualifiedName) :
fTableName(qualifiedName)
{ {
} }
@ -48,4 +46,4 @@ ostream& RestorePartitionStatement::put(ostream& os) const
return os; return os;
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: serialize.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: serialize.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <stdexcept> #include <stdexcept>
#include <iostream> #include <iostream>
@ -35,17 +35,17 @@ using namespace messageqcpp;
using namespace std; using namespace std;
using namespace ddlpackage; using namespace ddlpackage;
template<class T> template <class T>
void write_vec(vector<T*>& v, ByteStream& bs) void write_vec(vector<T*>& v, ByteStream& bs)
{ {
bs << (quadbyte) v.size(); bs << (quadbyte)v.size();
typename vector<T*>::const_iterator itr; typename vector<T*>::const_iterator itr;
for (itr = v.begin(); itr != v.end(); ++itr) for (itr = v.begin(); itr != v.end(); ++itr)
(*itr)->serialize(bs); (*itr)->serialize(bs);
} }
template<class T> template <class T>
void read_vec(vector<T*>& v, ByteStream& bs) void read_vec(vector<T*>& v, ByteStream& bs)
{ {
T* x; T* x;
@ -60,7 +60,6 @@ void read_vec(vector<T*>& v, ByteStream& bs)
} }
} }
/////////////////////////////////////// ///////////////////////////////////////
/// CreateTableStatement Serialization /// CreateTableStatement Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -71,7 +70,7 @@ int CreateTableStatement::unserialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
fTableDef = new TableDef(); fTableDef = new TableDef();
fTableDef->unserialize( bytestream ); fTableDef->unserialize(bytestream);
bytestream >> fSessionID; bytestream >> fSessionID;
bytestream >> fSql; bytestream >> fSql;
bytestream >> fOwner; bytestream >> fOwner;
@ -84,10 +83,10 @@ int CreateTableStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_CREATE_TABLE_STATEMENT; bytestream << (quadbyte)DDL_CREATE_TABLE_STATEMENT;
// write table def // write table def
fTableDef->serialize( bytestream ); fTableDef->serialize(bytestream);
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -103,8 +102,6 @@ int CreateTableStatement::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AlterTableStatement Serialization /// AlterTableStatement Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -119,7 +116,7 @@ int AlterTableStatement::unserialize(ByteStream& bytestream)
fTableName = new QualifiedName(); fTableName = new QualifiedName();
// read table name // read table name
fTableName->unserialize( bytestream ); fTableName->unserialize(bytestream);
bytestream >> fTimeZone; bytestream >> fTimeZone;
@ -127,7 +124,7 @@ int AlterTableStatement::unserialize(ByteStream& bytestream)
quadbyte action_count; quadbyte action_count;
bytestream >> action_count; bytestream >> action_count;
for ( unsigned int i = 0; i < action_count; i++ ) for (unsigned int i = 0; i < action_count; i++)
{ {
// read action type // read action type
bytestream >> type; bytestream >> type;
@ -137,78 +134,76 @@ int AlterTableStatement::unserialize(ByteStream& bytestream)
case DDL_ATA_ADD_COLUMN: case DDL_ATA_ADD_COLUMN:
ata = new AtaAddColumn(); ata = new AtaAddColumn();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_ADD_COLUMNS: case DDL_ATA_ADD_COLUMNS:
ata = new AtaAddColumns(); ata = new AtaAddColumns();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_DROP_COLUMN: case DDL_ATA_DROP_COLUMN:
ata = new AtaDropColumn(); ata = new AtaDropColumn();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_DROP_COLUMNS: case DDL_ATA_DROP_COLUMNS:
ata = new AtaDropColumns(); ata = new AtaDropColumns();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_ADD_TABLE_CONSTRAINT: case DDL_ATA_ADD_TABLE_CONSTRAINT:
ata = new AtaAddTableConstraint(); ata = new AtaAddTableConstraint();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_SET_COLUMN_DEFAULT: case DDL_ATA_SET_COLUMN_DEFAULT:
ata = new AtaSetColumnDefault(); ata = new AtaSetColumnDefault();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_DROP_COLUMN_DEFAULT: case DDL_ATA_DROP_COLUMN_DEFAULT:
ata = new AtaDropColumnDefault(); ata = new AtaDropColumnDefault();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_DROP_TABLE_CONSTRAINT: case DDL_ATA_DROP_TABLE_CONSTRAINT:
ata = new AtaDropTableConstraint(); ata = new AtaDropTableConstraint();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_RENAME_TABLE: case DDL_ATA_RENAME_TABLE:
ata = new AtaRenameTable(); ata = new AtaRenameTable();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_RENAME_COLUMN: case DDL_ATA_RENAME_COLUMN:
ata = new AtaRenameColumn(); ata = new AtaRenameColumn();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_MODIFY_COLUMN_TYPE: case DDL_ATA_MODIFY_COLUMN_TYPE:
ata = new AtaModifyColumnType(); ata = new AtaModifyColumnType();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
case DDL_ATA_TABLE_COMMENT: case DDL_ATA_TABLE_COMMENT:
ata = new AtaTableComment(); ata = new AtaTableComment();
ata->unserialize(bytestream); ata->unserialize(bytestream);
fActions.push_back( ata ); fActions.push_back(ata);
break; break;
default: default: throw("Bad typecode for AlterTableAction"); break;
throw ("Bad typecode for AlterTableAction");
break;
} }
bytestream >> fSessionID; bytestream >> fSessionID;
@ -225,10 +220,10 @@ int AlterTableStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ALTER_TABLE_STATEMENT; bytestream << (quadbyte)DDL_ALTER_TABLE_STATEMENT;
// write table name // write table name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
bytestream << fTimeZone; bytestream << fTimeZone;
@ -248,8 +243,6 @@ int AlterTableStatement::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// CreateIndexStatement Serialization /// CreateIndexStatement Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -261,23 +254,21 @@ int CreateIndexStatement::unserialize(ByteStream& bytestream)
// read the index and schema name // read the index and schema name
fIndexName = new QualifiedName(); fIndexName = new QualifiedName();
fIndexName->unserialize( bytestream ); fIndexName->unserialize(bytestream);
// read the table and schema name // read the table and schema name
fTableName = new QualifiedName(); fTableName = new QualifiedName();
fTableName->unserialize( bytestream ); fTableName->unserialize(bytestream);
quadbyte column_count; quadbyte column_count;
bytestream >> column_count; bytestream >> column_count;
std::string columnname; std::string columnname;
for ( unsigned int i = 0; i < column_count; i++ ) for (unsigned int i = 0; i < column_count; i++)
{ {
bytestream >> columnname; bytestream >> columnname;
fColumnNames.push_back( columnname ); fColumnNames.push_back(columnname);
} }
// read unique flag // read unique flag
@ -296,27 +287,25 @@ int CreateIndexStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_CREATE_INDEX; bytestream << (quadbyte)DDL_CREATE_INDEX;
// write the index and schema name // write the index and schema name
fIndexName->serialize( bytestream ); fIndexName->serialize(bytestream);
// write the table and schema name // write the table and schema name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
// write column name list // write column name list
bytestream << (quadbyte) fColumnNames.size(); bytestream << (quadbyte)fColumnNames.size();
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
for (itr = fColumnNames.begin(); for (itr = fColumnNames.begin(); itr != fColumnNames.end(); ++itr)
itr != fColumnNames.end();
++itr)
{ {
bytestream << *itr; bytestream << *itr;
} }
// write Unique flag // write Unique flag
bytestream << (quadbyte) fUnique; bytestream << (quadbyte)fUnique;
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -330,8 +319,6 @@ int CreateIndexStatement::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// DropIndexStatement Serialization /// DropIndexStatement Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -362,10 +349,10 @@ int DropIndexStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_DROP_INDEX_STATEMENT; bytestream << (quadbyte)DDL_DROP_INDEX_STATEMENT;
// write the table and schema name // write the table and schema name
fIndexName->serialize( bytestream ); fIndexName->serialize(bytestream);
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -379,7 +366,6 @@ int DropIndexStatement::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// DropTableStatement Serialization /// DropTableStatement Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -389,7 +375,7 @@ int DropTableStatement::unserialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
//cout << endl << "DropTableStatement unserialize testing started" << endl; // cout << endl << "DropTableStatement unserialize testing started" << endl;
fTableName = new QualifiedName(); fTableName = new QualifiedName();
fTableName->unserialize(bytestream); fTableName->unserialize(bytestream);
@ -418,15 +404,15 @@ int DropTableStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
//cout << "DropTableStatement serialize testing started" << endl; // cout << "DropTableStatement serialize testing started" << endl;
bytestream << (quadbyte) DDL_DROP_TABLE_STATEMENT; bytestream << (quadbyte)DDL_DROP_TABLE_STATEMENT;
// write the table and schema name // write the table and schema name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
// read cascade flag // read cascade flag
bytestream << (quadbyte) fCascade; bytestream << (quadbyte)fCascade;
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -449,7 +435,7 @@ int TruncTableStatement::unserialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
//cout << endl << "TruncTableStatement unserialize testing started" << endl; // cout << endl << "TruncTableStatement unserialize testing started" << endl;
fTableName = new QualifiedName(); fTableName = new QualifiedName();
fTableName->unserialize(bytestream); fTableName->unserialize(bytestream);
@ -471,12 +457,12 @@ int TruncTableStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
//cout << "TruncTableStatement serialize testing started" << endl; // cout << "TruncTableStatement serialize testing started" << endl;
bytestream << (quadbyte) DDL_TRUNC_TABLE_STATEMENT; bytestream << (quadbyte)DDL_TRUNC_TABLE_STATEMENT;
// write the table and schema name // write the table and schema name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -490,7 +476,6 @@ int TruncTableStatement::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// MarkPartitionStatement Serialization /// MarkPartitionStatement Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -531,11 +516,10 @@ int MarkPartitionStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte)DDL_MARK_PARTITION_STATEMENT;
bytestream << (quadbyte) DDL_MARK_PARTITION_STATEMENT;
// write the table and schema name // write the table and schema name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -594,10 +578,10 @@ int DropPartitionStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_DROP_PARTITION_STATEMENT; bytestream << (quadbyte)DDL_DROP_PARTITION_STATEMENT;
// write the table and schema name // write the table and schema name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -655,10 +639,10 @@ int RestorePartitionStatement::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_RESTORE_PARTITION_STATEMENT; bytestream << (quadbyte)DDL_RESTORE_PARTITION_STATEMENT;
// write the table and schema name // write the table and schema name
fTableName->serialize( bytestream ); fTableName->serialize(bytestream);
// write sessionid // write sessionid
bytestream << fSessionID; bytestream << fSessionID;
@ -690,7 +674,7 @@ int AtaAddColumn::unserialize(ByteStream& bytestream)
fColumnDef = new ColumnDef(); fColumnDef = new ColumnDef();
// read column // read column
fColumnDef->unserialize( bytestream ); fColumnDef->unserialize(bytestream);
return ret; return ret;
} }
@ -701,16 +685,14 @@ int AtaAddColumn::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
// write type code // write type code
bytestream << (quadbyte) DDL_ATA_ADD_COLUMN; bytestream << (quadbyte)DDL_ATA_ADD_COLUMN;
// write column // write column
fColumnDef->serialize( bytestream ); fColumnDef->serialize(bytestream);
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaAddColumns Serialization /// AtaAddColumns Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -731,7 +713,7 @@ int AtaAddColumns::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
// write type code // write type code
bytestream << (quadbyte) DDL_ATA_ADD_COLUMNS; bytestream << (quadbyte)DDL_ATA_ADD_COLUMNS;
write_vec<ColumnDef>(fColumns, bytestream); write_vec<ColumnDef>(fColumns, bytestream);
@ -766,9 +748,9 @@ int AtaDropColumns::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
// write type code // write type code
bytestream << (quadbyte) DDL_ATA_DROP_COLUMNS; bytestream << (quadbyte)DDL_ATA_DROP_COLUMNS;
bytestream << (quadbyte) fColumns.size(); bytestream << (quadbyte)fColumns.size();
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
@ -780,8 +762,6 @@ int AtaDropColumns::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaAddTableConstraint Serialization /// AtaAddTableConstraint Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -826,14 +806,13 @@ int AtaAddTableConstraint::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ATA_ADD_TABLE_CONSTRAINT; bytestream << (quadbyte)DDL_ATA_ADD_TABLE_CONSTRAINT;
bytestream << (quadbyte) fTableConstraint->getSerialType(); bytestream << (quadbyte)fTableConstraint->getSerialType();
fTableConstraint->serialize( bytestream ); fTableConstraint->serialize(bytestream);
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaDropColumn Serialization /// AtaDropColumn Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -846,7 +825,7 @@ int AtaDropColumn::unserialize(ByteStream& bytestream)
bytestream >> fColumnName; bytestream >> fColumnName;
quadbyte action; quadbyte action;
bytestream >> action; bytestream >> action;
fDropBehavior = (DDL_REFERENTIAL_ACTION) action; fDropBehavior = (DDL_REFERENTIAL_ACTION)action;
return ret; return ret;
} }
@ -857,14 +836,13 @@ int AtaDropColumn::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
// write type code // write type code
bytestream << (quadbyte) DDL_ATA_DROP_COLUMN; bytestream << (quadbyte)DDL_ATA_DROP_COLUMN;
bytestream << fColumnName; bytestream << fColumnName;
bytestream << (quadbyte) fDropBehavior; bytestream << (quadbyte)fDropBehavior;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaSetColumnDefault Serialization /// AtaSetColumnDefault Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -886,15 +864,13 @@ int AtaSetColumnDefault::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ATA_SET_COLUMN_DEFAULT; bytestream << (quadbyte)DDL_ATA_SET_COLUMN_DEFAULT;
bytestream << fColumnName; bytestream << fColumnName;
fDefaultValue->serialize( bytestream ); fDefaultValue->serialize(bytestream);
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaDropColumnDefault Serialization /// AtaDropColumnDefault Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -915,14 +891,12 @@ int AtaDropColumnDefault::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ATA_DROP_COLUMN_DEFAULT; bytestream << (quadbyte)DDL_ATA_DROP_COLUMN_DEFAULT;
bytestream << fColumnName; bytestream << fColumnName;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaDropTableConstraint Serialization /// AtaDropTableConstraint Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -937,7 +911,7 @@ int AtaDropTableConstraint::unserialize(ByteStream& bytestream)
quadbyte action; quadbyte action;
bytestream >> action; bytestream >> action;
fDropBehavior = (DDL_REFERENTIAL_ACTION) action; fDropBehavior = (DDL_REFERENTIAL_ACTION)action;
return ret; return ret;
} }
@ -947,14 +921,13 @@ int AtaDropTableConstraint::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ATA_DROP_TABLE_CONSTRAINT; bytestream << (quadbyte)DDL_ATA_DROP_TABLE_CONSTRAINT;
bytestream << fConstraintName; bytestream << fConstraintName;
bytestream << (quadbyte) fDropBehavior; bytestream << (quadbyte)fDropBehavior;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaTableComment Serialization /// AtaTableComment Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -975,14 +948,12 @@ int AtaTableComment::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ATA_TABLE_COMMENT; bytestream << (quadbyte)DDL_ATA_TABLE_COMMENT;
bytestream << fTableComment; bytestream << fTableComment;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaRenameTable Serialization /// AtaRenameTable Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -995,7 +966,7 @@ int AtaRenameTable::unserialize(ByteStream& bytestream)
fQualifiedName = new QualifiedName(); fQualifiedName = new QualifiedName();
// read the table and schema name // read the table and schema name
fQualifiedName->unserialize( bytestream ); fQualifiedName->unserialize(bytestream);
return ret; return ret;
} }
@ -1006,16 +977,14 @@ int AtaRenameTable::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
// write type code // write type code
bytestream << (quadbyte) DDL_ATA_RENAME_TABLE; bytestream << (quadbyte)DDL_ATA_RENAME_TABLE;
// write the table and schema name // write the table and schema name
fQualifiedName->serialize( bytestream ); fQualifiedName->serialize(bytestream);
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaModifyColumnType Serialization /// AtaModifyColumnType Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1028,7 +997,7 @@ int AtaModifyColumnType::unserialize(ByteStream& bytestream)
fColumnType = new ColumnType(); fColumnType = new ColumnType();
// read column type and name // read column type and name
fColumnType->unserialize( bytestream ); fColumnType->unserialize(bytestream);
bytestream >> fName; bytestream >> fName;
@ -1041,18 +1010,16 @@ int AtaModifyColumnType::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
// write type code // write type code
bytestream << (quadbyte) DDL_ATA_MODIFY_COLUMN_TYPE; bytestream << (quadbyte)DDL_ATA_MODIFY_COLUMN_TYPE;
// write column type and name // write column type and name
fColumnType->serialize( bytestream ); fColumnType->serialize(bytestream);
bytestream << fName; bytestream << fName;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// AtaRenameColumn Serialization /// AtaRenameColumn Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1097,7 +1064,7 @@ int AtaRenameColumn::serialize(ByteStream& bytestream)
{ {
int ret = 1; int ret = 1;
bytestream << (quadbyte) DDL_ATA_RENAME_COLUMN; bytestream << (quadbyte)DDL_ATA_RENAME_COLUMN;
bytestream << fName; bytestream << fName;
bytestream << fNewName; bytestream << fNewName;
@ -1116,14 +1083,12 @@ int AtaRenameColumn::serialize(ByteStream& bytestream)
else else
{ {
bytestream << (quadbyte)DDL_COLUMN_DEFAULT_VALUE; bytestream << (quadbyte)DDL_COLUMN_DEFAULT_VALUE;
fDefaultValue->serialize( bytestream ); fDefaultValue->serialize(bytestream);
} }
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// ColumnType Serialization /// ColumnType Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1161,7 +1126,7 @@ int ColumnType::unserialize(ByteStream& bytestream)
fAutoincrement = autoincrement; fAutoincrement = autoincrement;
fNextvalue = nextVal; fNextvalue = nextVal;
// cout << "BS length = " << bytestream.length() << endl; // cout << "BS length = " << bytestream.length() << endl;
return ret; return ret;
} }
@ -1190,13 +1155,11 @@ int ColumnType::serialize(ByteStream& bytestream)
bytestream << autoincrement; bytestream << autoincrement;
bytestream << nextVal; bytestream << nextVal;
// cout << "BS length = " << bytestream.length() << endl; // cout << "BS length = " << bytestream.length() << endl;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// ColumnConstraintDef Serialization /// ColumnConstraintDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1218,8 +1181,8 @@ int ColumnConstraintDef::unserialize(ByteStream& bytestream)
bytestream >> fCheck; bytestream >> fCheck;
fDeferrable = (deferrable != 0); fDeferrable = (deferrable != 0);
fCheckTime = (DDL_CONSTRAINT_ATTRIBUTES) checktime; fCheckTime = (DDL_CONSTRAINT_ATTRIBUTES)checktime;
fConstraintType = (DDL_CONSTRAINTS) constrainttype; fConstraintType = (DDL_CONSTRAINTS)constrainttype;
return ret; return ret;
} }
@ -1243,8 +1206,6 @@ int ColumnConstraintDef::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// ColumnDefaultValue Serialization /// ColumnDefaultValue Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1277,8 +1238,6 @@ int ColumnDefaultValue::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// ColumnDef Serialization /// ColumnDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1292,7 +1251,7 @@ int ColumnDef::unserialize(ByteStream& bytestream)
// read column type // read column type
fType = new ColumnType(); fType = new ColumnType();
fType->unserialize( bytestream ); fType->unserialize(bytestream);
read_vec<ColumnConstraintDef>(fConstraints, bytestream); read_vec<ColumnConstraintDef>(fConstraints, bytestream);
@ -1312,7 +1271,7 @@ int ColumnDef::unserialize(ByteStream& bytestream)
fDefaultValue->unserialize(bytestream); fDefaultValue->unserialize(bytestream);
} }
// cout << "BS length = " << bytestream.length() << endl; // cout << "BS length = " << bytestream.length() << endl;
return ret; return ret;
} }
@ -1324,7 +1283,7 @@ int ColumnDef::serialize(ByteStream& bytestream)
bytestream << fName; bytestream << fName;
// write column type // write column type
fType->serialize( bytestream ); fType->serialize(bytestream);
// serialize column constraints. // serialize column constraints.
write_vec<ColumnConstraintDef>(fConstraints, bytestream); write_vec<ColumnConstraintDef>(fConstraints, bytestream);
@ -1336,17 +1295,14 @@ int ColumnDef::serialize(ByteStream& bytestream)
else else
{ {
bytestream << (quadbyte)DDL_COLUMN_DEFAULT_VALUE; bytestream << (quadbyte)DDL_COLUMN_DEFAULT_VALUE;
fDefaultValue->serialize( bytestream ); fDefaultValue->serialize(bytestream);
} }
// cout << "BS length = " << bytestream.length() << endl;
// cout << "BS length = " << bytestream.length() << endl;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// TableConstraintDef Serialization /// TableConstraintDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1361,9 +1317,7 @@ int TableConstraintDef::unserialize(ByteStream& bytestream)
// read constraint def // read constraint def
bytestream >> constrainttype; bytestream >> constrainttype;
fConstraintType = (DDL_CONSTRAINTS) constrainttype; fConstraintType = (DDL_CONSTRAINTS)constrainttype;
return ret; return ret;
} }
@ -1378,12 +1332,9 @@ int TableConstraintDef::serialize(ByteStream& bytestream)
// write constraint def // write constraint def
bytestream << constrainttype; bytestream << constrainttype;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// TableUniqueConstraintDef Serialization /// TableUniqueConstraintDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1415,7 +1366,7 @@ int TableUniqueConstraintDef::serialize(ByteStream& bytestream)
bytestream << fName; bytestream << fName;
bytestream << (quadbyte) fColumnNameList.size(); bytestream << (quadbyte)fColumnNameList.size();
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
@ -1427,8 +1378,6 @@ int TableUniqueConstraintDef::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// TablePrimaryKeyConstraintDef Serialization /// TablePrimaryKeyConstraintDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1460,7 +1409,7 @@ int TablePrimaryKeyConstraintDef::serialize(ByteStream& bytestream)
bytestream << fName; bytestream << fName;
bytestream << (quadbyte) fColumnNameList.size(); bytestream << (quadbyte)fColumnNameList.size();
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
@ -1472,8 +1421,6 @@ int TablePrimaryKeyConstraintDef::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// ReferentialAction Serialization /// ReferentialAction Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1490,9 +1437,8 @@ int ReferentialAction::unserialize(ByteStream& bytestream)
bytestream >> onupdate; bytestream >> onupdate;
bytestream >> ondelete; bytestream >> ondelete;
fOnUpdate = (DDL_REFERENTIAL_ACTION) onupdate; fOnUpdate = (DDL_REFERENTIAL_ACTION)onupdate;
fOnDelete = (DDL_REFERENTIAL_ACTION) ondelete; fOnDelete = (DDL_REFERENTIAL_ACTION)ondelete;
return ret; return ret;
} }
@ -1509,12 +1455,9 @@ int ReferentialAction::serialize(ByteStream& bytestream)
bytestream << onupdate; bytestream << onupdate;
bytestream << ondelete; bytestream << ondelete;
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// TableReferencesConstraintDef Serialization /// TableReferencesConstraintDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1554,7 +1497,7 @@ int TableReferencesConstraintDef::unserialize(ByteStream& bytestream)
// Match type // Match type
quadbyte matchType; quadbyte matchType;
bytestream >> matchType; bytestream >> matchType;
fMatchType = (DDL_MATCH_TYPE) matchType; fMatchType = (DDL_MATCH_TYPE)matchType;
// Ref Action // Ref Action
quadbyte sertype; quadbyte sertype;
@ -1599,24 +1542,22 @@ int TableReferencesConstraintDef::serialize(ByteStream& bytestream)
bytestream << *itr; bytestream << *itr;
// Match type // Match type
bytestream << (quadbyte) fMatchType; bytestream << (quadbyte)fMatchType;
// Ref action // Ref action
if (0 == fRefAction) if (0 == fRefAction)
{ {
bytestream << (quadbyte) DDL_NULL; bytestream << (quadbyte)DDL_NULL;
} }
else else
{ {
bytestream << (quadbyte) DDL_REF_ACTION; bytestream << (quadbyte)DDL_REF_ACTION;
fRefAction->serialize(bytestream); fRefAction->serialize(bytestream);
} }
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// TableCheckConstraintDef Serialization /// TableCheckConstraintDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1643,8 +1584,6 @@ int TableCheckConstraintDef::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// TableDef Serialization /// TableDef Serialization
/////////////////////////////////////// ///////////////////////////////////////
@ -1676,43 +1615,41 @@ int TableDef::unserialize(ByteStream& bytestream)
case DDL_TABLE_UNIQUE_CONSTRAINT_DEF: case DDL_TABLE_UNIQUE_CONSTRAINT_DEF:
constraint = new TableUniqueConstraintDef(); constraint = new TableUniqueConstraintDef();
constraint->unserialize(bytestream); constraint->unserialize(bytestream);
fConstraints.push_back( constraint ); fConstraints.push_back(constraint);
break; break;
case DDL_TABLE_PRIMARY_CONSTRAINT_DEF: case DDL_TABLE_PRIMARY_CONSTRAINT_DEF:
constraint = new TablePrimaryKeyConstraintDef(); constraint = new TablePrimaryKeyConstraintDef();
constraint->unserialize(bytestream); constraint->unserialize(bytestream);
fConstraints.push_back( constraint ); fConstraints.push_back(constraint);
break; break;
case DDL_TABLE_REFERENCES_CONSTRAINT_DEF: case DDL_TABLE_REFERENCES_CONSTRAINT_DEF:
constraint = new TableReferencesConstraintDef(); constraint = new TableReferencesConstraintDef();
constraint->unserialize(bytestream); constraint->unserialize(bytestream);
fConstraints.push_back( constraint ); fConstraints.push_back(constraint);
break; break;
case DDL_TABLE_CHECK_CONSTRAINT_DEF: case DDL_TABLE_CHECK_CONSTRAINT_DEF:
constraint = new TableCheckConstraintDef(); constraint = new TableCheckConstraintDef();
constraint->unserialize(bytestream); constraint->unserialize(bytestream);
fConstraints.push_back( constraint ); fConstraints.push_back(constraint);
break; break;
default: default: throw("Bad typecode for TableConstraintDef"); break;
throw ("Bad typecode for TableConstraintDef");
break;
} }
} }
// read option maps list // read option maps list
bytestream >> count; bytestream >> count;
for ( unsigned int i = 0; i < count; i++ ) for (unsigned int i = 0; i < count; i++)
{ {
// read option map // read option map
string map, map1; string map, map1;
bytestream >> map; bytestream >> map;
bytestream >> map1; bytestream >> map1;
fOptions.insert( pair<string, string> (map, map1) ); fOptions.insert(pair<string, string>(map, map1));
} }
return ret; return ret;
@ -1724,7 +1661,7 @@ int TableDef::serialize(ByteStream& bytestream)
int ret = 1; int ret = 1;
messageqcpp::ByteStream::quadbyte size; messageqcpp::ByteStream::quadbyte size;
// table name // table name
fQualifiedName->serialize( bytestream ); fQualifiedName->serialize(bytestream);
// ColumnDef's // ColumnDef's
write_vec<ColumnDef>(fColumns, bytestream); write_vec<ColumnDef>(fColumns, bytestream);
@ -1735,12 +1672,10 @@ int TableDef::serialize(ByteStream& bytestream)
TableConstraintDefList::const_iterator itr; TableConstraintDefList::const_iterator itr;
for (itr = fConstraints.begin(); for (itr = fConstraints.begin(); itr != fConstraints.end(); ++itr)
itr != fConstraints.end();
++itr)
{ {
bytestream << (quadbyte) (*itr)->getSerialType(); bytestream << (quadbyte)(*itr)->getSerialType();
(*itr)->serialize( bytestream ); (*itr)->serialize(bytestream);
} }
// serialize TableOptions // serialize TableOptions
@ -1750,9 +1685,7 @@ int TableDef::serialize(ByteStream& bytestream)
pair<string, string> oval; pair<string, string> oval;
TableOptionMap::const_iterator itr2; TableOptionMap::const_iterator itr2;
for (itr2 = fOptions.begin(); for (itr2 = fOptions.begin(); itr2 != fOptions.end(); ++itr2)
itr2 != fOptions.end();
++itr2)
{ {
oval = *itr2; oval = *itr2;
bytestream << oval.first; bytestream << oval.first;
@ -1775,7 +1708,6 @@ int QualifiedName::unserialize(ByteStream& bytestream)
bytestream >> fSchema; bytestream >> fSchema;
bytestream >> fName; bytestream >> fName;
return ret; return ret;
} }
@ -1791,12 +1723,10 @@ int QualifiedName::serialize(ByteStream& bytestream)
return ret; return ret;
} }
/////////////////////////////////////// ///////////////////////////////////////
/// ConstraintAttributes Serialization /// ConstraintAttributes Serialization
/////////////////////////////////////// ///////////////////////////////////////
/** @brief Construct from Bytestream */ /** @brief Construct from Bytestream */
int ConstraintAttributes::unserialize(ByteStream& bytestream) int ConstraintAttributes::unserialize(ByteStream& bytestream)
{ {
@ -1809,10 +1739,9 @@ int ConstraintAttributes::unserialize(ByteStream& bytestream)
bytestream >> checktime; bytestream >> checktime;
bytestream >> deferrable; bytestream >> deferrable;
fCheckTime = (DDL_CONSTRAINT_ATTRIBUTES) checktime; fCheckTime = (DDL_CONSTRAINT_ATTRIBUTES)checktime;
fDeferrable = (deferrable != 0); fDeferrable = (deferrable != 0);
return ret; return ret;
} }
@ -1828,9 +1757,5 @@ int ConstraintAttributes::serialize(ByteStream& bytestream)
bytestream << checktime; bytestream << checktime;
bytestream << deferrable; bytestream << deferrable;
return ret; return ret;
} }

View File

@ -17,10 +17,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: sqlparser.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: sqlparser.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <fstream> #include <fstream>
#include <errno.h> #include <errno.h>
@ -45,14 +45,10 @@ namespace ddlpackage
{ {
using namespace std; using namespace std;
SqlParser::SqlParser() : SqlParser::SqlParser() : fStatus(-1), fDebug(false), x(&fParseTree)
fStatus(-1),
fDebug(false),
x(&fParseTree)
{ {
} }
void SqlParser::SetDebug(bool debug) void SqlParser::SetDebug(bool debug)
{ {
fDebug = debug; fDebug = debug;
@ -76,7 +72,6 @@ int SqlParser::Parse(const char* sqltext)
return fStatus; return fStatus;
} }
const ParseTree& SqlParser::GetParseTree(void) const ParseTree& SqlParser::GetParseTree(void)
{ {
if (!Good()) if (!Good())
@ -87,26 +82,21 @@ const ParseTree& SqlParser::GetParseTree(void)
return fParseTree; return fParseTree;
} }
bool SqlParser::Good() bool SqlParser::Good()
{ {
return fStatus == 0; return fStatus == 0;
} }
SqlParser::~SqlParser() SqlParser::~SqlParser()
{ {
scanner_finish(x.scanner); // free scanner allocated memory scanner_finish(x.scanner); // free scanner allocated memory
ddllex_destroy(x.scanner); ddllex_destroy(x.scanner);
} }
SqlFileParser::SqlFileParser() : SqlParser()
SqlFileParser::SqlFileParser() :
SqlParser()
{ {
} }
int SqlFileParser::Parse(const string& sqlfile) int SqlFileParser::Parse(const string& sqlfile)
{ {
fStatus = -1; fStatus = -1;
@ -122,9 +112,9 @@ int SqlFileParser::Parse(const string& sqlfile)
char sqlbuf[1024 * 1024]; char sqlbuf[1024 * 1024];
unsigned length; unsigned length;
ifsql.seekg (0, ios::end); ifsql.seekg(0, ios::end);
length = ifsql.tellg(); length = ifsql.tellg();
ifsql.seekg (0, ios::beg); ifsql.seekg(0, ios::beg);
if (length > sizeof(sqlbuf) - 1) if (length > sizeof(sqlbuf) - 1)
{ {
@ -139,10 +129,10 @@ int SqlFileParser::Parse(const string& sqlfile)
sqlbuf[rcount] = 0; sqlbuf[rcount] = 0;
//cout << endl << sqlfile << "(" << rcount << ")" << endl; // cout << endl << sqlfile << "(" << rcount << ")" << endl;
//cout << "----------------------" << endl; // cout << "----------------------" << endl;
//cout << sqlbuf << endl; // cout << sqlbuf << endl;
return SqlParser::Parse(sqlbuf); return SqlParser::Parse(sqlbuf);
} }
} } // namespace ddlpackage

View File

@ -17,10 +17,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: sqlparser.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: sqlparser.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file /** @file
* *
* This contains a class wrapper for the Bison parsing machinery. * This contains a class wrapper for the Bison parsing machinery.
@ -38,7 +38,6 @@
namespace ddlpackage namespace ddlpackage
{ {
typedef SqlStatementList ParseTree; typedef SqlStatementList ParseTree;
/** @brief SqlParser is a class interface around the Bison parser /** @brief SqlParser is a class interface around the Bison parser
@ -89,12 +88,12 @@ struct pass_to_bison
void* scanner; void* scanner;
const CHARSET_INFO* default_table_charset; const CHARSET_INFO* default_table_charset;
pass_to_bison(ParseTree* pt) : fParseTree(pt), scanner(NULL), default_table_charset(NULL) {}; pass_to_bison(ParseTree* pt) : fParseTree(pt), scanner(NULL), default_table_charset(NULL){};
}; };
class SqlParser class SqlParser
{ {
public: public:
EXPORT SqlParser(void); EXPORT SqlParser(void);
EXPORT virtual ~SqlParser(); EXPORT virtual ~SqlParser();
@ -129,7 +128,7 @@ public:
*/ */
EXPORT void setDefaultCharset(const CHARSET_INFO* default_charset); EXPORT void setDefaultCharset(const CHARSET_INFO* default_charset);
protected: protected:
ParseTree fParseTree; ParseTree fParseTree;
std::string fDBSchema; std::string fDBSchema;
int fStatus; ///< return from yyparse() stored here. int fStatus; ///< return from yyparse() stored here.
@ -138,16 +137,15 @@ protected:
pass_to_bison x; pass_to_bison x;
}; };
/** SqlFileParser is a testing device. /** SqlFileParser is a testing device.
*/ */
class SqlFileParser : public SqlParser class SqlFileParser : public SqlParser
{ {
public: public:
SqlFileParser(); SqlFileParser();
int Parse(const std::string& fileName); int Parse(const std::string& fileName);
}; };
} } // namespace ddlpackage
#undef EXPORT #undef EXPORT

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: sqlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: sqlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -44,4 +44,4 @@ ostream& operator<<(ostream& os, const SqlStatement& stmt)
{ {
return stmt.put(os); return stmt.put(os);
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: sqlstatementlist.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: sqlstatementlist.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
#include "ddlpkg.h" #include "ddlpkg.h"
@ -29,7 +29,6 @@ namespace ddlpackage
{ {
using namespace std; using namespace std;
ostream& operator<<(ostream& os, const SqlStatementList& ssl) ostream& operator<<(ostream& os, const SqlStatementList& ssl)
{ {
vector<SqlStatement*>::const_iterator itr; vector<SqlStatement*>::const_iterator itr;
@ -43,13 +42,11 @@ ostream& operator<<(ostream& os, const SqlStatementList& ssl)
return os; return os;
} }
void SqlStatementList::push_back(SqlStatement* v) void SqlStatementList::push_back(SqlStatement* v)
{ {
fList.push_back(v); fList.push_back(v);
} }
SqlStatementList::~SqlStatementList() SqlStatementList::~SqlStatementList()
{ {
vector<SqlStatement*>::iterator itr; vector<SqlStatement*>::iterator itr;
@ -60,4 +57,4 @@ SqlStatementList::~SqlStatementList()
} }
} }
} } // namespace ddlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: tabledef.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: tabledef.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <iostream> #include <iostream>
#define DDLPKG_DLLEXPORT #define DDLPKG_DLLEXPORT
@ -30,7 +30,6 @@ namespace ddlpackage
{ {
using namespace std; using namespace std;
TableDef::~TableDef() TableDef::~TableDef()
{ {
{ {
@ -53,9 +52,8 @@ TableDef::~TableDef()
delete fQualifiedName; delete fQualifiedName;
} }
TableDef::TableDef(QualifiedName* name, TableElementList* elements, TableOptionMap* options)
TableDef::TableDef(QualifiedName* name, TableElementList* elements, TableOptionMap* options) : : fQualifiedName(name)
fQualifiedName(name)
{ {
if (options) if (options)
{ {
@ -94,37 +92,30 @@ TableDef::TableDef(QualifiedName* name, TableElementList* elements, TableOptionM
delete elements; delete elements;
} }
/** \brief Put to ostream. */ /** \brief Put to ostream. */
ostream& operator<<(ostream& os, const TableDef& tableDef) ostream& operator<<(ostream& os, const TableDef& tableDef)
{ {
os << "CreateTable "; os << "CreateTable ";
if (tableDef.fQualifiedName->fSchema != "") if (tableDef.fQualifiedName->fSchema != "")
//cout << tableDef.fQualifiedName->fSchema << "."; // cout << tableDef.fQualifiedName->fSchema << ".";
os << tableDef.fQualifiedName->fName os << tableDef.fQualifiedName->fName << " " << tableDef.fConstraints.size() << " table constraints"
<< " " << tableDef.fConstraints.size()
<< " table constraints"
<< endl; << endl;
{ {
ColumnDefList::const_iterator itr; ColumnDefList::const_iterator itr;
for (itr = tableDef.fColumns.begin(); for (itr = tableDef.fColumns.begin(); itr != tableDef.fColumns.end(); ++itr)
itr != tableDef.fColumns.end(); ++itr)
{ {
ColumnDef* col = *itr; ColumnDef* col = *itr;
os << *col << endl; os << *col << endl;
} }
} }
{ {
TableConstraintDefList::const_iterator itr; TableConstraintDefList::const_iterator itr;
for (itr = tableDef.fConstraints.begin(); for (itr = tableDef.fConstraints.begin(); itr != tableDef.fConstraints.end(); ++itr)
itr != tableDef.fConstraints.end();
++itr)
{ {
os << (**itr); os << (**itr);
} }
@ -138,8 +129,7 @@ ostream& operator<<(ostream& os, const TableDef& tableDef)
{ {
TableOptionMap::const_iterator oitr; TableOptionMap::const_iterator oitr;
for (oitr = tableDef.fOptions.begin(); for (oitr = tableDef.fOptions.begin(); oitr != tableDef.fOptions.end(); ++oitr)
oitr != tableDef.fOptions.end(); ++oitr)
{ {
oval = *oitr; oval = *oitr;
os << " " << oval.first << "=" << oval.second << endl; os << " " << oval.first << "=" << oval.second << endl;
@ -149,9 +139,6 @@ ostream& operator<<(ostream& os, const TableDef& tableDef)
return os; return os;
} }
ostream& operator<<(ostream& os, const TableConstraintDef& constraint) ostream& operator<<(ostream& os, const TableConstraintDef& constraint)
{ {
return constraint.put(os); return constraint.put(os);
@ -164,51 +151,40 @@ std::ostream& TableConstraintDef::put(std::ostream& os) const
return os; return os;
} }
TableConstraintDef::TableConstraintDef(DDL_CONSTRAINTS cType) : fConstraintType(cType)
TableConstraintDef::TableConstraintDef(DDL_CONSTRAINTS cType) :
fConstraintType(cType)
{ {
} }
TableConstraintDef::TableConstraintDef() : TableConstraintDef::TableConstraintDef() : fConstraintType(DDL_INVALID_CONSTRAINT)
fConstraintType(DDL_INVALID_CONSTRAINT)
{ {
} }
TableCheckConstraintDef::TableCheckConstraintDef(const char* check) : TableCheckConstraintDef::TableCheckConstraintDef(const char* check)
TableConstraintDef(DDL_CHECK), : TableConstraintDef(DDL_CHECK), fCheck(check)
fCheck(check)
{ {
} }
std::ostream& TableCheckConstraintDef::put(std::ostream& os) const std::ostream& TableCheckConstraintDef::put(std::ostream& os) const
{ {
os << "Constraint: " os << "Constraint: " << ConstraintString[fConstraintType] << " ";
<< ConstraintString[fConstraintType] << " ";
os << "\"" << fCheck << "\""; os << "\"" << fCheck << "\"";
os << endl; os << endl;
return os; return os;
} }
TableUniqueConstraintDef::TableUniqueConstraintDef(ColumnNameList* columns)
TableUniqueConstraintDef::TableUniqueConstraintDef(ColumnNameList* columns) : : TableConstraintDef(DDL_UNIQUE), fColumnNameList(*columns)
TableConstraintDef(DDL_UNIQUE),
fColumnNameList(*columns)
{ {
delete columns; delete columns;
} }
std::ostream& TableUniqueConstraintDef::put(std::ostream& os) const std::ostream& TableUniqueConstraintDef::put(std::ostream& os) const
{ {
os << "Constraint: " os << "Constraint: " << fName << " " << ConstraintString[fConstraintType] << " ";
<< fName << " "
<< ConstraintString[fConstraintType] << " ";
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
os << "("; os << "(";
for (itr = fColumnNameList.begin(); for (itr = fColumnNameList.begin(); itr != fColumnNameList.end(); ++itr)
itr != fColumnNameList.end();
++itr)
{ {
os << *itr << " "; os << *itr << " ";
} }
@ -217,24 +193,19 @@ std::ostream& TableUniqueConstraintDef::put(std::ostream& os) const
return os; return os;
} }
TablePrimaryKeyConstraintDef::TablePrimaryKeyConstraintDef(ColumnNameList* columns) : TablePrimaryKeyConstraintDef::TablePrimaryKeyConstraintDef(ColumnNameList* columns)
TableConstraintDef(DDL_PRIMARY_KEY), : TableConstraintDef(DDL_PRIMARY_KEY), fColumnNameList(*columns)
fColumnNameList(*columns)
{ {
delete columns; delete columns;
} }
std::ostream& TablePrimaryKeyConstraintDef::put(std::ostream& os) const std::ostream& TablePrimaryKeyConstraintDef::put(std::ostream& os) const
{ {
os << "Constraint: " os << "Constraint: " << fName << " " << ConstraintString[fConstraintType] << " ";
<< fName << " "
<< ConstraintString[fConstraintType] << " ";
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
os << "("; os << "(";
for (itr = fColumnNameList.begin(); for (itr = fColumnNameList.begin(); itr != fColumnNameList.end(); ++itr)
itr != fColumnNameList.end();
++itr)
{ {
os << *itr << " "; os << *itr << " ";
} }
@ -244,34 +215,28 @@ std::ostream& TablePrimaryKeyConstraintDef::put(std::ostream& os) const
return os; return os;
} }
TableReferencesConstraintDef::TableReferencesConstraintDef TableReferencesConstraintDef::TableReferencesConstraintDef(ColumnNameList* columns, QualifiedName* tableName,
(ColumnNameList* columns,
QualifiedName* tableName,
ColumnNameList* foreignColumns, ColumnNameList* foreignColumns,
DDL_MATCH_TYPE matchType, DDL_MATCH_TYPE matchType,
ReferentialAction* refAction) : ReferentialAction* refAction)
TableConstraintDef(DDL_REFERENCES), : TableConstraintDef(DDL_REFERENCES)
fColumns(*columns), , fColumns(*columns)
fTableName(tableName), , fTableName(tableName)
fForeignColumns(*foreignColumns), , fForeignColumns(*foreignColumns)
fMatchType(matchType), , fMatchType(matchType)
fRefAction(refAction) , fRefAction(refAction)
{ {
delete columns; delete columns;
delete foreignColumns; delete foreignColumns;
} }
std::ostream& TableReferencesConstraintDef::put(std::ostream& os) const std::ostream& TableReferencesConstraintDef::put(std::ostream& os) const
{ {
os << "Constraint: " os << "Constraint: " << fName << " " << ConstraintString[fConstraintType] << " ";
<< fName << " "
<< ConstraintString[fConstraintType] << " ";
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
os << "lcols ("; os << "lcols (";
for (itr = fColumns.begin(); for (itr = fColumns.begin(); itr != fColumns.end(); ++itr)
itr != fColumns.end();
++itr)
{ {
os << *itr << " "; os << *itr << " ";
} }
@ -284,9 +249,7 @@ std::ostream& TableReferencesConstraintDef::put(std::ostream& os) const
os << "fcols ("; os << "fcols (";
for (itr = fForeignColumns.begin(); for (itr = fForeignColumns.begin(); itr != fForeignColumns.end(); ++itr)
itr != fForeignColumns.end();
++itr)
{ {
os << *itr << " "; os << *itr << " ";
} }
@ -300,9 +263,7 @@ std::ostream& operator<<(std::ostream& os, const ColumnNameList& columnNames)
ColumnNameList::const_iterator itr; ColumnNameList::const_iterator itr;
os << '('; os << '(';
for (itr = columnNames.begin(); for (itr = columnNames.begin(); itr != columnNames.end(); ++itr)
itr != columnNames.end();
++itr)
{ {
os << *itr << " "; os << *itr << " ";
} }
@ -311,12 +272,10 @@ std::ostream& operator<<(std::ostream& os, const ColumnNameList& columnNames)
return os; return os;
} }
TableReferencesConstraintDef::~TableReferencesConstraintDef() TableReferencesConstraintDef::~TableReferencesConstraintDef()
{ {
delete fTableName; delete fTableName;
delete fRefAction; delete fRefAction;
} }
} } // namespace ddlpackage

View File

@ -95,10 +95,9 @@ class ParserTest : public CppUnit::TestFixture
CPPUNIT_TEST(foo); CPPUNIT_TEST(foo);
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private:
private:
public: public:
void setUp() void setUp()
{ {
} }
@ -267,8 +266,7 @@ public:
} }
}; };
template <class T>
template<class T>
void u_sertest(T* x) void u_sertest(T* x)
{ {
ByteStream bs; ByteStream bs;
@ -283,17 +281,15 @@ void u_sertest(T* x)
cout << "String Compare" << endl; cout << "String Compare" << endl;
cout << "------------------" << endl; cout << "------------------" << endl;
cout << s1.str() << endl cout << s1.str() << endl << s2.str() << endl;
<< s2.str() << endl;
cout << "------------------" << endl; cout << "------------------" << endl;
CPPUNIT_ASSERT(s1.str() == s2.str()); CPPUNIT_ASSERT(s1.str() == s2.str());
} }
/** @brief Just like u_sertest except that a typecode is pulled off /** @brief Just like u_sertest except that a typecode is pulled off
the ByteStream before the unserialize. */ the ByteStream before the unserialize. */
template<class T> template <class T>
void t_sertest(T* x) void t_sertest(T* x)
{ {
ByteStream bs; ByteStream bs;
@ -312,17 +308,14 @@ void t_sertest(T* x)
cout << "String Compare" << endl; cout << "String Compare" << endl;
cout << "------------------" << endl; cout << "------------------" << endl;
cout << s1.str() << endl cout << s1.str() << endl << s2.str() << endl;
<< s2.str() << endl;
cout << "------------------" << endl; cout << "------------------" << endl;
CPPUNIT_ASSERT(s1.str() == s2.str()); CPPUNIT_ASSERT(s1.str() == s2.str());
} }
class SerializeTest : public CppUnit::TestFixture class SerializeTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(SerializeTest); CPPUNIT_TEST_SUITE(SerializeTest);
CPPUNIT_TEST(qname); CPPUNIT_TEST(qname);
CPPUNIT_TEST(columntype); CPPUNIT_TEST(columntype);
@ -357,18 +350,14 @@ class SerializeTest : public CppUnit::TestFixture
CPPUNIT_TEST(altertablerenamecolumn); CPPUNIT_TEST(altertablerenamecolumn);
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
public:
void setUp() void setUp()
{ {
} }
void tearDown() void tearDown()
{ {
} }
@ -387,7 +376,6 @@ public:
} }
} }
void altertablemodifycolumntype() void altertablemodifycolumntype()
{ {
SqlFileParser p; SqlFileParser p;
@ -402,7 +390,6 @@ public:
} }
} }
void altertablerenametable() void altertablerenametable()
{ {
SqlFileParser p; SqlFileParser p;
@ -459,7 +446,6 @@ public:
} }
} }
void altertabledropcolumn() void altertabledropcolumn()
{ {
SqlFileParser p; SqlFileParser p;
@ -488,7 +474,6 @@ public:
} }
} }
void altertableaddcolumn() void altertableaddcolumn()
{ {
cout << "Serialize test: AtaAddColumn" << endl; cout << "Serialize test: AtaAddColumn" << endl;
@ -524,9 +509,7 @@ public:
ColumnDefList::const_iterator itr; ColumnDefList::const_iterator itr;
for (itr = columns->begin(); for (itr = columns->begin(); itr != columns->end(); ++itr)
itr != columns->end();
++itr)
{ {
ata->fColumnDef = *itr; ata->fColumnDef = *itr;
t_sertest<AtaAddColumn>(ata.get()); t_sertest<AtaAddColumn>(ata.get());
@ -578,7 +561,6 @@ public:
} }
} }
void altertabledropcolumns() void altertabledropcolumns()
{ {
ColumnNameList* names = new ColumnNameList; ColumnNameList* names = new ColumnNameList;
@ -588,7 +570,6 @@ public:
t_sertest<AtaDropColumns>(stmt.get()); t_sertest<AtaDropColumns>(stmt.get());
} }
void qname() void qname()
{ {
cout << "Serialize test: QualifiedName" << endl; cout << "Serialize test: QualifiedName" << endl;
@ -596,7 +577,6 @@ public:
u_sertest<QualifiedName>(name.get()); u_sertest<QualifiedName>(name.get());
} }
void columntype() void columntype()
{ {
cout << "Serialize test: ColumnType" << endl; cout << "Serialize test: ColumnType" << endl;
@ -682,15 +662,12 @@ public:
ColumnDefList::const_iterator itr; ColumnDefList::const_iterator itr;
for (itr = columns->begin(); for (itr = columns->begin(); itr != columns->end(); ++itr)
itr != columns->end();
++itr)
{ {
u_sertest<ColumnDef>(*itr); u_sertest<ColumnDef>(*itr);
} }
} }
} }
} }
void referentialaction() void referentialaction()
@ -749,7 +726,6 @@ public:
qname->fName = "table_fooby"; qname->fName = "table_fooby";
tc->fTableName = qname; tc->fTableName = qname;
tc->fForeignColumns.push_back("F1"); tc->fForeignColumns.push_back("F1");
tc->fForeignColumns.push_back("F2"); tc->fForeignColumns.push_back("F2");
tc->fForeignColumns.push_back("F3"); tc->fForeignColumns.push_back("F3");
@ -801,10 +777,8 @@ public:
u_sertest<TableDef>(ct->fTableDef); u_sertest<TableDef>(ct->fTableDef);
} }
} }
} }
void createtable() void createtable()
{ {
vector<string> files; vector<string> files;
@ -933,15 +907,13 @@ CPPUNIT_TEST_SUITE_REGISTRATION(ParserTest);
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
CppUnit::TextUi::TestRunner runner; CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() ); runner.addTest(registry.makeTest());
bool wasSuccessful = runner.run( "", false ); bool wasSuccessful = runner.run("", false);
return (wasSuccessful ? 0 : 1); return (wasSuccessful ? 0 : 1);
} }
string itoa(const int i) string itoa(const int i)
@ -950,4 +922,3 @@ string itoa(const int i)
ss << i; ss << i;
return ss.str(); return ss.str();
} }

File diff suppressed because it is too large Load Diff

View File

@ -39,8 +39,10 @@ namespace ddlpackageprocessor
*/ */
class AlterTableProcessor : public DDLPackageProcessor class AlterTableProcessor : public DDLPackageProcessor
{ {
public: public:
AlterTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} AlterTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
{
}
/** @brief process an alter table statement /** @brief process an alter table statement
* *
* @param alterTableStmt the AlterTableStatement * @param alterTableStmt the AlterTableStatement
@ -53,8 +55,8 @@ public:
* @param fTableName the QualifiedName of the table * @param fTableName the QualifiedName of the table
*/ */
EXPORT void addColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void addColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result,
ddlpackage::ColumnDef* columnDefPtr, ddlpackage::ColumnDef* columnDefPtr, ddlpackage::QualifiedName& fTableName,
ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); const uint64_t uniqueId);
/** @brief drop a column /** @brief drop a column
* *
@ -63,8 +65,8 @@ public:
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void dropColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void dropColumn(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result,
ddlpackage::AtaDropColumn& ataDropColumn, ddlpackage::AtaDropColumn& ataDropColumn, ddlpackage::QualifiedName& fTableName,
ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); const uint64_t uniqueId);
/** @brief drop columns /** @brief drop columns
* *
@ -73,8 +75,8 @@ public:
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void dropColumns(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void dropColumns(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result,
ddlpackage::AtaDropColumns& ataDropColumns, ddlpackage::AtaDropColumns& ataDropColumns, ddlpackage::QualifiedName& fTableName,
ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId ); const uint64_t uniqueId);
/** @brief add table constraint /** @brief add table constraint
* *
@ -82,9 +84,9 @@ public:
* @param ataAddTableConstraint the AtaDropColumn object * @param ataAddTableConstraint the AtaDropColumn object
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void addTableConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void addTableConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
ddlpackage::AtaAddTableConstraint& ataAddTableConstraint, DDLResult& result, ddlpackage::AtaAddTableConstraint& ataAddTableConstraint,
ddlpackage::QualifiedName& fTableName ); ddlpackage::QualifiedName& fTableName);
/** @brief set column default /** @brief set column default
* *
@ -92,9 +94,9 @@ public:
* @param ataSetColumnDefault the AtaSetColumnDefault object * @param ataSetColumnDefault the AtaSetColumnDefault object
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void setColumnDefault(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void setColumnDefault(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
ddlpackage::AtaSetColumnDefault& ataSetColumnDefault, DDLResult& result, ddlpackage::AtaSetColumnDefault& ataSetColumnDefault,
ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId ); ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId);
/** @brief drop column default /** @brief drop column default
* *
@ -102,9 +104,9 @@ public:
* @param ataDropColumnDefault the AtaDropColumnDefault object * @param ataDropColumnDefault the AtaDropColumnDefault object
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void dropColumnDefault(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void dropColumnDefault(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
ddlpackage::AtaDropColumnDefault& ataDropColumnDefault, DDLResult& result, ddlpackage::AtaDropColumnDefault& ataDropColumnDefault,
ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId ); ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId);
/** @brief drop table constraint /** @brief drop table constraint
* *
@ -112,18 +114,19 @@ public:
* @param ataDropTableConstraint the AtaDropTableConstraint object * @param ataDropTableConstraint the AtaDropTableConstraint object
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void dropTableConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, EXPORT void dropTableConstraint(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
DDLResult& result,
ddlpackage::AtaDropTableConstraint& ataDropTableConstraint, ddlpackage::AtaDropTableConstraint& ataDropTableConstraint,
ddlpackage::QualifiedName& fTableName ); ddlpackage::QualifiedName& fTableName);
/** @brief rename a table /** @brief rename a table
* *
* @param result the result of the operation * @param result the result of the operation
* @param ataRenameTable the AtaRenameTable object * @param ataRenameTable the AtaRenameTable object
* @param fTableName the QualifiedName for the table * @param fTableName the QualifiedName for the table
*/ */
EXPORT void renameTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, EXPORT void renameTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result,
DDLResult& result, ddlpackage::AtaRenameTable& ataRenameTable, ddlpackage::AtaRenameTable& ataRenameTable, ddlpackage::QualifiedName& fTableName,
ddlpackage::QualifiedName& fTableName, const uint64_t uniqueId); const uint64_t uniqueId);
/** @brief rename a column /** @brief rename a column
* *
@ -147,14 +150,13 @@ public:
std::string fTimeZone; std::string fTimeZone;
protected: protected:
void rollBackAlter(const std::string& error, BRM::TxnID txnID, int sessionId, DDLResult& result, uint64_t uniqueId); void rollBackAlter(const std::string& error, BRM::TxnID txnID, int sessionId, DDLResult& result,
uint64_t uniqueId);
private:
private:
}; };
} //namespace ddlpackageprocessor } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT

View File

@ -37,8 +37,8 @@ using namespace logging;
using namespace BRM; using namespace BRM;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(
CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage::CreateIndexStatement& createIndexStmt) ddlpackage::CreateIndexStatement& createIndexStmt)
{ {
/* /*
get OIDs for the list & tree files get OIDs for the list & tree files
@ -65,25 +65,25 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
tableName.schema = (createIndexStmt.fTableName)->fSchema; tableName.schema = (createIndexStmt.fTableName)->fSchema;
tableName.table = (createIndexStmt.fTableName)->fName; tableName.table = (createIndexStmt.fTableName)->fName;
CalpontSystemCatalog::ROPair roPair; CalpontSystemCatalog::ROPair roPair;
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog( createIndexStmt.fSessionID ); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(createIndexStmt.fSessionID);
try try
{ {
roPair = systemCatalogPtr->tableRID( tableName ); roPair = systemCatalogPtr->tableRID(tableName);
} }
catch (exception& ex) catch (exception& ex)
{ {
// store primary key name in fPKName // store primary key name in fPKName
fPKName = createIndexStmt.fIndexName->fName; fPKName = createIndexStmt.fIndexName->fName;
return result; return result;
} }
catch (...) catch (...)
{ {
return result; return result;
} }
if ( roPair.objnum < 3000 ) if (roPair.objnum < 3000)
{ {
return result; return result;
} }
@ -91,29 +91,28 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
fPKName = createIndexStmt.fIndexName->fName; fPKName = createIndexStmt.fIndexName->fName;
int err = 0; int err = 0;
SQLLogger logger(createIndexStmt.fSql, fDDLLoggingId, createIndexStmt.fSessionID, txnID.id); SQLLogger logger(createIndexStmt.fSql, fDDLLoggingId, createIndexStmt.fSessionID, txnID.id);
VERBOSE_INFO("Allocating object IDs for columns"); VERBOSE_INFO("Allocating object IDs for columns");
// int oidbase = fObjectIDManager.allocOIDs(2); // int oidbase = fObjectIDManager.allocOIDs(2);
// fIdxOID.listOID = oidbase; // fIdxOID.listOID = oidbase;
// fIdxOID.treeOID = ++oidbase; // fIdxOID.treeOID = ++oidbase;
VERBOSE_INFO("Starting a new transaction"); VERBOSE_INFO("Starting a new transaction");
ddlpackage::DDL_CONSTRAINTS type = createIndexStmt.fUnique ? ddlpackage::DDL_UNIQUE : ddlpackage::DDL_INVALID_CONSTRAINT; ddlpackage::DDL_CONSTRAINTS type =
createIndexStmt.fUnique ? ddlpackage::DDL_UNIQUE : ddlpackage::DDL_INVALID_CONSTRAINT;
VERBOSE_INFO("Writing meta data to SYSINDEX"); VERBOSE_INFO("Writing meta data to SYSINDEX");
bool multicol = false; bool multicol = false;
if ( createIndexStmt.fColumnNames.size() > 1 ) if (createIndexStmt.fColumnNames.size() > 1)
{ {
multicol = true; multicol = true;
} }
//validate index columns // validate index columns
CalpontSystemCatalog::TableColName tableColName; CalpontSystemCatalog::TableColName tableColName;
tableColName.schema = (createIndexStmt.fTableName)->fSchema; tableColName.schema = (createIndexStmt.fTableName)->fSchema;
tableColName.table = (createIndexStmt.fTableName)->fName; tableColName.table = (createIndexStmt.fTableName)->fName;
@ -122,22 +121,23 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
ColumnNameList::const_iterator colIter; ColumnNameList::const_iterator colIter;
int totalWidth = 0; int totalWidth = 0;
DDLIndexPopulator pop(&fWriteEngine, &fSessionManager, createIndexStmt.fSessionID, txnID.id, result, DDLIndexPopulator pop(&fWriteEngine, &fSessionManager, createIndexStmt.fSessionID, txnID.id, result,
fIdxOID, createIndexStmt.fColumnNames, *createIndexStmt.fTableName, fIdxOID, createIndexStmt.fColumnNames, *createIndexStmt.fTableName, type,
type, getDebugLevel()); getDebugLevel());
if ( multicol) if (multicol)
{ {
for ( colIter = createIndexStmt.fColumnNames.begin(); colIter != createIndexStmt.fColumnNames.end(); colIter++) for (colIter = createIndexStmt.fColumnNames.begin(); colIter != createIndexStmt.fColumnNames.end();
colIter++)
{ {
tableColName.column = *colIter; tableColName.column = *colIter;
roPair = systemCatalogPtr->columnRID( tableColName ); roPair = systemCatalogPtr->columnRID(tableColName);
oid = systemCatalogPtr->lookupOID( tableColName ); oid = systemCatalogPtr->lookupOID(tableColName);
colType = systemCatalogPtr->colType (oid ); colType = systemCatalogPtr->colType(oid);
totalWidth += (pop.isDictionaryType(colType)) ? 8 : colType.colWidth; totalWidth += (pop.isDictionaryType(colType)) ? 8 : colType.colWidth;
} }
if ( totalWidth > 32 ) if (totalWidth > 32)
{ {
stringstream ss; stringstream ss;
ss << totalWidth; ss << totalWidth;
@ -147,7 +147,7 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
args.add("Error creating index: "); args.add("Error creating index: ");
args.add("Total indexed column width"); args.add("Total indexed column width");
args.add("greater than 32. "); args.add("greater than 32. ");
message.format( args ); message.format(args);
result.result = CREATE_ERROR; result.result = CREATE_ERROR;
result.message = message; result.message = message;
@ -157,13 +157,15 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
try try
{ {
//writeSysIndexMetaData(createIndexStmt.fSessionID, txnID.id, result, *createIndexStmt.fTableName, type, createIndexStmt.fIndexName->fName, multicol); // writeSysIndexMetaData(createIndexStmt.fSessionID, txnID.id, result, *createIndexStmt.fTableName, type,
// createIndexStmt.fIndexName->fName, multicol);
//fIdxOID values are set in writeSysIndexMetaData. // fIdxOID values are set in writeSysIndexMetaData.
pop.setIdxOID(fIdxOID); pop.setIdxOID(fIdxOID);
VERBOSE_INFO("Writing meta data to SYSINDEXCOL"); VERBOSE_INFO("Writing meta data to SYSINDEXCOL");
//writeSysIndexColMetaData(createIndexStmt.fSessionID, txnID.id, result,*createIndexStmt.fTableName, createIndexStmt.fColumnNames, createIndexStmt.fIndexName->fName ); // writeSysIndexColMetaData(createIndexStmt.fSessionID, txnID.id, result,*createIndexStmt.fTableName,
// createIndexStmt.fColumnNames, createIndexStmt.fIndexName->fName );
if (createIndexStmt.fUnique) if (createIndexStmt.fUnique)
{ {
@ -187,11 +189,12 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
// get the columns for the SYSCONSTRAINT table // get the columns for the SYSCONSTRAINT table
ColumnList sysConsColumns; ColumnList sysConsColumns;
ColumnList::const_iterator sysCons_iterator; ColumnList::const_iterator sysCons_iterator;
getColumnsForTable(createIndexStmt.fSessionID, sysConsTableName.schema, sysConsTableName.table, sysConsColumns); getColumnsForTable(createIndexStmt.fSessionID, sysConsTableName.schema, sysConsTableName.table,
sysConsColumns);
sysCons_iterator = sysConsColumns.begin(); sysCons_iterator = sysConsColumns.begin();
std::string idxData; std::string idxData;
while ( sysCons_iterator != sysConsColumns.end() ) while (sysCons_iterator != sysConsColumns.end())
{ {
column = *sysCons_iterator; column = *sysCons_iterator;
isNull = false; isNull = false;
@ -220,7 +223,7 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
} }
else if (CONSTRAINTPRIM_COL == column.tableColName.column) else if (CONSTRAINTPRIM_COL == column.tableColName.column)
{ {
colTuple.data =column.colType.getNullValueForType(); colTuple.data = column.colType.getNullValueForType();
isNull = true; isNull = true;
} }
else if (CONSTRAINTTEXT_COL == column.tableColName.column) else if (CONSTRAINTTEXT_COL == column.tableColName.column)
@ -251,11 +254,11 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
colTuple.data = tokenizeData(txnID.id, result, column.colType, colTuple.data); colTuple.data = tokenizeData(txnID.id, result, column.colType, colTuple.data);
} }
colStructs.push_back( colStruct ); colStructs.push_back(colStruct);
colTuples.push_back( colTuple ); colTuples.push_back(colTuple);
colValuesList.push_back( colTuples ); colValuesList.push_back(colTuples);
colTuples.pop_back(); colTuples.pop_back();
++sysCons_iterator; ++sysCons_iterator;
@ -263,22 +266,22 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
if (colStructs.size() != 0) if (colStructs.size() != 0)
{ {
//fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3); // fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3);
//error = fWriteEngine.insertColumnRec( txnID.id, colStructs, colValuesList, ridList ); // error = fWriteEngine.insertColumnRec( txnID.id, colStructs, colValuesList, ridList );
if ( error != WriteEngine::NO_ERROR ) if (error != WriteEngine::NO_ERROR)
{ {
return rollBackCreateIndex(errorString("WE: Error inserting Column Record: ", error), txnID,
return rollBackCreateIndex(errorString( "WE: Error inserting Column Record: ", error), txnID, createIndexStmt.fSessionID); createIndexStmt.fSessionID);
// logging::Message::Args args; // logging::Message::Args args;
// logging::Message message(9); // logging::Message message(9);
// args.add("Error updating: "); // args.add("Error updating: ");
// args.add("calpont.sysconstraint"); // args.add("calpont.sysconstraint");
// args.add("error number: "); // args.add("error number: ");
// args.add( error ); // args.add( error );
// message.format( args ); // message.format( args );
// //
// result.result = CREATE_ERROR; // result.result = CREATE_ERROR;
// result.message = message; // result.message = message;
} }
else else
{ {
@ -302,12 +305,13 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
// get the columns for the SYSCONSTRAINTCOL table // get the columns for the SYSCONSTRAINTCOL table
ColumnList sysConsColColumns; ColumnList sysConsColColumns;
ColumnList::const_iterator sysConsCol_iterator; ColumnList::const_iterator sysConsCol_iterator;
getColumnsForTable(createIndexStmt.fSessionID, sysConsColTableName.schema, sysConsColTableName.table, sysConsColColumns); getColumnsForTable(createIndexStmt.fSessionID, sysConsColTableName.schema, sysConsColTableName.table,
sysConsColColumns);
// write sysconstraintcol // write sysconstraintcol
sysConsCol_iterator = sysConsColColumns.begin(); sysConsCol_iterator = sysConsColColumns.begin();
std::string colData; std::string colData;
while ( sysConsCol_iterator != sysConsColColumns.end() ) while (sysConsCol_iterator != sysConsColColumns.end())
{ {
column = *sysConsCol_iterator; column = *sysConsCol_iterator;
@ -327,7 +331,6 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
{ {
colData = createIndexStmt.fColumnNames[0]; colData = createIndexStmt.fColumnNames[0];
colTupleCol.data = colData; colTupleCol.data = colData;
} }
else if (CONSTRAINTNAME_COL == column.tableColName.column) else if (CONSTRAINTNAME_COL == column.tableColName.column)
{ {
@ -351,11 +354,11 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
colTupleCol.data = tokenizeData(txnID.id, result, column.colType, colTupleCol.data); colTupleCol.data = tokenizeData(txnID.id, result, column.colType, colTupleCol.data);
} }
colStructsCol.push_back( colStructCol ); colStructsCol.push_back(colStructCol);
colTuplesCol.push_back( colTupleCol ); colTuplesCol.push_back(colTupleCol);
colValuesListCol.push_back( colTuplesCol ); colValuesListCol.push_back(colTuplesCol);
colTuplesCol.pop_back(); colTuplesCol.pop_back();
@ -364,11 +367,12 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
if (colStructsCol.size() != 0) if (colStructsCol.size() != 0)
{ {
//fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3); // fWriteEngine.setDebugLevel(WriteEngine::DEBUG_3);
//error = fWriteEngine.insertColumnRec( txnID.id, colStructsCol, colValuesListCol, ridList ); // error = fWriteEngine.insertColumnRec( txnID.id, colStructsCol, colValuesListCol, ridList );
if ( error != WriteEngine::NO_ERROR ) if (error != WriteEngine::NO_ERROR)
{ {
return rollBackCreateIndex(errorString( "WE: Error inserting Column Record: ", error), txnID, createIndexStmt.fSessionID); return rollBackCreateIndex(errorString("WE: Error inserting Column Record: ", error), txnID,
createIndexStmt.fSessionID);
/* logging::Message::Args args; /* logging::Message::Args args;
logging::Message message(9); logging::Message message(9);
@ -389,35 +393,37 @@ CreateIndexProcessor::DDLResult CreateIndexProcessor::processPackage(ddlpackage:
} }
VERBOSE_INFO("Creating index files"); VERBOSE_INFO("Creating index files");
err = fWriteEngine.createIndex( txnID.id, fIdxOID.treeOID, fIdxOID.listOID ); err = fWriteEngine.createIndex(txnID.id, fIdxOID.treeOID, fIdxOID.listOID);
if (err) if (err)
{ {
return rollBackCreateIndex(errorString("Write engine failed to create the new index. ", err), txnID, createIndexStmt.fSessionID); return rollBackCreateIndex(errorString("Write engine failed to create the new index. ", err), txnID,
createIndexStmt.fSessionID);
} }
// new if BULK_LOAD close // new if BULK_LOAD close
err = pop.populateIndex(result); err = pop.populateIndex(result);
if ( err ) if (err)
{ {
return rollBackCreateIndex(errorString("Failed to populate index with current data. ", err), txnID, createIndexStmt.fSessionID); return rollBackCreateIndex(errorString("Failed to populate index with current data. ", err), txnID,
createIndexStmt.fSessionID);
} }
// Log the DDL statement. // Log the DDL statement.
logging::logDDL(createIndexStmt.fSessionID, txnID.id, createIndexStmt.fSql, createIndexStmt.fOwner); logging::logDDL(createIndexStmt.fSessionID, txnID.id, createIndexStmt.fSql, createIndexStmt.fOwner);
DETAIL_INFO("Commiting transaction"); DETAIL_INFO("Commiting transaction");
err = fWriteEngine.commit( txnID.id ); err = fWriteEngine.commit(txnID.id);
if (err) if (err)
{ {
return rollBackCreateIndex(errorString("Failed to commit the create index transaction. ", err), txnID, createIndexStmt.fSessionID); return rollBackCreateIndex(errorString("Failed to commit the create index transaction. ", err), txnID,
createIndexStmt.fSessionID);
} }
fSessionManager.committed(txnID); fSessionManager.committed(txnID);
// original if BULK_LOAD close } // original if BULK_LOAD close }
} // try } // try
catch (exception& ex) catch (exception& ex)
@ -439,18 +445,18 @@ string CreateIndexProcessor::errorString(const string& msg, int error)
return string(msg + ec.errorString(error)); return string(msg + ec.errorString(error));
} }
CreateIndexProcessor::DDLResult CreateIndexProcessor::rollBackCreateIndex(const string& error,
CreateIndexProcessor::DDLResult CreateIndexProcessor::rollBackCreateIndex(const string& error, BRM::TxnID& txnID, int sessionId) BRM::TxnID& txnID, int sessionId)
{ {
cerr << "CreatetableProcessor::processPackage: " << error << endl; cerr << "CreatetableProcessor::processPackage: " << error << endl;
DETAIL_INFO(error); DETAIL_INFO(error);
logging::Message::Args args; logging::Message::Args args;
logging::Message message(1); logging::Message message(1);
args.add("Create Index Failed: "); args.add("Create Index Failed: ");
args.add( error ); args.add(error);
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
DDLResult result; DDLResult result;
result.result = CREATE_ERROR; result.result = CREATE_ERROR;
result.message = message; result.message = message;
@ -465,18 +471,17 @@ void CreateIndexProcessor::rollBackIndex(BRM::TxnID& txnID, int sessionId)
try try
{ {
//execplan::ObjectIDManager fObjectIDManager; // execplan::ObjectIDManager fObjectIDManager;
//fObjectIDManager.returnOIDs(fIdxOID.treeOID, fIdxOID.listOID); // fObjectIDManager.returnOIDs(fIdxOID.treeOID, fIdxOID.listOID);
} }
catch ( exception& ex ) catch (exception& ex)
{
}
catch (...)
{ {
} }
catch (... )
{ }
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
} }
} // namespace ddlpackageprocessor
}

View File

@ -34,19 +34,19 @@ namespace ddlpackageprocessor
*/ */
class CreateIndexProcessor : public DDLPackageProcessor class CreateIndexProcessor : public DDLPackageProcessor
{ {
public: public:
/** @brief process a create index statement /** @brief process a create index statement
* *
* @param createIndexStmt the create index statement * @param createIndexStmt the create index statement
*/ */
DDLResult processPackage(ddlpackage::CreateIndexStatement& createIndexStmt); DDLResult processPackage(ddlpackage::CreateIndexStatement& createIndexStmt);
protected: protected:
DDLResult rollBackCreateIndex(const std::string& error, BRM::TxnID& txnID, int sessionId); DDLResult rollBackCreateIndex(const std::string& error, BRM::TxnID& txnID, int sessionId);
void rollBackIndex(BRM::TxnID& txnID); void rollBackIndex(BRM::TxnID& txnID);
std::string errorString(const std::string& msg, int error); std::string errorString(const std::string& msg, int error);
private:
private:
}; };
} //namespace ddlpackageprocessor } // namespace ddlpackageprocessor

View File

@ -47,7 +47,6 @@ using namespace logging;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
CreateTableProcessor::DDLResult CreateTableProcessor::processPackage( CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
ddlpackage::CreateTableStatement& createTableStmt) ddlpackage::CreateTableStatement& createTableStmt)
{ {
@ -61,7 +60,7 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
int rc1 = 0; int rc1 = 0;
rc1 = fDbrm->isReadWrite(); rc1 = fDbrm->isReadWrite();
if (rc1 != 0 ) if (rc1 != 0)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
@ -75,11 +74,11 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
DETAIL_INFO(createTableStmt); DETAIL_INFO(createTableStmt);
ddlpackage::TableDef& tableDef = *createTableStmt.fTableDef; ddlpackage::TableDef& tableDef = *createTableStmt.fTableDef;
//If schema = CALPONTSYS, do not create table // If schema = CALPONTSYS, do not create table
if (tableDef.fQualifiedName->fSchema == CALPONT_SCHEMA) if (tableDef.fQualifiedName->fSchema == CALPONT_SCHEMA)
{ {
//release the transaction // release the transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -88,7 +87,7 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
// all DDL statements cause an implicut commit // all DDL statements cause an implicut commit
VERBOSE_INFO("Getting current txnID"); VERBOSE_INFO("Getting current txnID");
//Check whether the table is existed already // Check whether the table is existed already
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(createTableStmt.fSessionID); CalpontSystemCatalog::makeCalpontSystemCatalog(createTableStmt.fSessionID);
execplan::CalpontSystemCatalog::TableName tableName; execplan::CalpontSystemCatalog::TableName tableName;
@ -109,7 +108,7 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
// TODO: What is and is not an error here? // TODO: What is and is not an error here?
if (ie.errorCode() == ERR_DATA_OFFLINE) if (ie.errorCode() == ERR_DATA_OFFLINE)
{ {
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
// Return the error for display to user // Return the error for display to user
Message::Args args; Message::Args args;
@ -120,13 +119,13 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
result.message = message; result.message = message;
return result; return result;
} }
else if ( ie.errorCode() == ERR_TABLE_NOT_IN_CATALOG) else if (ie.errorCode() == ERR_TABLE_NOT_IN_CATALOG)
{ {
roPair.objnum = 0; roPair.objnum = 0;
} }
else //error out else // error out
{ {
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
// Return the error for display to user // Return the error for display to user
Message::Args args; Message::Args args;
@ -138,9 +137,9 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
return result; return result;
} }
} }
catch (std::exception& ex) //error out catch (std::exception& ex) // error out
{ {
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
// Return the error for display to user // Return the error for display to user
Message::Args args; Message::Args args;
@ -151,9 +150,9 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
result.message = message; result.message = message;
return result; return result;
} }
catch (...) //error out catch (...) // error out
{ {
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
// Return the error for display to user // Return the error for display to user
Message::Args args; Message::Args args;
@ -165,11 +164,11 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
return result; return result;
} }
//This is a current db bug, it should not turn OID is it cannot find // This is a current db bug, it should not turn OID is it cannot find
if (roPair.objnum >= 3000) if (roPair.objnum >= 3000)
{ {
#ifdef _MSC_VER #ifdef _MSC_VER
//FIXME: Why do we need to do this??? // FIXME: Why do we need to do this???
systemCatalogPtr->flushCache(); systemCatalogPtr->flushCache();
try try
@ -195,7 +194,7 @@ CreateTableProcessor::DDLResult CreateTableProcessor::processPackage(
result.result = CREATE_ERROR; result.result = CREATE_ERROR;
result.message = message; result.message = message;
//release the transaction // release the transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -209,15 +208,14 @@ keepGoing:
string stmt = createTableStmt.fSql + "|" + tableDef.fQualifiedName->fSchema + "|"; string stmt = createTableStmt.fSql + "|" + tableDef.fQualifiedName->fSchema + "|";
SQLLogger logger(stmt, fDDLLoggingId, createTableStmt.fSessionID, txnID.id); SQLLogger logger(stmt, fDDLLoggingId, createTableStmt.fSessionID, txnID.id);
std::string err; std::string err;
execplan::ObjectIDManager fObjectIDManager; execplan::ObjectIDManager fObjectIDManager;
OamCache* oamcache = OamCache::makeOamCache(); OamCache* oamcache = OamCache::makeOamCache();
string errorMsg; string errorMsg;
//get a unique number // get a unique number
uint64_t uniqueId = 0; uint64_t uniqueId = 0;
//Bug 5070. Added exception handling // Bug 5070. Added exception handling
try try
{ {
uniqueId = fDbrm->getUnique64(); uniqueId = fDbrm->getUnique64();
@ -233,7 +231,7 @@ keepGoing:
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
catch ( ... ) catch (...)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
@ -249,7 +247,7 @@ keepGoing:
try try
{ {
//Allocate tableoid table identification // Allocate tableoid table identification
VERBOSE_INFO("Allocating object ID for table"); VERBOSE_INFO("Allocating object ID for table");
// Allocate a object ID for each column we are about to create // Allocate a object ID for each column we are about to create
VERBOSE_INFO("Allocating object IDs for columns"); VERBOSE_INFO("Allocating object IDs for columns");
@ -261,15 +259,16 @@ keepGoing:
int dataType; int dataType;
dataType = convertDataType(tableDef.fColumns[i]->fType->fType); dataType = convertDataType(tableDef.fColumns[i]->fType->fType);
if ( (dataType == CalpontSystemCatalog::CHAR && tableDef.fColumns[i]->fType->fLength > 8) || if ((dataType == CalpontSystemCatalog::CHAR && tableDef.fColumns[i]->fType->fLength > 8) ||
(dataType == CalpontSystemCatalog::VARCHAR && tableDef.fColumns[i]->fType->fLength > 7) || (dataType == CalpontSystemCatalog::VARCHAR && tableDef.fColumns[i]->fType->fLength > 7) ||
(dataType == CalpontSystemCatalog::VARBINARY && tableDef.fColumns[i]->fType->fLength > 7) || (dataType == CalpontSystemCatalog::VARBINARY && tableDef.fColumns[i]->fType->fLength > 7) ||
(dataType == CalpontSystemCatalog::BLOB && tableDef.fColumns[i]->fType->fLength > 7) || (dataType == CalpontSystemCatalog::BLOB && tableDef.fColumns[i]->fType->fLength > 7) ||
(dataType == CalpontSystemCatalog::TEXT && tableDef.fColumns[i]->fType->fLength > 7) ) (dataType == CalpontSystemCatalog::TEXT && tableDef.fColumns[i]->fType->fLength > 7))
numDictCols++; numDictCols++;
} }
fStartingColOID = fObjectIDManager.allocOIDs(numColumns + numDictCols + 1); //include column, oids,dictionary oids and tableoid fStartingColOID = fObjectIDManager.allocOIDs(numColumns + numDictCols +
1); // include column, oids,dictionary oids and tableoid
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Create table allocOIDs got the starting oid " << fStartingColOID << endl; cout << fTxnid.id << " Create table allocOIDs got the starting oid " << fStartingColOID << endl;
#endif #endif
@ -293,25 +292,25 @@ keepGoing:
ByteStream bytestream; ByteStream bytestream;
bytestream << (ByteStream::byte)WE_SVR_WRITE_SYSTABLE; bytestream << (ByteStream::byte)WE_SVR_WRITE_SYSTABLE;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) createTableStmt.fSessionID; bytestream << (uint32_t)createTableStmt.fSessionID;
bytestream << (uint32_t)txnID.id; bytestream << (uint32_t)txnID.id;
bytestream << (uint32_t)fStartingColOID; bytestream << (uint32_t)fStartingColOID;
bytestream << (uint32_t)createTableStmt.fTableWithAutoi; bytestream << (uint32_t)createTableStmt.fTableWithAutoi;
uint16_t dbRoot; uint16_t dbRoot;
BRM::OID_t sysOid = 1001; BRM::OID_t sysOid = 1001;
//Find out where systable is // Find out where systable is
rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot);
if (rc != 0) if (rc != 0)
{ {
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Error while calling getSysCatDBRoot "); args.add("Error while calling getSysCatDBRoot ");
args.add(errorMsg); args.add(errorMsg);
message.format(args); message.format(args);
result.message = message; result.message = message;
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -337,7 +336,7 @@ keepGoing:
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
@ -360,7 +359,7 @@ keepGoing:
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " create table got exception" << ex.what() << endl; cout << fTxnid.id << " create table got exception" << ex.what() << endl;
@ -381,20 +380,20 @@ keepGoing:
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl; cout << fTxnid.id << " Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl;
#endif #endif
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("(2)Create table failed due to "); args.add("(2)Create table failed due to ");
args.add(errorMsg); args.add(errorMsg);
message.format( args ); message.format(args);
result.message = message; result.message = message;
if (rc != NETWORK_ERROR) if (rc != NETWORK_ERROR)
{ {
rollBackTransaction( uniqueId, txnID, createTableStmt.fSessionID ); //What to do with the error code rollBackTransaction(uniqueId, txnID, createTableStmt.fSessionID); // What to do with the error code
} }
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -403,7 +402,7 @@ keepGoing:
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte)WE_SVR_WRITE_CREATE_SYSCOLUMN; bytestream << (ByteStream::byte)WE_SVR_WRITE_CREATE_SYSCOLUMN;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) createTableStmt.fSessionID; bytestream << (uint32_t)createTableStmt.fSessionID;
bytestream << (uint32_t)txnID.id; bytestream << (uint32_t)txnID.id;
bytestream << numColumns; bytestream << numColumns;
@ -425,19 +424,19 @@ keepGoing:
bytestream << (uint32_t)colPos; bytestream << (uint32_t)colPos;
sysOid = 1021; sysOid = 1021;
//Find out where syscolumn is // Find out where syscolumn is
rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot);
if (rc != 0) if (rc != 0)
{ {
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Error while calling getSysCatDBRoot "); args.add("Error while calling getSysCatDBRoot ");
args.add(errorMsg); args.add(errorMsg);
message.format(args); message.format(args);
result.message = message; result.message = message;
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -458,7 +457,7 @@ keepGoing:
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
@ -481,7 +480,7 @@ keepGoing:
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " create table got exception" << ex.what() << endl; cout << fTxnid.id << " create table got exception" << ex.what() << endl;
@ -502,33 +501,32 @@ keepGoing:
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Create table WE_SVR_WRITE_CREATE_SYSCOLUMN: " << errorMsg << endl; cout << fTxnid.id << " Create table WE_SVR_WRITE_CREATE_SYSCOLUMN: " << errorMsg << endl;
#endif #endif
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("(3)Create table failed due to "); args.add("(3)Create table failed due to ");
args.add(errorMsg); args.add(errorMsg);
message.format( args ); message.format(args);
result.message = message; result.message = message;
if (rc != NETWORK_ERROR) if (rc != NETWORK_ERROR)
{ {
rollBackTransaction( uniqueId, txnID, createTableStmt.fSessionID ); //What to do with the error code rollBackTransaction(uniqueId, txnID, createTableStmt.fSessionID); // What to do with the error code
} }
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
// Get the number of tables in the database, the current table is included.
//Get the number of tables in the database, the current table is included.
int tableCount = systemCatalogPtr->getTableCount(); int tableCount = systemCatalogPtr->getTableCount();
//Calculate which dbroot the columns should start // Calculate which dbroot the columns should start
DBRootConfigList dbRootList = oamcache->getDBRootNums(); DBRootConfigList dbRootList = oamcache->getDBRootNums();
uint16_t useDBRootIndex = tableCount % dbRootList.size(); uint16_t useDBRootIndex = tableCount % dbRootList.size();
//Find out the dbroot# corresponding the useDBRootIndex from oam // Find out the dbroot# corresponding the useDBRootIndex from oam
uint16_t useDBRoot = dbRootList[useDBRootIndex]; uint16_t useDBRoot = dbRootList[useDBRootIndex];
VERBOSE_INFO("Creating column files"); VERBOSE_INFO("Creating column files");
@ -549,8 +547,7 @@ keepGoing:
CalpontSystemCatalog::ColDataType dataType = convertDataType(colDefPtr->fType->fType); CalpontSystemCatalog::ColDataType dataType = convertDataType(colDefPtr->fType->fType);
if (dataType == CalpontSystemCatalog::DECIMAL || if (dataType == CalpontSystemCatalog::DECIMAL || dataType == CalpontSystemCatalog::UDECIMAL)
dataType == CalpontSystemCatalog::UDECIMAL)
{ {
if (colDefPtr->fType->fPrecision == -1 || colDefPtr->fType->fPrecision == 0) if (colDefPtr->fType->fPrecision == -1 || colDefPtr->fType->fPrecision == 0)
{ {
@ -580,32 +577,32 @@ keepGoing:
} }
bytestream << (fStartingColOID + (colNum++) + 1); bytestream << (fStartingColOID + (colNum++) + 1);
bytestream << (uint8_t) dataType; bytestream << (uint8_t)dataType;
bytestream << (uint8_t) false; bytestream << (uint8_t) false;
bytestream << (uint32_t) colDefPtr->fType->fLength; bytestream << (uint32_t)colDefPtr->fType->fLength;
bytestream << (uint16_t) useDBRoot; bytestream << (uint16_t)useDBRoot;
bytestream << (uint32_t) colDefPtr->fType->fCompressiontype; bytestream << (uint32_t)colDefPtr->fType->fCompressiontype;
if ( (dataType == CalpontSystemCatalog::CHAR && colDefPtr->fType->fLength > 8) || if ((dataType == CalpontSystemCatalog::CHAR && colDefPtr->fType->fLength > 8) ||
(dataType == CalpontSystemCatalog::VARCHAR && colDefPtr->fType->fLength > 7) || (dataType == CalpontSystemCatalog::VARCHAR && colDefPtr->fType->fLength > 7) ||
(dataType == CalpontSystemCatalog::VARBINARY && colDefPtr->fType->fLength > 7) || (dataType == CalpontSystemCatalog::VARBINARY && colDefPtr->fType->fLength > 7) ||
(dataType == CalpontSystemCatalog::BLOB && colDefPtr->fType->fLength > 7) || (dataType == CalpontSystemCatalog::BLOB && colDefPtr->fType->fLength > 7) ||
(dataType == CalpontSystemCatalog::TEXT && colDefPtr->fType->fLength > 7) ) (dataType == CalpontSystemCatalog::TEXT && colDefPtr->fType->fLength > 7))
{ {
bytestream << (uint32_t) (fStartingColOID + numColumns + (dictNum++) + 1); bytestream << (uint32_t)(fStartingColOID + numColumns + (dictNum++) + 1);
bytestream << (uint8_t) dataType; bytestream << (uint8_t)dataType;
bytestream << (uint8_t) true; bytestream << (uint8_t) true;
bytestream << (uint32_t) colDefPtr->fType->fLength; bytestream << (uint32_t)colDefPtr->fType->fLength;
bytestream << (uint16_t) useDBRoot; bytestream << (uint16_t)useDBRoot;
bytestream << (uint32_t) colDefPtr->fType->fCompressiontype; bytestream << (uint32_t)colDefPtr->fType->fCompressiontype;
} }
++iter; ++iter;
} }
//@Bug 4176. save oids to a log file for cleanup after fail over. //@Bug 4176. save oids to a log file for cleanup after fail over.
std::vector <CalpontSystemCatalog::OID> oidList; std::vector<CalpontSystemCatalog::OID> oidList;
for (unsigned i = 0; i < numColumns; ++i) for (unsigned i = 0; i < numColumns; ++i)
{ {
@ -621,24 +618,24 @@ keepGoing:
try try
{ {
createWriteDropLogFile( fStartingColOID, uniqueId, oidList ); createWriteDropLogFile(fStartingColOID, uniqueId, oidList);
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("(4)Create table failed due to "); args.add("(4)Create table failed due to ");
args.add(ex.what()); args.add(ex.what());
message.format( args ); message.format(args);
result.message = message; result.message = message;
if (rc != NETWORK_ERROR) if (rc != NETWORK_ERROR)
{ {
rollBackTransaction( uniqueId, txnID, createTableStmt.fSessionID ); //What to do with the error code rollBackTransaction(uniqueId, txnID, createTableStmt.fSessionID); // What to do with the error code
} }
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -657,7 +654,7 @@ keepGoing:
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
@ -682,9 +679,9 @@ keepGoing:
if (rc != 0) if (rc != 0)
{ {
//drop the newly created files // drop the newly created files
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte) WE_SVR_WRITE_DROPFILES; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t)(numColumns + numDictCols); bytestream << (uint32_t)(numColumns + numDictCols);
@ -700,7 +697,7 @@ keepGoing:
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
break; break;
} }
@ -712,7 +709,6 @@ keepGoing:
//@Bug 5464. Delete from extent map. //@Bug 5464. Delete from extent map.
fDbrm->deleteOIDs(oidList); fDbrm->deleteOIDs(oidList);
} }
} }
catch (runtime_error&) catch (runtime_error&)
@ -725,7 +721,7 @@ keepGoing:
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl; cout << fTxnid.id << " Create table We_SVR_WRITE_CREATETABLEFILES: " << errorMsg << endl;
#endif #endif
rollBackTransaction( uniqueId, txnID, createTableStmt.fSessionID); //What to do with the error code rollBackTransaction(uniqueId, txnID, createTableStmt.fSessionID); // What to do with the error code
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
} }
else else
@ -746,14 +742,14 @@ keepGoing:
Message message(9); Message message(9);
args.add("(5)Create table failed due to "); args.add("(5)Create table failed due to ");
args.add(ex.what()); args.add(ex.what());
message.format( args ); message.format(args);
result.message = message; result.message = message;
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
return result; return result;
} }
//fWEClient->removeQueue(uniqueId); // fWEClient->removeQueue(uniqueId);
if (rc != 0) if (rc != 0)
{ {
result.result = CREATE_ERROR; result.result = CREATE_ERROR;
@ -761,7 +757,7 @@ keepGoing:
Message message(9); Message message(9);
args.add("(6)Create table failed due to "); args.add("(6)Create table failed due to ");
args.add(errorMsg); args.add(errorMsg);
message.format( args ); message.format(args);
result.message = message; result.message = message;
} }
@ -797,8 +793,7 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t
{ {
execplan::ObjectIDManager fObjectIDManager; execplan::ObjectIDManager fObjectIDManager;
fObjectIDManager.returnOID(fTableOID); fObjectIDManager.returnOID(fTableOID);
fObjectIDManager.returnOIDs(fStartingColOID, fObjectIDManager.returnOIDs(fStartingColOID, fStartingColOID + tableDef.fColumns.size() - 1);
fStartingColOID + tableDef.fColumns.size() - 1);
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
@ -817,7 +812,7 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t
message.format(args); message.format(args);
result.message = message; result.message = message;
result.result = CREATE_ERROR; result.result = CREATE_ERROR;
//cout << "returnOIDs error" << endl; // cout << "returnOIDs error" << endl;
} }
DictionaryOIDList::const_iterator dictoid_iter = fDictionaryOIDList.begin(); DictionaryOIDList::const_iterator dictoid_iter = fDictionaryOIDList.begin();
@ -826,7 +821,7 @@ void CreateTableProcessor::rollBackCreateTable(const string& error, BRM::TxnID t
{ {
DictOID dictOID = *dictoid_iter; DictOID dictOID = *dictoid_iter;
fWriteEngine.dropDctnry(txnID.id, dictOID.dictOID, dictOID.treeOID, dictOID.listOID); fWriteEngine.dropDctnry(txnID.id, dictOID.dictOID, dictOID.treeOID, dictOID.listOID);
//fObjectIDManager.returnOID(dictOID.dictOID); // fObjectIDManager.returnOID(dictOID.dictOID);
++dictoid_iter; ++dictoid_iter;
} }

View File

@ -33,30 +33,29 @@
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
/** @brief specialization of a DDLPackageProcessor /** @brief specialization of a DDLPackageProcessor
* for interacting with the Write Engine * for interacting with the Write Engine
* to process create table ddl statements. * to process create table ddl statements.
*/ */
class CreateTableProcessor : public DDLPackageProcessor class CreateTableProcessor : public DDLPackageProcessor
{ {
public: public:
CreateTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
CreateTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} {
}
/** @brief process a create table statement /** @brief process a create table statement
* *
* @param createTableStmt the CreateTableStatement * @param createTableStmt the CreateTableStatement
*/ */
EXPORT DDLResult processPackage(ddlpackage::CreateTableStatement& createTableStmt); EXPORT DDLResult processPackage(ddlpackage::CreateTableStatement& createTableStmt);
protected: protected:
void rollBackCreateTable(const std::string& error, BRM::TxnID txnID, int sessionId, ddlpackage::TableDef& tableDef, DDLResult& result); void rollBackCreateTable(const std::string& error, BRM::TxnID txnID, int sessionId,
ddlpackage::TableDef& tableDef, DDLResult& result);
private:
private:
}; };
} // namespace ddlpackageprocessor } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT

View File

@ -51,24 +51,22 @@ using namespace messageqcpp;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
bool DDLIndexPopulator::populateIndex(DDLPackageProcessor::DDLResult& result) bool DDLIndexPopulator::populateIndex(DDLPackageProcessor::DDLResult& result)
{ {
if (makeIndexStructs() ) if (makeIndexStructs())
insertIndex(); insertIndex();
result = fResult; result = fResult;
return NO_ERROR != fResult.result; return NO_ERROR != fResult.result;
} }
bool DDLIndexPopulator::makeIndexStructs()
bool DDLIndexPopulator::makeIndexStructs( )
{ {
CalpontSelectExecutionPlan csep; CalpontSelectExecutionPlan csep;
makeCsep(csep); makeCsep(csep);
ResourceManager* rm; ResourceManager* rm;
if (! fEC) if (!fEC)
{ {
fEC = DistributedEngineComm::instance(rm); fEC = DistributedEngineComm::instance(rm);
fEC->Open(); fEC->Open();
@ -76,7 +74,7 @@ bool DDLIndexPopulator::makeIndexStructs( )
SJLP jbl = joblist::JobListFactory::makeJobList(&csep, rm); SJLP jbl = joblist::JobListFactory::makeJobList(&csep, rm);
boost::shared_ptr<CalpontSystemCatalog> csc = CalpontSystemCatalog::makeCalpontSystemCatalog( fSessionID ); boost::shared_ptr<CalpontSystemCatalog> csc = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID);
csc->identity(CalpontSystemCatalog::EC); csc->identity(CalpontSystemCatalog::EC);
jbl->putEngineComm(fEC); jbl->putEngineComm(fEC);
@ -90,7 +88,7 @@ bool DDLIndexPopulator::makeIndexStructs( )
tableName.schema = fTable.fSchema; tableName.schema = fTable.fSchema;
tableName.table = fTable.fName; tableName.table = fTable.fName;
CalpontSystemCatalog::OID tableOid = (csc->tableRID ( tableName )).objnum; CalpontSystemCatalog::OID tableOid = (csc->tableRID(tableName)).objnum;
CalpontSystemCatalog::NJLSysDataList sysDataList; CalpontSystemCatalog::NJLSysDataList sysDataList;
for (;;) for (;;)
@ -108,7 +106,7 @@ bool DDLIndexPopulator::makeIndexStructs( )
break; break;
} }
//size_t cnt = fColNames.size(); // size_t cnt = fColNames.size();
size_t i = 0; size_t i = 0;
vector<ColumnResult*>::const_iterator it; vector<ColumnResult*>::const_iterator it;
vector<int>::const_iterator oid_iter; vector<int>::const_iterator oid_iter;
@ -118,9 +116,9 @@ bool DDLIndexPopulator::makeIndexStructs( )
if (isUnique()) if (isUnique())
fUniqueColResultList.push_back(*it); fUniqueColResultList.push_back(*it);
for ( oid_iter = fOidList.begin(); oid_iter != fOidList.end(); oid_iter++ ) for (oid_iter = fOidList.begin(); oid_iter != fOidList.end(); oid_iter++)
{ {
if ( (*it)->ColumnOID() == *oid_iter ) if ((*it)->ColumnOID() == *oid_iter)
{ {
CalpontSystemCatalog::ColType coltype = makeIdxStruct(*it, fColNames.size(), csc); CalpontSystemCatalog::ColType coltype = makeIdxStruct(*it, fColNames.size(), csc);
addColumnData(*it, coltype, i); addColumnData(*it, coltype, i);
@ -130,15 +128,11 @@ bool DDLIndexPopulator::makeIndexStructs( )
i++; i++;
} }
return (fIdxValueList.size() && NO_ERROR == fResult.result ); return (fIdxValueList.size() && NO_ERROR == fResult.result);
} }
void DDLIndexPopulator::makeCsep(CalpontSelectExecutionPlan& csep) void DDLIndexPopulator::makeCsep(CalpontSelectExecutionPlan& csep)
{ {
csep.sessionID(fSessionID); csep.sessionID(fSessionID);
csep.txnID(fTxnID); csep.txnID(fTxnID);
@ -150,7 +144,7 @@ void DDLIndexPopulator::makeCsep(CalpontSelectExecutionPlan& csep)
CalpontSystemCatalog::OID oid; CalpontSystemCatalog::OID oid;
tableColName.schema = fTable.fSchema; tableColName.schema = fTable.fSchema;
tableColName.table = fTable.fName; tableColName.table = fTable.fName;
boost::shared_ptr<CalpontSystemCatalog> csc = CalpontSystemCatalog::makeCalpontSystemCatalog( fSessionID ); boost::shared_ptr<CalpontSystemCatalog> csc = CalpontSystemCatalog::makeCalpontSystemCatalog(fSessionID);
string tableName(fTable.fSchema + "." + fTable.fName + "."); string tableName(fTable.fSchema + "." + fTable.fName + ".");
ColumnNameList::const_iterator cend = fColNames.end(); ColumnNameList::const_iterator cend = fColNames.end();
@ -158,20 +152,20 @@ void DDLIndexPopulator::makeCsep(CalpontSelectExecutionPlan& csep)
for (ColumnNameList::const_iterator cname = fColNames.begin(); cname != cend; ++cname) for (ColumnNameList::const_iterator cname = fColNames.begin(); cname != cend; ++cname)
{ {
string fullColName(tableName + *cname); string fullColName(tableName + *cname);
SRCP srcp(new SimpleColumn (fullColName, fSessionID)); SRCP srcp(new SimpleColumn(fullColName, fSessionID));
colList.push_back(srcp); colList.push_back(srcp);
tableColName.column = *cname; tableColName.column = *cname;
oid = csc->lookupOID( tableColName ); oid = csc->lookupOID(tableColName);
fOidList.push_back( oid ); fOidList.push_back(oid);
colMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(fullColName, srcp)); colMap.insert(CalpontSelectExecutionPlan::ColumnMap::value_type(fullColName, srcp));
} }
csep.columnMap (colMap); csep.columnMap(colMap);
csep.returnedCols (colList); csep.returnedCols(colList);
} }
CalpontSystemCatalog::ColType DDLIndexPopulator::makeIdxStruct(const ColumnResult* cr, size_t cols,
CalpontSystemCatalog::ColType DDLIndexPopulator::makeIdxStruct(const ColumnResult* cr, size_t cols, boost::shared_ptr<CalpontSystemCatalog> csc ) boost::shared_ptr<CalpontSystemCatalog> csc)
{ {
IdxStruct idx; IdxStruct idx;
idx.treeOid = fIdxOID.treeOID; idx.treeOid = fIdxOID.treeOID;
@ -180,15 +174,17 @@ CalpontSystemCatalog::ColType DDLIndexPopulator::makeIdxStruct(const ColumnResul
CalpontSystemCatalog::ColType coltype = csc->colType(cr->ColumnOID()); CalpontSystemCatalog::ColType coltype = csc->colType(cr->ColumnOID());
idx.idxDataType = static_cast<CalpontSystemCatalog::ColDataType>(coltype.colDataType); idx.idxDataType = static_cast<CalpontSystemCatalog::ColDataType>(coltype.colDataType);
if (isDictionaryType(coltype) ) if (isDictionaryType(coltype))
{ {
idx.idxWidth = fTOKENSIZE; idx.idxWidth = fTOKENSIZE;
idx.idxType = WR_CHAR; idx.idxType = WR_CHAR;
}//@bug 410: index sizes are either 1, 4 or 8 } //@bug 410: index sizes are either 1, 4 or 8
else if (exeplan::isCharType(coltype)) else if (exeplan::isCharType(coltype))
{ {
if (1 == coltype.colWidth) idx.idxWidth = 1; if (1 == coltype.colWidth)
else idx.idxWidth = (coltype.colWidth > 4) ? 8 : 4; idx.idxWidth = 1;
else
idx.idxWidth = (coltype.colWidth > 4) ? 8 : 4;
idx.idxType = WR_CHAR; idx.idxType = WR_CHAR;
} }
@ -199,22 +195,22 @@ CalpontSystemCatalog::ColType DDLIndexPopulator::makeIdxStruct(const ColumnResul
return coltype; return coltype;
} }
void DDLIndexPopulator::addColumnData(const execplan::ColumnResult* cr, const CalpontSystemCatalog::ColType colType, int added) void DDLIndexPopulator::addColumnData(const execplan::ColumnResult* cr,
const CalpontSystemCatalog::ColType colType, int added)
{ {
WriteEngine::IdxTupleList tupleList; WriteEngine::IdxTupleList tupleList;
WriteEngine::IdxTuple tuple; WriteEngine::IdxTuple tuple;
for (int i = 0; i < cr->dataCount(); ++i) for (int i = 0; i < cr->dataCount(); ++i)
{ {
WriteEngine::IdxTuple tuple;
convertColData(cr, i, colType, tuple);
WriteEngine::IdxTuple tuple ; if (checkConstraints(tuple, colType, i, added))
convertColData( cr, i, colType, tuple);
if (checkConstraints( tuple, colType, i, added))
{ {
tupleList.push_back(tuple); tupleList.push_back(tuple);
if (! added ) if (!added)
fRidList.push_back(cr->GetRid(i)); fRidList.push_back(cr->GetRid(i));
} }
else else
@ -225,9 +221,9 @@ void DDLIndexPopulator::addColumnData(const execplan::ColumnResult* cr, const Ca
fIdxValueList.push_back(tupleList); fIdxValueList.push_back(tupleList);
} }
void DDLIndexPopulator::convertColData(const execplan::ColumnResult* cr, int idx,
const CalpontSystemCatalog::ColType& colType,
void DDLIndexPopulator::convertColData(const execplan::ColumnResult* cr, int idx, const CalpontSystemCatalog::ColType& colType, WriteEngine::IdxTuple& tuple) WriteEngine::IdxTuple& tuple)
{ {
if (isDictionaryType(colType)) if (isDictionaryType(colType))
{ {
@ -235,10 +231,11 @@ void DDLIndexPopulator::convertColData(const execplan::ColumnResult* cr, int idx
/* tuple.data = tokenizeData ( cr->GetRid(idx) );*/ /* tuple.data = tokenizeData ( cr->GetRid(idx) );*/
tuple.data = convertTokenData(cr->GetStringData(idx)); tuple.data = convertTokenData(cr->GetStringData(idx));
} }
else tuple.data = convertData( colType, cr, idx); else
tuple.data = convertData(colType, cr, idx);
} }
boost::any DDLIndexPopulator::convertTokenData( const std::string& data ) boost::any DDLIndexPopulator::convertTokenData(const std::string& data)
{ {
string strData((size_t)fTOKENSIZE < data.length() ? data.substr(0, fTOKENSIZE) : data); string strData((size_t)fTOKENSIZE < data.length() ? data.substr(0, fTOKENSIZE) : data);
return strData; return strData;
@ -269,7 +266,7 @@ bool DDLIndexPopulator::openColumnFile(WriteEngine::OID oid)
#endif #endif
// Workaround to get original column token and not "retokenize" the string value // Workaround to get original column token and not "retokenize" the string value
boost::any DDLIndexPopulator::tokenizeData( WriteEngine::RID rid ) boost::any DDLIndexPopulator::tokenizeData(WriteEngine::RID rid)
{ {
int64_t byteOffset = rid * fTOKENSIZE; int64_t byteOffset = rid * fTOKENSIZE;
ByteStream::byte inbuf[fTOKENSIZE]; ByteStream::byte inbuf[fTOKENSIZE];
@ -281,12 +278,12 @@ boost::any DDLIndexPopulator::tokenizeData( WriteEngine::RID rid )
return token; return token;
} }
boost::any DDLIndexPopulator::tokenizeData(const execplan::CalpontSystemCatalog::ColType& colType,
boost::any DDLIndexPopulator::tokenizeData( const execplan::CalpontSystemCatalog::ColType& colType, const std::string& data ) const std::string& data)
{ {
WriteEngine::DctnryTuple dictTuple; WriteEngine::DctnryTuple dictTuple;
if ( data.length() > (unsigned int)colType.colWidth ) if (data.length() > (unsigned int)colType.colWidth)
{ {
logError("Insert value is too large for column"); logError("Insert value is too large for column");
} }
@ -300,7 +297,7 @@ boost::any DDLIndexPopulator::tokenizeData( const execplan::CalpontSystemCatalog
dictTuple.sigSize = data.length(); dictTuple.sigSize = data.length();
int error = NO_ERROR; int error = NO_ERROR;
if ( NO_ERROR != (error = fWriteEngine->tokenize( fTxnID, dictStruct, dictTuple)) ) if (NO_ERROR != (error = fWriteEngine->tokenize(fTxnID, dictStruct, dictTuple)))
{ {
logError("Tokenization failed", error); logError("Tokenization failed", error);
} }
@ -309,135 +306,119 @@ boost::any DDLIndexPopulator::tokenizeData( const execplan::CalpontSystemCatalog
return dictTuple.token; return dictTuple.token;
} }
boost::any DDLIndexPopulator::convertData(const CalpontSystemCatalog::ColType& colType,
const execplan::ColumnResult* cr, int idx)
boost::any DDLIndexPopulator::convertData(const CalpontSystemCatalog::ColType& colType, const execplan::ColumnResult* cr, int idx )
{ {
uint64_t data = cr->GetData(idx); uint64_t data = cr->GetData(idx);
switch ( colType.colDataType ) switch (colType.colDataType)
{ {
case CalpontSystemCatalog::BIT: case CalpontSystemCatalog::BIT:
case execplan::CalpontSystemCatalog::TINYINT: case execplan::CalpontSystemCatalog::TINYINT: return *reinterpret_cast<char*>(&data);
return *reinterpret_cast<char*>(&data);
case execplan::CalpontSystemCatalog::SMALLINT: case execplan::CalpontSystemCatalog::SMALLINT: return *reinterpret_cast<short*>(&data);
return *reinterpret_cast<short*>(&data);
case execplan::CalpontSystemCatalog::DATE: // @bug 375 case execplan::CalpontSystemCatalog::DATE: // @bug 375
case execplan::CalpontSystemCatalog::MEDINT: case execplan::CalpontSystemCatalog::MEDINT:
case execplan::CalpontSystemCatalog::INT: case execplan::CalpontSystemCatalog::INT: return *reinterpret_cast<int*>(&data);
return *reinterpret_cast<int*>(&data);
case execplan::CalpontSystemCatalog::DATETIME: // @bug 375 case execplan::CalpontSystemCatalog::DATETIME: // @bug 375
case execplan::CalpontSystemCatalog::TIME: case execplan::CalpontSystemCatalog::TIME:
case execplan::CalpontSystemCatalog::TIMESTAMP: case execplan::CalpontSystemCatalog::TIMESTAMP:
case execplan::CalpontSystemCatalog::BIGINT: case execplan::CalpontSystemCatalog::BIGINT: return *reinterpret_cast<long long*>(&data);
return *reinterpret_cast<long long*>(&data);
case execplan::CalpontSystemCatalog::DECIMAL: case execplan::CalpontSystemCatalog::DECIMAL:
{ {
if (colType.colWidth <= CalpontSystemCatalog::FOUR_BYTE) return *reinterpret_cast<short*>(&data); if (colType.colWidth <= CalpontSystemCatalog::FOUR_BYTE)
return *reinterpret_cast<short*>(&data);
else if (colType.colWidth <= 9) return *reinterpret_cast<int*>(&data); else if (colType.colWidth <= 9)
return *reinterpret_cast<int*>(&data);
else return *reinterpret_cast<long long*>(&data); else
return *reinterpret_cast<long long*>(&data);
} }
case execplan::CalpontSystemCatalog::FLOAT: case execplan::CalpontSystemCatalog::FLOAT: return *reinterpret_cast<float*>(&data);
return *reinterpret_cast<float*>(&data);
case execplan::CalpontSystemCatalog::DOUBLE: case execplan::CalpontSystemCatalog::DOUBLE: return *reinterpret_cast<double*>(&data);
return *reinterpret_cast<double*>(&data);
case execplan::CalpontSystemCatalog::CHAR: case execplan::CalpontSystemCatalog::CHAR:
case execplan::CalpontSystemCatalog::VARCHAR: case execplan::CalpontSystemCatalog::VARCHAR:
{ {
string strData(cr->GetStringData(idx) ); string strData(cr->GetStringData(idx));
return *reinterpret_cast<string*>(&strData); return *reinterpret_cast<string*>(&strData);
} }
default: default: break;
break;
} }
logError("Invalid column type"); logError("Invalid column type");
throw std::runtime_error("Invalid data"); throw std::runtime_error("Invalid data");
return *reinterpret_cast<long long*>(&data); return *reinterpret_cast<long long*>(&data);
} }
void DDLIndexPopulator::insertIndex()
void DDLIndexPopulator::insertIndex( )
{ {
// @bug 359 use bulk load build // @bug 359 use bulk load build
int rc = (1 < fIdxStructList.size()) ? int rc = (1 < fIdxStructList.size()) ? (void)0 : (void)0;
(void)0
: (void)0;
if (rc) if (rc)
logError("Error inserting index values", rc ); logError("Error inserting index values", rc);
} }
bool DDLIndexPopulator::isDictionaryType(const CalpontSystemCatalog::ColType& colType) bool DDLIndexPopulator::isDictionaryType(const CalpontSystemCatalog::ColType& colType)
{ {
return ( (CalpontSystemCatalog::CHAR == colType.colDataType && 8 < colType.colWidth ) return ((CalpontSystemCatalog::CHAR == colType.colDataType && 8 < colType.colWidth) ||
|| (CalpontSystemCatalog::VARCHAR == colType.colDataType && 7 < colType.colWidth ) (CalpontSystemCatalog::VARCHAR == colType.colDataType && 7 < colType.colWidth) ||
|| (CalpontSystemCatalog::DECIMAL == colType.colDataType && 18 < colType.precision )); (CalpontSystemCatalog::DECIMAL == colType.colDataType && 18 < colType.precision));
} }
bool DDLIndexPopulator::checkConstraints( const IdxTuple& data, const CalpontSystemCatalog::ColType& ctype, int i, int column) bool DDLIndexPopulator::checkConstraints(const IdxTuple& data, const CalpontSystemCatalog::ColType& ctype,
int i, int column)
{ {
switch (fConstraint)
switch ( fConstraint )
{ {
case DDL_INVALID_CONSTRAINT: case DDL_INVALID_CONSTRAINT: return true;
return true;
case DDL_UNIQUE: case DDL_UNIQUE:
case DDL_PRIMARY_KEY: case DDL_PRIMARY_KEY:
if ((size_t)column + 1 < fColNames.size() ) if ((size_t)column + 1 < fColNames.size())
return true; return true;
return checkUnique( i, ctype ); return checkUnique(i, ctype);
case DDL_NOT_NULL: case DDL_NOT_NULL: return checkNotNull(data, ctype);
return checkNotNull( data, ctype );
case DDL_CHECK: case DDL_CHECK: return checkCheck(data, ctype);
return checkCheck( data, ctype );
default: default: return true; //?
return true; //?
} }
} }
// Check if the row of data at idx is already in fUniqueColResultList // Check if the row of data at idx is already in fUniqueColResultList
bool DDLIndexPopulator::checkUnique( int idx, const CalpontSystemCatalog::ColType& colType ) bool DDLIndexPopulator::checkUnique(int idx, const CalpontSystemCatalog::ColType& colType)
{ {
if (0 == idx) if (0 == idx)
return true; return true;
//Get row of data as each column result data at idx // Get row of data as each column result data at idx
size_t indexSize = fColNames.size(); size_t indexSize = fColNames.size();
vector <uint64_t> rowIntData(indexSize); vector<uint64_t> rowIntData(indexSize);
vector <string> rowStrData(indexSize); vector<string> rowStrData(indexSize);
for (size_t i = 0; i < indexSize; ++i) for (size_t i = 0; i < indexSize; ++i)
{ {
//if ( isStringType(fUniqueColResultList[i]->columnType()) ) // if ( isStringType(fUniqueColResultList[i]->columnType()) )
if ( isStringType(colType.colDataType) ) if (isStringType(colType.colDataType))
rowStrData[i] = fUniqueColResultList[i]->GetStringData(idx); rowStrData[i] = fUniqueColResultList[i]->GetStringData(idx);
else else
rowIntData[i] = fUniqueColResultList[i]->GetData(idx); rowIntData[i] = fUniqueColResultList[i]->GetData(idx);
} }
//check if each value in the idx row is equal to each value in a previous row // check if each value in the idx row is equal to each value in a previous row
// i is the row; j is the column. // i is the row; j is the column.
bool unique = true; bool unique = true;
@ -447,7 +428,7 @@ bool DDLIndexPopulator::checkUnique( int idx, const CalpontSystemCatalog::ColTyp
for (size_t j = 0; j < indexSize && equal; ++j) for (size_t j = 0; j < indexSize && equal; ++j)
{ {
if ( isStringType(colType.colDataType) ) if (isStringType(colType.colDataType))
{ {
equal = fUniqueColResultList[j]->GetStringData(i) == rowStrData[j]; equal = fUniqueColResultList[j]->GetStringData(i) == rowStrData[j];
} }
@ -457,30 +438,27 @@ bool DDLIndexPopulator::checkUnique( int idx, const CalpontSystemCatalog::ColTyp
} }
} }
unique = ! equal; unique = !equal;
} }
if (! unique) if (!unique)
{ {
stringstream ss; stringstream ss;
ss << idx; ss << idx;
logError("Unique Constraint violated on row: " + ss.str() ); logError("Unique Constraint violated on row: " + ss.str());
} }
return unique; return unique;
} }
bool DDLIndexPopulator::checkNotNull(const IdxTuple& data, const CalpontSystemCatalog::ColType& colType) bool DDLIndexPopulator::checkNotNull(const IdxTuple& data, const CalpontSystemCatalog::ColType& colType)
{ {
any nullvalue = DDLNullValueForType(colType); any nullvalue = DDLNullValueForType(colType);
bool isNull = false; bool isNull = false;
switch ( colType.colDataType ) switch (colType.colDataType)
{ {
case CalpontSystemCatalog::BIT: case CalpontSystemCatalog::BIT: break;
break;
case execplan::CalpontSystemCatalog::TINYINT: case execplan::CalpontSystemCatalog::TINYINT:
isNull = any_cast<char>(data.data) == any_cast<char>(nullvalue); isNull = any_cast<char>(data.data) == any_cast<char>(nullvalue);
@ -508,7 +486,8 @@ bool DDLIndexPopulator::checkNotNull(const IdxTuple& data, const CalpontSystemCa
else if (colType.colWidth <= 18) else if (colType.colWidth <= 18)
isNull = any_cast<long long>(data.data) == any_cast<long long>(nullvalue); isNull = any_cast<long long>(data.data) == any_cast<long long>(nullvalue);
else else
isNull = compareToken(any_cast<WriteEngine::Token>(data.data), any_cast<WriteEngine::Token>(nullvalue)); isNull =
compareToken(any_cast<WriteEngine::Token>(data.data), any_cast<WriteEngine::Token>(nullvalue));
break; break;
} }
@ -540,10 +519,10 @@ bool DDLIndexPopulator::checkNotNull(const IdxTuple& data, const CalpontSystemCa
else if (colType.colWidth <= execplan::CalpontSystemCatalog::FOUR_BYTE) else if (colType.colWidth <= execplan::CalpontSystemCatalog::FOUR_BYTE)
isNull = any_cast<string>(data.data) == any_cast<string>(nullvalue); isNull = any_cast<string>(data.data) == any_cast<string>(nullvalue);
else else
isNull = compareToken(any_cast<WriteEngine::Token>(data.data), any_cast<WriteEngine::Token>(nullvalue)); isNull =
compareToken(any_cast<WriteEngine::Token>(data.data), any_cast<WriteEngine::Token>(nullvalue));
break; break;
} }
case execplan::CalpontSystemCatalog::VARCHAR: case execplan::CalpontSystemCatalog::VARCHAR:
@ -553,25 +532,23 @@ bool DDLIndexPopulator::checkNotNull(const IdxTuple& data, const CalpontSystemCa
else if (colType.colWidth < execplan::CalpontSystemCatalog::FOUR_BYTE) else if (colType.colWidth < execplan::CalpontSystemCatalog::FOUR_BYTE)
isNull = any_cast<string>(data.data) == any_cast<string>(nullvalue); isNull = any_cast<string>(data.data) == any_cast<string>(nullvalue);
else else
isNull = compareToken(any_cast<WriteEngine::Token>(data.data), any_cast<WriteEngine::Token>(nullvalue)); isNull =
compareToken(any_cast<WriteEngine::Token>(data.data), any_cast<WriteEngine::Token>(nullvalue));
break; break;
} }
default: default: throw std::runtime_error("getNullValueForType: unkown column data type");
throw std::runtime_error("getNullValueForType: unkown column data type");
} }
if (isNull) if (isNull)
logError("Null value not allowed in index"); logError("Null value not allowed in index");
return ! isNull; return !isNull;
} }
void DDLIndexPopulator::logError(const string& msg, int error) void DDLIndexPopulator::logError(const string& msg, int error)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add((string)__FILE__ + ": "); args.add((string)__FILE__ + ": ");
@ -583,17 +560,10 @@ void DDLIndexPopulator::logError(const string& msg, int error)
args.add(error); args.add(error);
} }
message.format( args ); message.format(args);
fResult.result = DDLPackageProcessor::CREATE_ERROR; fResult.result = DDLPackageProcessor::CREATE_ERROR;
fResult.message = message; fResult.message = message;
} }
} // namespace ddlpackageprocessor
} //namespace

View File

@ -40,7 +40,6 @@
#include <boost/any.hpp> #include <boost/any.hpp>
#include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple.hpp>
#include "joblistfactory.h" #include "joblistfactory.h"
namespace joblist namespace joblist
@ -50,43 +49,47 @@ class DistributedEngineComm;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
/** @brief Populate an new Index /** @brief Populate an new Index
* implementation of a DDLPopulator * implementation of a DDLPopulator
*/ */
class DDLIndexPopulator class DDLIndexPopulator
{ {
public:
public:
/** @brief constructor /** @brief constructor
* *
*/ */
DDLIndexPopulator(WriteEngine::WriteEngineWrapper* writeEngine, DDLIndexPopulator(WriteEngine::WriteEngineWrapper* writeEngine, execplan::SessionManager* sessionManager,
execplan::SessionManager* sessionManager, uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
uint32_t sessionID, DDLPackageProcessor::DDLResult& result, const DDLPackageProcessor::IndexOID& idxOID,
execplan::CalpontSystemCatalog::SCN txnID, const ddlpackage::ColumnNameList& colNames, const ddlpackage::QualifiedName& table,
DDLPackageProcessor::DDLResult& result, const ddlpackage::DDL_CONSTRAINTS constraint, const DDLPackageProcessor::DebugLevel debug)
const DDLPackageProcessor::IndexOID& idxOID, : fWriteEngine(writeEngine)
const ddlpackage::ColumnNameList& colNames, , fSessionManager(sessionManager)
const ddlpackage::QualifiedName& table, , fSessionID(sessionID)
const ddlpackage::DDL_CONSTRAINTS constraint, , fTxnID(txnID)
const DDLPackageProcessor::DebugLevel debug): , fResult(result)
fWriteEngine(writeEngine), fSessionManager(sessionManager), , fIdxOID(idxOID)
fSessionID(sessionID), fTxnID(txnID), fResult(result), , fColNames(colNames)
fIdxOID(idxOID), fColNames(colNames), fTable(table), fDebugLevel(debug), , fTable(table)
fEC(0), fRidList(), fIdxStructList(), fIdxValueList(), , fDebugLevel(debug)
, fEC(0)
, fRidList()
, fIdxStructList()
, fIdxValueList()
,
/* fTOKENSIZE(sizeof(WriteEngine::Token) ) {}*/ /* fTOKENSIZE(sizeof(WriteEngine::Token) ) {}*/
fConstraint(constraint), fUniqueColResultList() {} fConstraint(constraint)
, fUniqueColResultList()
{
}
/** @brief destructor /** @brief destructor
*/ */
virtual ~DDLIndexPopulator() { }; virtual ~DDLIndexPopulator(){};
/** @brief Is it required to debug /** @brief Is it required to debug
*/ */
const bool isDebug( const DDLPackageProcessor::DebugLevel level ) const const bool isDebug(const DDLPackageProcessor::DebugLevel level) const
{ {
return level <= fDebugLevel; return level <= fDebugLevel;
} }
@ -98,7 +101,6 @@ public:
return fDebugLevel; return fDebugLevel;
} }
/** @brief set distributedEngineComm pointer ( for /** @brief set distributedEngineComm pointer ( for
* loading index). * loading index).
*/ */
@ -116,7 +118,6 @@ public:
return fResult; return fResult;
} }
/** @brief add data to the index from the statement /** @brief add data to the index from the statement
* *
* populate the newly made index with data in the index columns. * populate the newly made index with data in the index columns.
@ -131,8 +132,7 @@ public:
void setConstraint(ddlpackage::DDL_CONSTRAINTS constraint); void setConstraint(ddlpackage::DDL_CONSTRAINTS constraint);
protected: protected:
/** @brief make the structures to update the index /** @brief make the structures to update the index
* *
* builds and executes a query to retrieve all the data from the index columns * builds and executes a query to retrieve all the data from the index columns
@ -146,7 +146,8 @@ protected:
* Fills in the values from the column result and calpont system catalog for * Fills in the values from the column result and calpont system catalog for
* the WriteEngine::IdxStruct * the WriteEngine::IdxStruct
*/ */
execplan::CalpontSystemCatalog::ColType makeIdxStruct(const execplan::ColumnResult* cr, size_t cols, boost::shared_ptr<execplan::CalpontSystemCatalog> csc ); execplan::CalpontSystemCatalog::ColType makeIdxStruct(
const execplan::ColumnResult* cr, size_t cols, boost::shared_ptr<execplan::CalpontSystemCatalog> csc);
/** @brief add the column result data to the value list /** @brief add the column result data to the value list
* *
@ -154,7 +155,8 @@ protected:
* Adds the rid to the rid list if it is the first column (not been added) * Adds the rid to the rid list if it is the first column (not been added)
* Adds the completed tuple list to the fValueList * Adds the completed tuple list to the fValueList
*/ */
void addColumnData(const execplan::ColumnResult* cr, const execplan::CalpontSystemCatalog::ColType ctype, int added); void addColumnData(const execplan::ColumnResult* cr, const execplan::CalpontSystemCatalog::ColType ctype,
int added);
/** @brief insert data into index. /** @brief insert data into index.
* *
@ -163,10 +165,9 @@ protected:
*/ */
void insertIndex(); void insertIndex();
private:
private: DDLIndexPopulator(const DDLIndexPopulator&);
DDLIndexPopulator(const DDLIndexPopulator& ); void operator=(const DDLIndexPopulator&);
void operator=(const DDLIndexPopulator& );
/** @brief makes Calpont Select Execution Plan /** @brief makes Calpont Select Execution Plan
* *
* builds csep to select data from all columns from fColNames * builds csep to select data from all columns from fColNames
@ -181,23 +182,23 @@ private:
bool isStringType(int type) const bool isStringType(int type) const
{ {
return (type == execplan::CalpontSystemCatalog::CHAR return (type == execplan::CalpontSystemCatalog::CHAR || type == execplan::CalpontSystemCatalog::VARCHAR ||
|| type == execplan::CalpontSystemCatalog::VARCHAR type == execplan::CalpontSystemCatalog::FLOAT || type == execplan::CalpontSystemCatalog::DOUBLE ||
|| type == execplan::CalpontSystemCatalog::FLOAT type == execplan::CalpontSystemCatalog::UFLOAT ||
|| type == execplan::CalpontSystemCatalog::DOUBLE type == execplan::CalpontSystemCatalog::UDOUBLE);
|| type == execplan::CalpontSystemCatalog::UFLOAT
|| type == execplan::CalpontSystemCatalog::UDOUBLE );
} }
/** @brief converts column result data /** @brief converts column result data
* *
* Converts or tokenizes data, depending on column type * Converts or tokenizes data, depending on column type
*/ */
void convertColData(const execplan::ColumnResult* cr, int idx, const execplan::CalpontSystemCatalog::ColType& cType, WriteEngine::IdxTuple& tuple); void convertColData(const execplan::ColumnResult* cr, int idx,
const execplan::CalpontSystemCatalog::ColType& cType, WriteEngine::IdxTuple& tuple);
/** @brief converts non token data to its original type /** @brief converts non token data to its original type
*/ */
boost::any convertData(const execplan::CalpontSystemCatalog::ColType& colType, const execplan::ColumnResult* cr, int idx ); boost::any convertData(const execplan::CalpontSystemCatalog::ColType& colType,
const execplan::ColumnResult* cr, int idx);
/** @brief returns token for string data /** @brief returns token for string data
* *
@ -206,9 +207,9 @@ private:
* able to return an existing token for a string. The rid method reads * able to return an existing token for a string. The rid method reads
* the column file directly. * the column file directly.
*/ */
boost::any tokenizeData( const execplan::CalpontSystemCatalog::ColType& colType, const std::string& data ); boost::any tokenizeData(const execplan::CalpontSystemCatalog::ColType& colType, const std::string& data);
boost::any tokenizeData( WriteEngine::RID rid ); boost::any tokenizeData(WriteEngine::RID rid);
/** @brief convert token data /** @brief convert token data
* *
@ -216,7 +217,7 @@ private:
* of a token. * of a token.
*/ */
boost::any convertTokenData( const std::string& data ); boost::any convertTokenData(const std::string& data);
/** @brief opens the column file for the oid /** @brief opens the column file for the oid
* *
@ -224,14 +225,15 @@ private:
* tokenizeData method. The fColumnFile and this method are no longer * tokenizeData method. The fColumnFile and this method are no longer
* needed when the WriteEngine::tokenize method can be used. * needed when the WriteEngine::tokenize method can be used.
*/ */
//bool openColumnFile(WriteEngine::OID oid); // bool openColumnFile(WriteEngine::OID oid);
/** @brief returns if data violated its constraint /** @brief returns if data violated its constraint
* *
* checks data according to contraint in coltype and sets result to error * checks data according to contraint in coltype and sets result to error
* if constraint violated. Returns if no error. * if constraint violated. Returns if no error.
*/ */
bool checkConstraints(const WriteEngine::IdxTuple& data, const execplan::CalpontSystemCatalog::ColType& ctype, int i, int column); bool checkConstraints(const WriteEngine::IdxTuple& data,
const execplan::CalpontSystemCatalog::ColType& ctype, int i, int column);
/** @brief returns if data not null /** @brief returns if data not null
* *
@ -243,9 +245,10 @@ private:
* *
* Returns false if data row is found more than once in columns and sets result to error * Returns false if data row is found more than once in columns and sets result to error
*/ */
bool checkUnique(int i, const execplan::CalpontSystemCatalog::ColType& colType ); bool checkUnique(int i, const execplan::CalpontSystemCatalog::ColType& colType);
bool checkCheck( const WriteEngine::IdxTuple& data, const execplan::CalpontSystemCatalog::ColType& ctype) const bool checkCheck(const WriteEngine::IdxTuple& data,
const execplan::CalpontSystemCatalog::ColType& ctype) const
{ {
return true; return true;
} }
@ -288,15 +291,16 @@ private:
struct DDLNullValueForType : DDLPackageProcessor struct DDLNullValueForType : DDLPackageProcessor
{ {
DDLNullValueForType(const execplan::CalpontSystemCatalog::ColType& ctype) DDLNullValueForType(const execplan::CalpontSystemCatalog::ColType& ctype)
: DDLPackageProcessor(), fType(ctype) {} : DDLPackageProcessor(), fType(ctype)
{
}
boost::any operator()(execplan::CalpontSystemCatalog::ColType& ctype) boost::any operator()(execplan::CalpontSystemCatalog::ColType& ctype)
{ {
return ctype.getNullValueForType(); return ctype.getNullValueForType();
} }
const execplan::CalpontSystemCatalog::ColType& fType; const execplan::CalpontSystemCatalog::ColType& fType;
}; };
}; };
} } // namespace ddlpackageprocessor
#endif //DDLPINDEXPOPULATOR_H #endif // DDLPINDEXPOPULATOR_H

View File

@ -67,11 +67,11 @@ const SOP opne(new Operator("<>"));
const SOP opor(new Operator("or")); const SOP opor(new Operator("or"));
const SOP opand(new Operator("and")); const SOP opand(new Operator("and"));
const SOP opis(new Operator("is")); const SOP opis(new Operator("is"));
} } // namespace
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
using boost::lexical_cast;
using boost::any_cast; using boost::any_cast;
using boost::lexical_cast;
using namespace std; using namespace std;
using namespace execplan; using namespace execplan;
@ -83,14 +83,13 @@ boost::mutex DDLPackageProcessor::dbrmMutex;
DDLPackageProcessor::~DDLPackageProcessor() DDLPackageProcessor::~DDLPackageProcessor()
{ {
//cout << "in DDLPackageProcessor destructor " << this << endl; // cout << "in DDLPackageProcessor destructor " << this << endl;
delete fWEClient; delete fWEClient;
} }
void DDLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string schema, std::string table, void DDLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string schema, std::string table,
ColumnList& colList) ColumnList& colList)
{ {
CalpontSystemCatalog::TableName tableName; CalpontSystemCatalog::TableName tableName;
tableName.schema = schema; tableName.schema = schema;
tableName.table = table; tableName.table = table;
@ -98,7 +97,8 @@ void DDLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string sc
try try
{ {
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(sessionID);
systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->identity(CalpontSystemCatalog::EC);
const CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(tableName); const CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(tableName);
@ -118,20 +118,18 @@ void DDLPackageProcessor::getColumnsForTable(uint32_t sessionID, std::string sc
++rid_iterator; ++rid_iterator;
} }
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
err = "DDLPackageProcessor::getColumnsForTable: while reading columns for table " + schema + '.' + table +
err = "DDLPackageProcessor::getColumnsForTable: while reading columns for table " + schema + '.' + table + ": " + ex.what(); ": " + ex.what();
throw std::runtime_error(err); throw std::runtime_error(err);
} }
catch (...) catch (...)
{ {
err = "DDLPackageProcessor::getColumnsForTable: caught unkown exception!" ; err = "DDLPackageProcessor::getColumnsForTable: caught unkown exception!";
throw std::runtime_error(err); throw std::runtime_error(err);
} }
} }
execplan::CalpontSystemCatalog::ColDataType DDLPackageProcessor::convertDataType(int dataType) execplan::CalpontSystemCatalog::ColDataType DDLPackageProcessor::convertDataType(int dataType)
@ -140,129 +138,72 @@ execplan::CalpontSystemCatalog::ColDataType DDLPackageProcessor::convertDataType
switch (dataType) switch (dataType)
{ {
case ddlpackage::DDL_CHAR: case ddlpackage::DDL_CHAR: colDataType = CalpontSystemCatalog::CHAR; break;
colDataType = CalpontSystemCatalog::CHAR;
break;
case ddlpackage::DDL_VARCHAR: case ddlpackage::DDL_VARCHAR: colDataType = CalpontSystemCatalog::VARCHAR; break;
colDataType = CalpontSystemCatalog::VARCHAR;
break;
case ddlpackage::DDL_VARBINARY: case ddlpackage::DDL_VARBINARY: colDataType = CalpontSystemCatalog::VARBINARY; break;
colDataType = CalpontSystemCatalog::VARBINARY;
break;
case ddlpackage::DDL_BIT: case ddlpackage::DDL_BIT: colDataType = CalpontSystemCatalog::BIT; break;
colDataType = CalpontSystemCatalog::BIT;
break;
case ddlpackage::DDL_REAL: case ddlpackage::DDL_REAL:
case ddlpackage::DDL_DECIMAL: case ddlpackage::DDL_DECIMAL:
case ddlpackage::DDL_NUMERIC: case ddlpackage::DDL_NUMERIC:
case ddlpackage::DDL_NUMBER: case ddlpackage::DDL_NUMBER: colDataType = CalpontSystemCatalog::DECIMAL; break;
colDataType = CalpontSystemCatalog::DECIMAL;
break;
case ddlpackage::DDL_FLOAT: case ddlpackage::DDL_FLOAT: colDataType = CalpontSystemCatalog::FLOAT; break;
colDataType = CalpontSystemCatalog::FLOAT;
break;
case ddlpackage::DDL_DOUBLE: case ddlpackage::DDL_DOUBLE: colDataType = CalpontSystemCatalog::DOUBLE; break;
colDataType = CalpontSystemCatalog::DOUBLE;
break;
case ddlpackage::DDL_INT: case ddlpackage::DDL_INT:
case ddlpackage::DDL_INTEGER: case ddlpackage::DDL_INTEGER: colDataType = CalpontSystemCatalog::INT; break;
colDataType = CalpontSystemCatalog::INT;
break;
case ddlpackage::DDL_BIGINT: case ddlpackage::DDL_BIGINT: colDataType = CalpontSystemCatalog::BIGINT; break;
colDataType = CalpontSystemCatalog::BIGINT;
break;
case ddlpackage::DDL_MEDINT: case ddlpackage::DDL_MEDINT: colDataType = CalpontSystemCatalog::MEDINT; break;
colDataType = CalpontSystemCatalog::MEDINT;
break;
case ddlpackage::DDL_SMALLINT: case ddlpackage::DDL_SMALLINT: colDataType = CalpontSystemCatalog::SMALLINT; break;
colDataType = CalpontSystemCatalog::SMALLINT;
break;
case ddlpackage::DDL_TINYINT: case ddlpackage::DDL_TINYINT: colDataType = CalpontSystemCatalog::TINYINT; break;
colDataType = CalpontSystemCatalog::TINYINT;
break;
case ddlpackage::DDL_UNSIGNED_DECIMAL: case ddlpackage::DDL_UNSIGNED_DECIMAL:
case ddlpackage::DDL_UNSIGNED_NUMERIC: case ddlpackage::DDL_UNSIGNED_NUMERIC: colDataType = CalpontSystemCatalog::UDECIMAL; break;
colDataType = CalpontSystemCatalog::UDECIMAL;
break;
case ddlpackage::DDL_UNSIGNED_FLOAT: case ddlpackage::DDL_UNSIGNED_FLOAT: colDataType = CalpontSystemCatalog::UFLOAT; break;
colDataType = CalpontSystemCatalog::UFLOAT;
break;
case ddlpackage::DDL_UNSIGNED_DOUBLE: case ddlpackage::DDL_UNSIGNED_DOUBLE: colDataType = CalpontSystemCatalog::UDOUBLE; break;
colDataType = CalpontSystemCatalog::UDOUBLE;
break;
case ddlpackage::DDL_UNSIGNED_INT: case ddlpackage::DDL_UNSIGNED_INT: colDataType = CalpontSystemCatalog::UINT; break;
colDataType = CalpontSystemCatalog::UINT;
break;
case ddlpackage::DDL_UNSIGNED_BIGINT: case ddlpackage::DDL_UNSIGNED_BIGINT: colDataType = CalpontSystemCatalog::UBIGINT; break;
colDataType = CalpontSystemCatalog::UBIGINT;
break;
case ddlpackage::DDL_UNSIGNED_MEDINT: case ddlpackage::DDL_UNSIGNED_MEDINT: colDataType = CalpontSystemCatalog::UMEDINT; break;
colDataType = CalpontSystemCatalog::UMEDINT;
break;
case ddlpackage::DDL_UNSIGNED_SMALLINT: case ddlpackage::DDL_UNSIGNED_SMALLINT: colDataType = CalpontSystemCatalog::USMALLINT; break;
colDataType = CalpontSystemCatalog::USMALLINT;
break;
case ddlpackage::DDL_UNSIGNED_TINYINT: case ddlpackage::DDL_UNSIGNED_TINYINT: colDataType = CalpontSystemCatalog::UTINYINT; break;
colDataType = CalpontSystemCatalog::UTINYINT;
break;
case ddlpackage::DDL_DATE: case ddlpackage::DDL_DATE: colDataType = CalpontSystemCatalog::DATE; break;
colDataType = CalpontSystemCatalog::DATE;
break;
case ddlpackage::DDL_DATETIME: case ddlpackage::DDL_DATETIME: colDataType = CalpontSystemCatalog::DATETIME; break;
colDataType = CalpontSystemCatalog::DATETIME;
break;
case ddlpackage::DDL_TIME: case ddlpackage::DDL_TIME: colDataType = CalpontSystemCatalog::TIME; break;
colDataType = CalpontSystemCatalog::TIME;
break;
case ddlpackage::DDL_TIMESTAMP: case ddlpackage::DDL_TIMESTAMP: colDataType = CalpontSystemCatalog::TIMESTAMP; break;
colDataType = CalpontSystemCatalog::TIMESTAMP;
break;
case ddlpackage::DDL_CLOB: case ddlpackage::DDL_CLOB: colDataType = CalpontSystemCatalog::CLOB; break;
colDataType = CalpontSystemCatalog::CLOB;
break;
case ddlpackage::DDL_BLOB: case ddlpackage::DDL_BLOB: colDataType = CalpontSystemCatalog::BLOB; break;
colDataType = CalpontSystemCatalog::BLOB;
break;
case ddlpackage::DDL_TEXT: case ddlpackage::DDL_TEXT: colDataType = CalpontSystemCatalog::TEXT; break;
colDataType = CalpontSystemCatalog::TEXT;
break;
default:
throw runtime_error("Unsupported datatype!");
default: throw runtime_error("Unsupported datatype!");
} }
return colDataType; return colDataType;
} }
std::string DDLPackageProcessor::buildTableConstraintName(const int oid, std::string DDLPackageProcessor::buildTableConstraintName(const int oid, ddlpackage::DDL_CONSTRAINTS type)
ddlpackage::DDL_CONSTRAINTS type)
{ {
std::stringstream oid_number; std::stringstream oid_number;
oid_number << oid; oid_number << oid;
@ -272,32 +213,22 @@ std::string DDLPackageProcessor::buildTableConstraintName(const int oid,
switch (type) switch (type)
{ {
case ddlpackage::DDL_PRIMARY_KEY: case ddlpackage::DDL_PRIMARY_KEY:
//prefix = "pk_"; // prefix = "pk_";
// @note this name is supplied by the previous create index statement // @note this name is supplied by the previous create index statement
// generated by Oracle. Use Oracle's PK name instead of making up our own // generated by Oracle. Use Oracle's PK name instead of making up our own
indexName = fPKName; indexName = fPKName;
break; break;
case ddlpackage::DDL_FOREIGN_KEY: case ddlpackage::DDL_FOREIGN_KEY:
case ddlpackage::DDL_REFERENCES: case ddlpackage::DDL_REFERENCES: prefix = "fk_"; break;
prefix = "fk_";
break;
case ddlpackage::DDL_UNIQUE: case ddlpackage::DDL_UNIQUE: prefix = "uk_"; break;
prefix = "uk_";
break;
case ddlpackage::DDL_CHECK: case ddlpackage::DDL_CHECK: prefix = "ck_"; break;
prefix = "ck_";
break;
case ddlpackage::DDL_NOT_NULL: case ddlpackage::DDL_NOT_NULL: prefix = "nk_"; break;
prefix = "nk_";
break;
default: default: throw runtime_error("Unsupported constraint type!"); break;
throw runtime_error("Unsupported constraint type!");
break;
} }
if (type != ddlpackage::DDL_PRIMARY_KEY) if (type != ddlpackage::DDL_PRIMARY_KEY)
@ -319,30 +250,18 @@ std::string DDLPackageProcessor::buildColumnConstraintName(const std::string& sc
switch (type) switch (type)
{ {
case ddlpackage::DDL_PRIMARY_KEY: case ddlpackage::DDL_PRIMARY_KEY: prefix = "pk_"; break;
prefix = "pk_";
break;
case ddlpackage::DDL_FOREIGN_KEY: case ddlpackage::DDL_FOREIGN_KEY:
case ddlpackage::DDL_REFERENCES: case ddlpackage::DDL_REFERENCES: prefix = "fk_"; break;
prefix = "fk_";
break;
case ddlpackage::DDL_UNIQUE: case ddlpackage::DDL_UNIQUE: prefix = "uk_"; break;
prefix = "uk_";
break;
case ddlpackage::DDL_CHECK: case ddlpackage::DDL_CHECK: prefix = "ck_"; break;
prefix = "ck_";
break;
case ddlpackage::DDL_NOT_NULL: case ddlpackage::DDL_NOT_NULL: prefix = "nk_"; break;
prefix = "nk_";
break;
default: default: throw runtime_error("Unsupported constraint type!"); break;
throw runtime_error("Unsupported constraint type!");
break;
} }
indexName = prefix + schema + "_" + table + "_" + column; indexName = prefix + schema + "_" + table + "_" + column;
@ -358,36 +277,23 @@ char DDLPackageProcessor::getConstraintCode(ddlpackage::DDL_CONSTRAINTS type)
switch (type) switch (type)
{ {
case ddlpackage::DDL_PRIMARY_KEY: case ddlpackage::DDL_PRIMARY_KEY: constraint_type = 'p'; break;
constraint_type = 'p';
break;
case ddlpackage::DDL_REFERENCES: case ddlpackage::DDL_REFERENCES:
case ddlpackage::DDL_FOREIGN_KEY: case ddlpackage::DDL_FOREIGN_KEY: constraint_type = 'f'; break;
constraint_type = 'f';
break;
case ddlpackage::DDL_UNIQUE: case ddlpackage::DDL_UNIQUE: constraint_type = 'u'; break;
constraint_type = 'u';
break;
case ddlpackage::DDL_CHECK: case ddlpackage::DDL_CHECK: constraint_type = 'c'; break;
constraint_type = 'c';
break;
case ddlpackage::DDL_NOT_NULL: case ddlpackage::DDL_NOT_NULL: constraint_type = 'n'; break;
constraint_type = 'n';
break;
default: default: constraint_type = '0'; break;
constraint_type = '0';
break;
} }
return constraint_type; return constraint_type;
} }
bool DDLPackageProcessor::isIndexConstraint(ddlpackage::DDL_CONSTRAINTS type) bool DDLPackageProcessor::isIndexConstraint(ddlpackage::DDL_CONSTRAINTS type)
{ {
bool indexConstraint = false; bool indexConstraint = false;
@ -397,14 +303,10 @@ bool DDLPackageProcessor::isIndexConstraint(ddlpackage::DDL_CONSTRAINTS type)
case ddlpackage::DDL_PRIMARY_KEY: case ddlpackage::DDL_PRIMARY_KEY:
// @bug fix for #418, #416. Do not insert into sysindex // @bug fix for #418, #416. Do not insert into sysindex
//case ddlpackage::DDL_REFERENCES: // case ddlpackage::DDL_REFERENCES:
case ddlpackage::DDL_UNIQUE: case ddlpackage::DDL_UNIQUE: indexConstraint = true; break;
indexConstraint = true;
break;
default:
break;
default: break;
} }
return indexConstraint; return indexConstraint;
@ -413,7 +315,6 @@ bool DDLPackageProcessor::isIndexConstraint(ddlpackage::DDL_CONSTRAINTS type)
void DDLPackageProcessor::getColumnReferences(ddlpackage::TableConstraintDef& tableConstraint, void DDLPackageProcessor::getColumnReferences(ddlpackage::TableConstraintDef& tableConstraint,
ddlpackage::ColumnNameList& columns) ddlpackage::ColumnNameList& columns)
{ {
switch (tableConstraint.fConstraintType) switch (tableConstraint.fConstraintType)
{ {
case ddlpackage::DDL_PRIMARY_KEY: case ddlpackage::DDL_PRIMARY_KEY:
@ -443,13 +344,12 @@ void DDLPackageProcessor::getColumnReferences(ddlpackage::TableConstraintDef& ta
} }
break; break;
default: default: break;
break;
} }
} }
boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN txnID,
const DDLResult& result,
const execplan::CalpontSystemCatalog::ColType& colType, const execplan::CalpontSystemCatalog::ColType& colType,
const boost::any& data) const boost::any& data)
{ {
@ -459,7 +359,6 @@ boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN
if (result.result == NO_ERROR) if (result.result == NO_ERROR)
{ {
try try
{ {
std::string str; std::string str;
@ -481,17 +380,18 @@ boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN
else else
str = any_cast<std::string>(data); str = any_cast<std::string>(data);
//Tokenize the data value // Tokenize the data value
WriteEngine::DctnryStruct dictStruct; WriteEngine::DctnryStruct dictStruct;
dictStruct.dctnryOid = colType.ddn.dictOID; dictStruct.dctnryOid = colType.ddn.dictOID;
//added for multifiles per oid // added for multifiles per oid
dictStruct.columnOid = colType.columnOID; dictStruct.columnOid = colType.columnOID;
WriteEngine::DctnryTuple dictTuple; WriteEngine::DctnryTuple dictTuple;
dictTuple.sigValue = (unsigned char*)str.c_str(); dictTuple.sigValue = (unsigned char*)str.c_str();
dictTuple.sigSize = str.length(); dictTuple.sigSize = str.length();
int error = NO_ERROR; int error = NO_ERROR;
if (NO_ERROR != (error = fWriteEngine.tokenize(txnID, dictStruct, dictTuple, false))) // @bug 5572 HDFS tmp file if (NO_ERROR !=
(error = fWriteEngine.tokenize(txnID, dictStruct, dictTuple, false))) // @bug 5572 HDFS tmp file
{ {
WErrorCodes ec; WErrorCodes ec;
throw std::runtime_error("WE: Tokenization failed " + ec.errorString(error)); throw std::runtime_error("WE: Tokenization failed " + ec.errorString(error));
@ -500,7 +400,6 @@ boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN
WriteEngine::Token aToken = dictTuple.token; WriteEngine::Token aToken = dictTuple.token;
value = aToken; value = aToken;
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
@ -511,7 +410,6 @@ boost::any DDLPackageProcessor::tokenizeData(execplan::CalpontSystemCatalog::SCN
{ {
err += "Unknown exception caught, tokenizeData failed."; err += "Unknown exception caught, tokenizeData failed.";
throw std::runtime_error(err); throw std::runtime_error(err);
} }
} }
@ -563,9 +461,9 @@ void DDLPackageProcessor::flushPrimprocCache(std::vector<execplan::CalpontSystem
} }
} }
//Need find a more efficient way to do this. // Need find a more efficient way to do this.
err = cacheutils::flushPrimProcBlocks (blockList); err = cacheutils::flushPrimProcBlocks(blockList);
//No need to handle this error as the error comes from timeout, not real error // No need to handle this error as the error comes from timeout, not real error
(void)err; (void)err;
++iter; ++iter;
@ -583,9 +481,8 @@ void DDLPackageProcessor::flushPrimprocCache(std::vector<execplan::CalpontSystem
} }
} }
void DDLPackageProcessor::removeFiles(const uint64_t uniqueId,
std::vector<execplan::CalpontSystemCatalog::OID>& oidList)
void DDLPackageProcessor::removeFiles(const uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList)
{ {
SUMMARY_INFO("DDLPackageProcessor::removeFiles"); SUMMARY_INFO("DDLPackageProcessor::removeFiles");
ByteStream bytestream; ByteStream bytestream;
@ -593,11 +490,11 @@ void DDLPackageProcessor::removeFiles(const uint64_t uniqueId, std::vector<execp
fWEClient->addQueue(uniqueId); fWEClient->addQueue(uniqueId);
bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) oidList.size(); bytestream << (uint32_t)oidList.size();
for (unsigned i = 0; i < oidList.size(); i++) for (unsigned i = 0; i < oidList.size(); i++)
{ {
bytestream << (uint32_t) oidList[i]; bytestream << (uint32_t)oidList[i];
} }
uint32_t msgRecived = 0; uint32_t msgRecived = 0;
@ -618,7 +515,7 @@ void DDLPackageProcessor::removeFiles(const uint64_t uniqueId, std::vector<execp
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Network error while deleting files."; errorMsg = "Network error while deleting files.";
@ -654,7 +551,7 @@ void DDLPackageProcessor::removeFiles(const uint64_t uniqueId, std::vector<execp
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
if ( rc != 0) if (rc != 0)
{ {
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
@ -664,7 +561,8 @@ void DDLPackageProcessor::createFiles(CalpontSystemCatalog::TableName aTableName
const uint64_t uniqueId, const uint32_t numOids) const uint64_t uniqueId, const uint32_t numOids)
{ {
SUMMARY_INFO("DDLPackageProcessor::createFiles"); SUMMARY_INFO("DDLPackageProcessor::createFiles");
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(1); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(1);
CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(aTableName); CalpontSystemCatalog::RIDList ridList = systemCatalogPtr->columnRIDs(aTableName);
fWEClient->addQueue(uniqueId); fWEClient->addQueue(uniqueId);
CalpontSystemCatalog::ColType colType; CalpontSystemCatalog::ColType colType;
@ -678,21 +576,21 @@ void DDLPackageProcessor::createFiles(CalpontSystemCatalog::TableName aTableName
for (unsigned col = 0; col < ridList.size(); col++) for (unsigned col = 0; col < ridList.size(); col++)
{ {
colType = systemCatalogPtr->colType(ridList[col].objnum); colType = systemCatalogPtr->colType(ridList[col].objnum);
bytestream << (uint32_t) ridList[col].objnum; bytestream << (uint32_t)ridList[col].objnum;
bytestream << (uint8_t) colType.colDataType; bytestream << (uint8_t)colType.colDataType;
bytestream << (uint8_t) false; bytestream << (uint8_t) false;
bytestream << (uint32_t) colType.colWidth; bytestream << (uint32_t)colType.colWidth;
bytestream << (uint16_t) useDBRoot; bytestream << (uint16_t)useDBRoot;
bytestream << (uint32_t) colType.compressionType; bytestream << (uint32_t)colType.compressionType;
if (colType.ddn.dictOID > 3000) if (colType.ddn.dictOID > 3000)
{ {
bytestream << (uint32_t) colType.ddn.dictOID; bytestream << (uint32_t)colType.ddn.dictOID;
bytestream << (uint8_t) colType.colDataType; bytestream << (uint8_t)colType.colDataType;
bytestream << (uint8_t) true; bytestream << (uint8_t) true;
bytestream << (uint32_t) colType.colWidth; bytestream << (uint32_t)colType.colWidth;
bytestream << (uint16_t) useDBRoot; bytestream << (uint16_t)useDBRoot;
bytestream << (uint32_t) colType.compressionType; bytestream << (uint32_t)colType.compressionType;
} }
} }
@ -713,7 +611,7 @@ void DDLPackageProcessor::createFiles(CalpontSystemCatalog::TableName aTableName
{ {
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Network error while creating files."; errorMsg = "Network error while creating files.";
@ -747,20 +645,19 @@ void DDLPackageProcessor::createFiles(CalpontSystemCatalog::TableName aTableName
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
if ( rc != 0) if (rc != 0)
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
void DDLPackageProcessor::removePartitionFiles(std::vector<execplan::CalpontSystemCatalog::OID>& oidList, void DDLPackageProcessor::removePartitionFiles(std::vector<execplan::CalpontSystemCatalog::OID>& oidList,
const PartitionNums& partitions, const PartitionNums& partitions, uint64_t uniqueId)
uint64_t uniqueId)
{ {
SUMMARY_INFO("DDLPackageProcessor::removeFiles"); SUMMARY_INFO("DDLPackageProcessor::removeFiles");
ByteStream::byte rc = 0; ByteStream::byte rc = 0;
std::string errorMsg; std::string errorMsg;
//get a unique number. // get a unique number.
fWEClient->addQueue(uniqueId); fWEClient->addQueue(uniqueId);
// Write the tables metadata to the system catalog // Write the tables metadata to the system catalog
VERBOSE_INFO("Remove Partition Files"); VERBOSE_INFO("Remove Partition Files");
@ -800,7 +697,7 @@ void DDLPackageProcessor::removePartitionFiles(std::vector<execplan::CalpontSyst
bsIn->restart(); bsIn->restart();
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while dropping partitions"; errorMsg = "Lost connection to Write Engine Server while dropping partitions";
@ -846,14 +743,14 @@ void DDLPackageProcessor::removeExtents(std::vector<execplan::CalpontSystemCatal
BRM::errString(err, errMsg); BRM::errString(err, errMsg);
throw std::runtime_error(errMsg); throw std::runtime_error(errMsg);
} }
} }
void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog::OID tableOid, void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog::OID tableOid,
uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList) uint64_t uniqueId,
std::vector<execplan::CalpontSystemCatalog::OID>& oidList)
{ {
SUMMARY_INFO("DDLPackageProcessor::createWriteDropLogFile"); SUMMARY_INFO("DDLPackageProcessor::createWriteDropLogFile");
//For shared nothing, the meta files are created under data1 with controllernode. // For shared nothing, the meta files are created under data1 with controllernode.
OamCache* oamcache = OamCache::makeOamCache(); OamCache* oamcache = OamCache::makeOamCache();
std::string OAMParentModuleName = oamcache->getOAMParentModuleName(); std::string OAMParentModuleName = oamcache->getOAMParentModuleName();
OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length()); OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length());
@ -865,7 +762,7 @@ void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog:
bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPTABLE; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPTABLE;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t)tableOid; bytestream << (uint32_t)tableOid;
bytestream << (uint32_t) oidList.size(); bytestream << (uint32_t)oidList.size();
for (uint32_t i = 0; i < oidList.size(); i++) for (uint32_t i = 0; i < oidList.size(); i++)
{ {
@ -881,7 +778,7 @@ void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog:
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while writting drop table Log"; errorMsg = "Lost connection to Write Engine Server while writting drop table Log";
@ -900,7 +797,7 @@ void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog:
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = ex.what(); errorMsg = ex.what();
@ -908,14 +805,15 @@ void DDLPackageProcessor::createWriteDropLogFile(execplan::CalpontSystemCatalog:
catch (...) catch (...)
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Got unknown exception while writting drop table Log." ; errorMsg = "Got unknown exception while writting drop table Log.";
} }
if ( rc != 0) if (rc != 0)
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId) void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontSystemCatalog::OID tableOid,
uint64_t uniqueId)
{ {
SUMMARY_INFO("DDLPackageProcessor::deleteLogFile"); SUMMARY_INFO("DDLPackageProcessor::deleteLogFile");
OamCache* oamcache = OamCache::makeOamCache(); OamCache* oamcache = OamCache::makeOamCache();
@ -929,7 +827,7 @@ void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontS
boost::shared_ptr<messageqcpp::ByteStream> bsIn; boost::shared_ptr<messageqcpp::ByteStream> bsIn;
bytestream << (ByteStream::byte)WE_SVR_DELETE_DDLLOG; bytestream << (ByteStream::byte)WE_SVR_DELETE_DDLLOG;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) fileType; bytestream << (uint32_t)fileType;
bytestream << (uint32_t)tableOid; bytestream << (uint32_t)tableOid;
try try
@ -941,7 +839,7 @@ void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontS
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while deleting DDL log"; errorMsg = "Lost connection to Write Engine Server while deleting DDL log";
@ -960,7 +858,7 @@ void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontS
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = ex.what(); errorMsg = ex.what();
@ -968,12 +866,12 @@ void DDLPackageProcessor::deleteLogFile(LogFileType fileType, execplan::CalpontS
catch (...) catch (...)
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Got unknown exception while deleting DDL Log." ; errorMsg = "Got unknown exception while deleting DDL Log.";
} }
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
if ( rc != 0) if (rc != 0)
{ {
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
@ -985,7 +883,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo& tableLogInfos, uint64_t uni
OamCache* oamcache = OamCache::makeOamCache(); OamCache* oamcache = OamCache::makeOamCache();
std::string OAMParentModuleName = oamcache->getOAMParentModuleName(); std::string OAMParentModuleName = oamcache->getOAMParentModuleName();
//Use a sensible default so that substr doesn't throw... // Use a sensible default so that substr doesn't throw...
if (OAMParentModuleName.empty()) if (OAMParentModuleName.empty())
OAMParentModuleName = "pm1"; OAMParentModuleName = "pm1";
@ -1009,7 +907,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo& tableLogInfos, uint64_t uni
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while deleting DDL log"; errorMsg = "Lost connection to Write Engine Server while deleting DDL log";
@ -1020,7 +918,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo& tableLogInfos, uint64_t uni
*bsIn >> rc; *bsIn >> rc;
*bsIn >> errorMsg; *bsIn >> errorMsg;
while ( bsIn->length() > 0 ) while (bsIn->length() > 0)
{ {
*bsIn >> tmp32; *bsIn >> tmp32;
tableOid = tmp32; tableOid = tmp32;
@ -1047,7 +945,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo& tableLogInfos, uint64_t uni
partitionNums.insert(lp); partitionNums.insert(lp);
} }
//build the tableloginfo // build the tableloginfo
LogInfo aLog; LogInfo aLog;
aLog.fileType = logFileType; aLog.fileType = logFileType;
aLog.oids = oidsList; aLog.oids = oidsList;
@ -1059,7 +957,7 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo& tableLogInfos, uint64_t uni
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = ex.what(); errorMsg = ex.what();
@ -1067,18 +965,17 @@ void DDLPackageProcessor::fetchLogFile(TableLogInfo& tableLogInfos, uint64_t uni
catch (...) catch (...)
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Got unknown exception while fetching DDL Log." ; errorMsg = "Got unknown exception while fetching DDL Log.";
} }
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
if ( rc != 0) if (rc != 0)
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCatalog::OID tableOid, void DDLPackageProcessor::createWritePartitionLogFile(
const PartitionNums& partitionNums, execplan::CalpontSystemCatalog::OID tableOid, const PartitionNums& partitionNums,
std::vector<execplan::CalpontSystemCatalog::OID>& oidList, uint64_t uniqueId) std::vector<execplan::CalpontSystemCatalog::OID>& oidList, uint64_t uniqueId)
{ {
SUMMARY_INFO("DDLPackageProcessor::createWritePartitionLogFile"); SUMMARY_INFO("DDLPackageProcessor::createWritePartitionLogFile");
@ -1094,13 +991,13 @@ void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCat
bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPPARTITION; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPPARTITION;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t)tableOid; bytestream << (uint32_t)tableOid;
bytestream << (uint32_t) partitionNums.size(); bytestream << (uint32_t)partitionNums.size();
PartitionNums::const_iterator it; PartitionNums::const_iterator it;
for (it = partitionNums.begin(); it != partitionNums.end(); ++it) for (it = partitionNums.begin(); it != partitionNums.end(); ++it)
(*it).serialize(bytestream); (*it).serialize(bytestream);
bytestream << (uint32_t) oidList.size(); bytestream << (uint32_t)oidList.size();
for (uint32_t i = 0; i < oidList.size(); i++) for (uint32_t i = 0; i < oidList.size(); i++)
{ {
@ -1116,7 +1013,7 @@ void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCat
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while writing DDL drop partition log"; errorMsg = "Lost connection to Write Engine Server while writing DDL drop partition log";
@ -1135,7 +1032,7 @@ void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCat
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = ex.what(); errorMsg = ex.what();
@ -1143,19 +1040,21 @@ void DDLPackageProcessor::createWritePartitionLogFile(execplan::CalpontSystemCat
catch (...) catch (...)
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Got unknown exception while writting truncate Log." ; errorMsg = "Got unknown exception while writting truncate Log.";
} }
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
if ( rc != 0) if (rc != 0)
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList) void DDLPackageProcessor::createWriteTruncateTableLogFile(
execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId,
std::vector<execplan::CalpontSystemCatalog::OID>& oidList)
{ {
SUMMARY_INFO("DDLPackageProcessor::createWriteTruncateTableLogFile"); SUMMARY_INFO("DDLPackageProcessor::createWriteTruncateTableLogFile");
//For shared nothing, the meta files are created under data1 with controllernode. // For shared nothing, the meta files are created under data1 with controllernode.
OamCache* oamcache = OamCache::makeOamCache(); OamCache* oamcache = OamCache::makeOamCache();
std::string OAMParentModuleName = oamcache->getOAMParentModuleName(); std::string OAMParentModuleName = oamcache->getOAMParentModuleName();
OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length()); OAMParentModuleName = OAMParentModuleName.substr(2, OAMParentModuleName.length());
@ -1167,7 +1066,7 @@ void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSyste
bytestream << (ByteStream::byte)WE_SVR_WRITE_TRUNCATE; bytestream << (ByteStream::byte)WE_SVR_WRITE_TRUNCATE;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t)tableOid; bytestream << (uint32_t)tableOid;
bytestream << (uint32_t) oidList.size(); bytestream << (uint32_t)oidList.size();
for (uint32_t i = 0; i < oidList.size(); i++) for (uint32_t i = 0; i < oidList.size(); i++)
{ {
@ -1183,7 +1082,7 @@ void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSyste
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while writing truncate table log"; errorMsg = "Lost connection to Write Engine Server while writing truncate table log";
@ -1202,7 +1101,7 @@ void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSyste
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = ex.what(); errorMsg = ex.what();
@ -1210,10 +1109,10 @@ void DDLPackageProcessor::createWriteTruncateTableLogFile(execplan::CalpontSyste
catch (...) catch (...)
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Got unknown exception while writting truncate table Log." ; errorMsg = "Got unknown exception while writting truncate table Log.";
} }
if ( rc != 0) if (rc != 0)
throw std::runtime_error(errorMsg); throw std::runtime_error(errorMsg);
} }
@ -1413,9 +1312,9 @@ void DDLPackageProcessor::returnOIDs(execplan::CalpontSystemCatalog::RIDList& ri
} }
} }
void DDLPackageProcessor::findColumnData(uint32_t sessionID, execplan::CalpontSystemCatalog::TableName& systableName, void DDLPackageProcessor::findColumnData(uint32_t sessionID,
const std::string& colName, execplan::CalpontSystemCatalog::TableName& systableName,
DDLColumn& sysCol) const std::string& colName, DDLColumn& sysCol)
{ {
ColumnList columns; ColumnList columns;
ColumnList::const_iterator column_iterator; ColumnList::const_iterator column_iterator;
@ -1455,7 +1354,7 @@ void DDLPackageProcessor::cleanString(string& s)
{ {
string::size_type pos = s.find_first_not_of(" "); string::size_type pos = s.find_first_not_of(" ");
//stripe off space and ' or '' at beginning and end // stripe off space and ' or '' at beginning and end
if (pos < s.length()) if (pos < s.length())
{ {
s = s.substr(pos, s.length() - pos); s = s.substr(pos, s.length() - pos);
@ -1464,7 +1363,6 @@ void DDLPackageProcessor::cleanString(string& s)
{ {
s = s.substr(0, pos); s = s.substr(0, pos);
} }
} }
if (s[0] == '\'') if (s[0] == '\'')
@ -1483,13 +1381,16 @@ void DDLPackageProcessor::convertRidToColumn(uint64_t& rid, unsigned& dbRoot, un
{ {
partition = rid / (filesPerColumnPartition * extentsPerSegmentFile * extentRows); partition = rid / (filesPerColumnPartition * extentsPerSegmentFile * extentRows);
segment = (((rid % (filesPerColumnPartition * extentsPerSegmentFile * extentRows)) / extentRows)) % filesPerColumnPartition; segment = (((rid % (filesPerColumnPartition * extentsPerSegmentFile * extentRows)) / extentRows)) %
filesPerColumnPartition;
dbRoot = ((startDBRoot - 1 + segment) % dbrootCnt) + 1; dbRoot = ((startDBRoot - 1 + segment) % dbrootCnt) + 1;
//Calculate the relative rid for this segment file // Calculate the relative rid for this segment file
uint64_t relRidInPartition = rid - ((uint64_t)partition * (uint64_t)filesPerColumnPartition * (uint64_t)extentsPerSegmentFile * (uint64_t)extentRows); uint64_t relRidInPartition = rid - ((uint64_t)partition * (uint64_t)filesPerColumnPartition *
idbassert(relRidInPartition <= (uint64_t)filesPerColumnPartition * (uint64_t)extentsPerSegmentFile * (uint64_t)extentRows); (uint64_t)extentsPerSegmentFile * (uint64_t)extentRows);
idbassert(relRidInPartition <=
(uint64_t)filesPerColumnPartition * (uint64_t)extentsPerSegmentFile * (uint64_t)extentRows);
uint32_t numExtentsInThisPart = relRidInPartition / extentRows; uint32_t numExtentsInThisPart = relRidInPartition / extentRows;
unsigned numExtentsInThisSegPart = numExtentsInThisPart / filesPerColumnPartition; unsigned numExtentsInThisSegPart = numExtentsInThisPart / filesPerColumnPartition;
uint64_t relRidInThisExtent = relRidInPartition - numExtentsInThisPart * extentRows; uint64_t relRidInThisExtent = relRidInPartition - numExtentsInThisPart * extentRows;
@ -1499,7 +1400,7 @@ void DDLPackageProcessor::convertRidToColumn(uint64_t& rid, unsigned& dbRoot, un
int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID) int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID)
{ {
ByteStream bytestream; ByteStream bytestream;
bytestream << (ByteStream::byte) WE_SVR_ROLLBACK_BLOCKS; bytestream << (ByteStream::byte)WE_SVR_ROLLBACK_BLOCKS;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << sessionID; bytestream << sessionID;
bytestream << (uint32_t)txnID.id; bytestream << (uint32_t)txnID.id;
@ -1518,7 +1419,7 @@ int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
@ -1543,10 +1444,10 @@ int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID
if ((msgRecived == fWEClient->getPmCount()) && (rc == 0)) if ((msgRecived == fWEClient->getPmCount()) && (rc == 0))
{ {
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte) WE_SVR_ROLLBACK_VERSION; bytestream << (ByteStream::byte)WE_SVR_ROLLBACK_VERSION;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << sessionID; bytestream << sessionID;
bytestream << (uint32_t) txnID.id; bytestream << (uint32_t)txnID.id;
fWEClient->write_to_all(bytestream); fWEClient->write_to_all(bytestream);
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
msgRecived = 0; msgRecived = 0;
@ -1558,7 +1459,7 @@ int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
break; break;
@ -1576,7 +1477,6 @@ int DDLPackageProcessor::rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID
} }
else else
msgRecived++; msgRecived++;
} }
} }
} }
@ -1590,6 +1490,5 @@ int DDLPackageProcessor::commitTransaction(uint64_t uniqueId, BRM::TxnID txnID)
return rc; return rc;
} }
} // namespace } // namespace ddlpackageprocessor
// vim:ts=4 sw=4: // vim:ts=4 sw=4:

View File

@ -56,21 +56,20 @@
//#define IDB_DDL_DEBUG //#define IDB_DDL_DEBUG
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
#define SUMMARY_INFO(message) \
#define SUMMARY_INFO( message ) \ if (isDebug(SUMMARY)) \
if ( isDebug(SUMMARY) ) \
{ \ { \
std::cerr << message << std::endl; \ std::cerr << message << std::endl; \
} }
#define DETAIL_INFO( message ) \ #define DETAIL_INFO(message) \
if ( isDebug(DETAIL) ) \ if (isDebug(DETAIL)) \
{ \ { \
std::cerr << message << std::endl; \ std::cerr << message << std::endl; \
} }
#define VERBOSE_INFO( message ) \ #define VERBOSE_INFO(message) \
if ( isDebug(VERBOSE) ) \ if (isDebug(VERBOSE)) \
{ \ { \
std::cerr << message << std::endl; \ std::cerr << message << std::endl; \
} }
@ -80,14 +79,25 @@ namespace ddlpackageprocessor
*/ */
class DDLPackageProcessor class DDLPackageProcessor
{ {
public:
public:
/** @brief Result code /** @brief Result code
*/ */
enum ResultCode { NO_ERROR, CREATE_ERROR, ALTER_ERROR, DROP_ERROR, TRUNC_ERROR, enum ResultCode
TOKENIZATION_ERROR, NOT_ACCEPTING_PACKAGES, PK_NOTNULL_ERROR, WARNING, USER_ERROR, NETWORK_ERROR, PARTITION_WARNING, {
WARN_NO_PARTITION, DROP_TABLE_NOT_IN_CATALOG_ERROR NO_ERROR,
CREATE_ERROR,
ALTER_ERROR,
DROP_ERROR,
TRUNC_ERROR,
TOKENIZATION_ERROR,
NOT_ACCEPTING_PACKAGES,
PK_NOTNULL_ERROR,
WARNING,
USER_ERROR,
NETWORK_ERROR,
PARTITION_WARNING,
WARN_NO_PARTITION,
DROP_TABLE_NOT_IN_CATALOG_ERROR
}; };
enum DebugLevel /** @brief Debug level type enumeration */ enum DebugLevel /** @brief Debug level type enumeration */
@ -98,7 +108,12 @@ public:
VERBOSE = 3, /** @brief Detailed debug info */ VERBOSE = 3, /** @brief Detailed debug info */
}; };
enum LogFileType { DROPTABLE_LOG, DROPPART_LOG, TRUNCATE_LOG}; enum LogFileType
{
DROPTABLE_LOG,
DROPPART_LOG,
TRUNCATE_LOG
};
typedef std::vector<execplan::CalpontSystemCatalog::OID> OidList; typedef std::vector<execplan::CalpontSystemCatalog::OID> OidList;
typedef std::set<BRM::LogicalPartition> PartitionNums; typedef std::set<BRM::LogicalPartition> PartitionNums;
struct LogInfo struct LogInfo
@ -127,7 +142,7 @@ public:
{ {
execplan::CalpontSystemCatalog::OID oid; execplan::CalpontSystemCatalog::OID oid;
execplan::CalpontSystemCatalog::ColType colType; execplan::CalpontSystemCatalog::ColType colType;
execplan:: CalpontSystemCatalog::TableColName tableColName; execplan::CalpontSystemCatalog::TableColName tableColName;
}; };
/** @brief a list of DDLColumns /** @brief a list of DDLColumns
@ -167,7 +182,7 @@ public:
unsigned month : 4; unsigned month : 4;
unsigned year : 16; unsigned year : 16;
// NULL column value = 0xFFFFFFFE // NULL column value = 0xFFFFFFFE
EXPORT Date( ) EXPORT Date()
{ {
year = 0xFFFF; year = 0xFFFF;
month = 0xF; month = 0xF;
@ -196,7 +211,7 @@ public:
unsigned month : 4; unsigned month : 4;
unsigned year : 16; unsigned year : 16;
// NULL column value = 0xFFFFFFFFFFFFFFFE // NULL column value = 0xFFFFFFFFFFFFFFFE
EXPORT dateTime( ) EXPORT dateTime()
{ {
year = 0xFFFF; year = 0xFFFF;
month = 0xF; month = 0xF;
@ -226,11 +241,11 @@ public:
/** the type of a list of ColumnResult as returned from getSysData /** the type of a list of ColumnResult as returned from getSysData
*/ */
typedef std::vector <execplan::ColumnResult*> NJLSysDataVector; typedef std::vector<execplan::ColumnResult*> NJLSysDataVector;
struct NJLSysDataList struct NJLSysDataList
{ {
NJLSysDataVector sysDataVec; NJLSysDataVector sysDataVec;
EXPORT NJLSysDataList() {}; EXPORT NJLSysDataList(){};
EXPORT ~NJLSysDataList(); EXPORT ~NJLSysDataList();
NJLSysDataVector::const_iterator begin() NJLSysDataVector::const_iterator begin()
{ {
@ -262,25 +277,23 @@ public:
} }
}; };
/** @brief constructor /** @brief constructor
*/ */
DDLPackageProcessor(BRM::DBRM* aDbrm) : fStartingColOID(0), fDDLLoggingId(23), fDebugLevel( NONE ) DDLPackageProcessor(BRM::DBRM* aDbrm) : fStartingColOID(0), fDDLLoggingId(23), fDebugLevel(NONE)
{ {
fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DDLPROC); fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DDLPROC);
fPMCount = fWEClient->getPmCount(); fPMCount = fWEClient->getPmCount();
fDbrm = aDbrm; fDbrm = aDbrm;
//std::cout << "in DDLPackageProcessor constructor " << this << std::endl; // std::cout << "in DDLPackageProcessor constructor " << this << std::endl;
} }
/** @brief destructor /** @brief destructor
*/ */
EXPORT virtual ~DDLPackageProcessor(); EXPORT virtual ~DDLPackageProcessor();
/** @brief Is it required to debug /** @brief Is it required to debug
*/ */
bool isDebug( const DebugLevel level ) const bool isDebug(const DebugLevel level) const
{ {
return level <= fDebugLevel; return level <= fDebugLevel;
} }
@ -294,7 +307,7 @@ public:
/** @brief Set debug level /** @brief Set debug level
*/ */
void setDebugLevel( const DebugLevel level ) void setDebugLevel(const DebugLevel level)
{ {
fDebugLevel = level; fDebugLevel = level;
} }
@ -319,7 +332,7 @@ public:
{ {
return fPKName; return fPKName;
} }
void PKName (const std::string PKName) void PKName(const std::string PKName)
{ {
fPKName = PKName; fPKName = PKName;
} }
@ -328,7 +341,7 @@ public:
* @param oidList the list of OIDs for * @param oidList the list of OIDs for
* which the lbids for those files will be removed * which the lbids for those files will be removed
*/ */
EXPORT void flushPrimprocCache( std::vector<execplan::CalpontSystemCatalog::OID>& oidList ); EXPORT void flushPrimprocCache(std::vector<execplan::CalpontSystemCatalog::OID>& oidList);
/** @brief remove the physical files /** @brief remove the physical files
* *
@ -338,7 +351,8 @@ public:
*/ */
EXPORT void removeFiles(const uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList); EXPORT void removeFiles(const uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList);
EXPORT void createFiles(execplan::CalpontSystemCatalog::TableName aTableName, const int useDBRoot, const uint64_t uniqueId, const uint32_t numOids); EXPORT void createFiles(execplan::CalpontSystemCatalog::TableName aTableName, const int useDBRoot,
const uint64_t uniqueId, const uint32_t numOids);
/** @brief remove the physical files for the specified partition /** @brief remove the physical files for the specified partition
* *
@ -347,8 +361,7 @@ public:
* @param partition number * @param partition number
*/ */
EXPORT void removePartitionFiles(std::vector<execplan::CalpontSystemCatalog::OID>& oidList, EXPORT void removePartitionFiles(std::vector<execplan::CalpontSystemCatalog::OID>& oidList,
const PartitionNums& partitions, const PartitionNums& partitions, uint64_t uniqueId);
uint64_t uniqueId);
/** @brief remove the extents from extent map /** @brief remove the extents from extent map
* *
@ -359,14 +372,13 @@ public:
*/ */
EXPORT void removeExtents(std::vector<execplan::CalpontSystemCatalog::OID>& oidList); EXPORT void removeExtents(std::vector<execplan::CalpontSystemCatalog::OID>& oidList);
/** @brief create and open log file to log a table information /** @brief create and open log file to log a table information
* *
* @param tableOid the oid of the table * @param tableOid the oid of the table
* @param tableName the shcema, table name * @param tableName the shcema, table name
*/ */
EXPORT void createWriteDropLogFile(execplan::CalpontSystemCatalog::OID tableOid, EXPORT void createWriteDropLogFile(execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId,
uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList); std::vector<execplan::CalpontSystemCatalog::OID>& oidList);
/** @brief create and open log file to log a table partition information /** @brief create and open log file to log a table partition information
* *
@ -379,20 +391,22 @@ public:
std::vector<execplan::CalpontSystemCatalog::OID>& oidList, std::vector<execplan::CalpontSystemCatalog::OID>& oidList,
uint64_t uniqueId); uint64_t uniqueId);
// EXPORT void createOpenTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, execplan::CalpontSystemCatalog::TableName tableName); // EXPORT void createOpenTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid,
// execplan::CalpontSystemCatalog::TableName tableName);
/** @brief create and open log file to log a truncae table information /** @brief create and open log file to log a truncae table information
* *
* @param tableOid the oid of the table * @param tableOid the oid of the table
* @param tableName the shcema, table name * @param tableName the shcema, table name
*/ */
EXPORT void createWriteTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId, std::vector<execplan::CalpontSystemCatalog::OID>& oidList); EXPORT void createWriteTruncateTableLogFile(execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId,
std::vector<execplan::CalpontSystemCatalog::OID>& oidList);
/** @brief delete log file /** @brief delete log file
* *
*/ */
EXPORT void deleteLogFile(LogFileType fileType, execplan::CalpontSystemCatalog::OID tableOid, uint64_t uniqueId); EXPORT void deleteLogFile(LogFileType fileType, execplan::CalpontSystemCatalog::OID tableOid,
uint64_t uniqueId);
/** @brief fetch log file infomation /** @brief fetch log file infomation
* *
@ -401,15 +415,15 @@ public:
BRM::TxnID fTxnid; BRM::TxnID fTxnid;
protected: protected:
/** @brief get a list of DDLColumns for the given schema.table /** @brief get a list of DDLColumns for the given schema.table
* *
* @param schema the schema the table belongs to * @param schema the schema the table belongs to
* @param table the table name * @param table the table name
* @param colList will contain the list of columns on return * @param colList will contain the list of columns on return
*/ */
EXPORT void getColumnsForTable( uint32_t sessionID, std::string schema, std::string table, EXPORT void getColumnsForTable(uint32_t sessionID, std::string schema, std::string table,
ColumnList& colList ); ColumnList& colList);
/** @brief convert parsed ddl data type to a system catalog data type /** @brief convert parsed ddl data type to a system catalog data type
* *
@ -424,8 +438,7 @@ protected:
* @param data the value to tokenize * @param data the value to tokenize
*/ */
boost::any tokenizeData(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, boost::any tokenizeData(execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result,
const execplan::CalpontSystemCatalog::ColType& colType, const execplan::CalpontSystemCatalog::ColType& colType, const boost::any& data);
const boost::any& data );
/** @brief does the supplied constraint type require an index /** @brief does the supplied constraint type require an index
* *
@ -454,8 +467,7 @@ protected:
* @param constraintNumber the constraint number * @param constraintNumber the constraint number
* @param type the constraint type * @param type the constraint type
*/ */
std::string buildTableConstraintName(int oid, std::string buildTableConstraintName(int oid, ddlpackage::DDL_CONSTRAINTS type);
ddlpackage::DDL_CONSTRAINTS type);
/** @brief build a column constraint name /** @brief build a column constraint name
* *
@ -464,11 +476,8 @@ protected:
* @param column the column name * @param column the column name
* @param type the constraint type * @param type the constraint type
*/ */
std::string buildColumnConstraintName(const std::string& schema, std::string buildColumnConstraintName(const std::string& schema, const std::string& table,
const std::string& table, const std::string& column, ddlpackage::DDL_CONSTRAINTS type);
const std::string& column,
ddlpackage::DDL_CONSTRAINTS type);
/** @brief write the tables meta data to the SYSTABLE table /** @brief write the tables meta data to the SYSTABLE table
* *
@ -476,7 +485,8 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param tableDef the table definition * @param tableDef the table definition
*/ */
//void writeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, // void writeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const
// DDLResult& result,
// ddlpackage::TableDef& tableDef, uint32_t tableWithAutoi=0); // ddlpackage::TableDef& tableDef, uint32_t tableWithAutoi=0);
/** @brief write the table columns meta data to the SYSCOLUMN table /** @brief write the table columns meta data to the SYSCOLUMN table
@ -486,7 +496,8 @@ protected:
* @param tableDefCols the table columns definition * @param tableDefCols the table columns definition
* @param qualifiedName the name of catalog, schema, object names * @param qualifiedName the name of catalog, schema, object names
*/ */
//void writeSysColumnMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, // void writeSysColumnMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const
// DDLResult& result,
// ddlpackage::ColumnDefList& tableDefCols, // ddlpackage::ColumnDefList& tableDefCols,
// ddlpackage::QualifiedName& qualifiedName, int colpos, bool alterFlag=false ); // ddlpackage::QualifiedName& qualifiedName, int colpos, bool alterFlag=false );
@ -497,9 +508,11 @@ protected:
* @param constraintList the table constrain list * @param constraintList the table constrain list
* @param qualifiedName the name of catalog, schema, object names * @param qualifiedName the name of catalog, schema, object names
*/ */
// void writeTableSysConstraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void writeTableSysConstraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// ddlpackage::TableConstraintDefList& constraintList, ddlpackage::QualifiedName& // DDLResult& result,
// qualifiedName, bool alterFlag=false ); // ddlpackage::TableConstraintDefList& constraintList,
// ddlpackage::QualifiedName&
// qualifiedName, bool alterFlag=false );
/** @brief write the table constraint meta data to the SYSCONSTRAINTCOL table /** @brief write the table constraint meta data to the SYSCONSTRAINTCOL table
* *
* @param txnID the transaction id * @param txnID the transaction id
@ -507,9 +520,10 @@ protected:
* @param constraintList the table constrain list * @param constraintList the table constrain list
* @param qualifiedName the name of catalog, schema, object names * @param qualifiedName the name of catalog, schema, object names
*/ */
// void writeTableSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, // void writeTableSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// const DDLResult& result, ddlpackage::TableConstraintDefList& constraintList, // const DDLResult& result, ddlpackage::TableConstraintDefList&
// ddlpackage::QualifiedName& qualifiedName, bool alterFlag=false ); // constraintList, ddlpackage::QualifiedName& qualifiedName, bool
// alterFlag=false );
/** @brief write the column constraint meta data to the SYSCONTRAINT table /** @brief write the column constraint meta data to the SYSCONTRAINT table
* *
@ -518,9 +532,10 @@ protected:
* @param constraintList the table constrain list * @param constraintList the table constrain list
* @param qualifiedName the name of catalog, schema, object names * @param qualifiedName the name of catalog, schema, object names
*/ */
// void writeColumnSysConstraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, // void writeColumnSysConstraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// ddlpackage::ColumnDefList& tableDefCols, // const DDLResult& result,
// ddlpackage::QualifiedName& qualifiedName ); // ddlpackage::ColumnDefList& tableDefCols,
// ddlpackage::QualifiedName& qualifiedName );
/** @brief write the column constraint meta data to the SYSCONTRAINTCOL table /** @brief write the column constraint meta data to the SYSCONTRAINTCOL table
* *
@ -528,10 +543,10 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param tableDef the table definition * @param tableDef the table definition
*/ */
// void writeColumnSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, // void writeColumnSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN
// const DDLResult& result, ddlpackage::ColumnDefList& tableDefCols, // txnID,
// ddlpackage::QualifiedName& qualifiedName); // const DDLResult& result, ddlpackage::ColumnDefList& tableDefCols,
// ddlpackage::QualifiedName& qualifiedName);
/** @brief write the index meta data to the SYSINDEX table /** @brief write the index meta data to the SYSINDEX table
* *
@ -541,7 +556,8 @@ protected:
* @param consDef the table constraint * @param consDef the table constraint
* @param indexName name of the index * @param indexName name of the index
*/ */
// void writeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, // void writeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const
// DDLResult& result,
// ddlpackage::QualifiedName& qualifiedName, // ddlpackage::QualifiedName& qualifiedName,
// ddlpackage::DDL_CONSTRAINTS type, // ddlpackage::DDL_CONSTRAINTS type,
// std::string& indexName, bool multicol, bool alterFlag=false); // std::string& indexName, bool multicol, bool alterFlag=false);
@ -554,8 +570,9 @@ protected:
* @param constraintCols the list of columns in this index * @param constraintCols the list of columns in this index
* @param indexName name of the index * @param indexName name of the index
*/ */
// void writeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, // void writeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const
//ddlpackage::QualifiedName& qualifiedName, // DDLResult& result,
// ddlpackage::QualifiedName& qualifiedName,
// ddlpackage::ColumnNameList& constraintCols, // ddlpackage::ColumnNameList& constraintCols,
// std::string& indexName, bool alterFlag=false); // std::string& indexName, bool alterFlag=false);
@ -565,7 +582,7 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param tableName the qualified name of the table * @param tableName the qualified name of the table
*/ */
//void removeSysIndexMetaDataForTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, // void removeSysIndexMetaDataForTable(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// DDLResult& result, ddlpackage::QualifiedName& tableName); // DDLResult& result, ddlpackage::QualifiedName& tableName);
/** @brief remove all index columns for the supplied table from the SYSINDEXCOL table /** @brief remove all index columns for the supplied table from the SYSINDEXCOL table
@ -583,7 +600,8 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param indexName the qualified name of the index * @param indexName the qualified name of the index
*/ */
// void removeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeSysIndexMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult&
// result,
// ddlpackage::QualifiedName& indexName); // ddlpackage::QualifiedName& indexName);
/** @brief remove index columns from the SYSINDEXCOL table /** @brief remove index columns from the SYSINDEXCOL table
@ -592,7 +610,8 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param indexName the qualified name of the index * @param indexName the qualified name of the index
*/ */
// void removeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeSysIndexColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult&
// result,
// ddlpackage::QualifiedName& indexName); // ddlpackage::QualifiedName& indexName);
/** @brief remove the table meta data from the SYSTABLE table /** @brief remove the table meta data from the SYSTABLE table
@ -601,7 +620,8 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param tableName the qualified name of the table to remove * @param tableName the qualified name of the table to remove
*/ */
// void removeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeSysTableMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult&
// result,
// ddlpackage::QualifiedName& tableName); // ddlpackage::QualifiedName& tableName);
/** @brief remove the column meta data from the SYSCOLUMN table /** @brief remove the column meta data from the SYSCOLUMN table
@ -611,7 +631,8 @@ protected:
* @param tableName the qualified name of the table whose columns * @param tableName the qualified name of the table whose columns
* are to be removed * are to be removed
*/ */
// void removeSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult&
// result,
// ddlpackage::QualifiedName& tableName); // ddlpackage::QualifiedName& tableName);
/** @brief remove the column meta data from the SYSCOLUMN table /** @brief remove the column meta data from the SYSCOLUMN table
@ -621,7 +642,8 @@ protected:
* @param columnInfo the qualified name of the column * @param columnInfo the qualified name of the column
* to be removed * to be removed
*/ */
// void removeColSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeColSysColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult&
// result,
// ddlpackage::QualifiedName& columnInfo); // ddlpackage::QualifiedName& columnInfo);
/** @brief remove the constraint meta data from the SYSCONSTRAINT table /** @brief remove the constraint meta data from the SYSCONSTRAINT table
@ -631,7 +653,8 @@ protected:
* @param tableName the qualified name of the table whose constraints * @param tableName the qualified name of the table whose constraints
* are to be removed * are to be removed
*/ */
// void removeSysContraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeSysContraintMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// DDLResult& result,
// ddlpackage::QualifiedName& tableName); // ddlpackage::QualifiedName& tableName);
/** @brief remove the constraint meta data from the SYSCONSTRAINT table /** @brief remove the constraint meta data from the SYSCONSTRAINT table
@ -640,9 +663,9 @@ protected:
* @param result the result of the operation * @param result the result of the operation
* @param indexName the index name to be removed * @param indexName the index name to be removed
*/ */
// void removeSysIndexMetaDataForIndex(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, // void removeSysIndexMetaDataForIndex(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// DDLResult& result, // DDLResult& result,
// execplan::CalpontSystemCatalog::IndexNameList& indexNameList); // execplan::CalpontSystemCatalog::IndexNameList& indexNameList);
/** @brief remove the column constraint meta data from the SYSCONSTRAINTCOL table /** @brief remove the column constraint meta data from the SYSCONSTRAINTCOL table
* *
@ -651,7 +674,8 @@ protected:
* @param tableName the qualified name of the table whose column constraints * @param tableName the qualified name of the table whose column constraints
* are to be removed * are to be removed
*/ */
// void removeSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, DDLResult& result, // void removeSysConstraintColMetaData(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
// DDLResult& result,
// ddlpackage::QualifiedName& tableName); // ddlpackage::QualifiedName& tableName);
/** @brief remove the column constraint meta data from the SYSCONSTRAINT table /** @brief remove the column constraint meta data from the SYSCONSTRAINT table
* *
@ -728,7 +752,7 @@ protected:
* @param type the columns database type * @param type the columns database type
* @param data the columns string representation of it's data * @param data the columns string representation of it's data
*/ */
//boost::any convertColumnData( execplan::CalpontSystemCatalog::ColType colType, // boost::any convertColumnData( execplan::CalpontSystemCatalog::ColType colType,
// const std::string& data ); // const std::string& data );
/** /**
@ -740,7 +764,7 @@ protected:
* @param sysCol on success the returned sysCol object * @param sysCol on success the returned sysCol object
*/ */
void findColumnData(uint32_t sessionID, execplan::CalpontSystemCatalog::TableName& systableName, void findColumnData(uint32_t sessionID, execplan::CalpontSystemCatalog::TableName& systableName,
const std::string& colName, DDLColumn& sysCol ); const std::string& colName, DDLColumn& sysCol);
/** @brief remove the supplied row from the supplied system catalog table /** @brief remove the supplied row from the supplied system catalog table
* *
@ -748,8 +772,9 @@ protected:
* @param sysCatalogTableName the qualified name of the system catalog table * @param sysCatalogTableName the qualified name of the system catalog table
* @param rid the id of the row to remove * @param rid the id of the row to remove
*/ */
void removeRowFromSysCatalog(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, void removeRowFromSysCatalog(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
ddlpackage::QualifiedName& sysCatalogTableName, WriteEngine::RID& rid); const DDLResult& result, ddlpackage::QualifiedName& sysCatalogTableName,
WriteEngine::RID& rid);
/** @brief validate reference constraint for altering existing table /** @brief validate reference constraint for altering existing table
* *
@ -759,8 +784,7 @@ protected:
* @param refIndexName the index name of the referenced primary key constraint * @param refIndexName the index name of the referenced primary key constraint
* @return true if violation * @return true if violation
*/ */
bool referenceConstraintViolation(uint32_t sessionID, bool referenceConstraintViolation(uint32_t sessionID, DDLResult& result,
DDLResult& result,
execplan::CalpontSystemCatalog::TableColName tcn, execplan::CalpontSystemCatalog::TableColName tcn,
execplan::CalpontSystemCatalog::IndexName refIndexName); execplan::CalpontSystemCatalog::IndexName refIndexName);
@ -772,9 +796,7 @@ protected:
* @param constraintCols the columns associated with the primary key * @param constraintCols the columns associated with the primary key
* @return true if violation * @return true if violation
*/ */
bool PKConstraintViolation(uint32_t sessionID, bool PKConstraintViolation(uint32_t sessionID, DDLResult& result, ddlpackage::QualifiedName& qualifiedName,
DDLResult& result,
ddlpackage::QualifiedName& qualifiedName,
ddlpackage::ColumnNameList& constraintCols); ddlpackage::ColumnNameList& constraintCols);
/** @brief validate check constraint for altering existing table /** @brief validate check constraint for altering existing table
* *
@ -784,11 +806,8 @@ protected:
* @param checkConstraint the constraint text string * @param checkConstraint the constraint text string
* @return true if violation * @return true if violation
*/ */
bool checkConstraintViolation(uint32_t sessionID, bool checkConstraintViolation(uint32_t sessionID, DDLResult& result,
DDLResult& result, ddlpackage::QualifiedName& qualifiedName, std::string& checkConstraint);
ddlpackage::QualifiedName& qualifiedName,
std::string& checkConstraint);
/** @brief remove the supplied rows from the supplied system catalog table /** @brief remove the supplied rows from the supplied system catalog table
* *
@ -796,11 +815,10 @@ protected:
* @param sysCatalogTableName the qualified name of the system catalog table * @param sysCatalogTableName the qualified name of the system catalog table
* @param colRidList the list of row ids to remove * @param colRidList the list of row ids to remove
*/ */
void removeRowsFromSysCatalog(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID, const DDLResult& result, void removeRowsFromSysCatalog(uint32_t sessionID, execplan::CalpontSystemCatalog::SCN txnID,
ddlpackage::QualifiedName& sysCatalogTableName, const DDLResult& result, ddlpackage::QualifiedName& sysCatalogTableName,
execplan::CalpontSystemCatalog::RIDList& colRidList); execplan::CalpontSystemCatalog::RIDList& colRidList);
WriteEngine::WriteEngineWrapper fWriteEngine; WriteEngine::WriteEngineWrapper fWriteEngine;
BRM::DBRM* fDbrm; BRM::DBRM* fDbrm;
@ -809,7 +827,6 @@ protected:
uint32_t fPMCount; uint32_t fPMCount;
WriteEngine::WEClients* fWEClient; WriteEngine::WEClients* fWEClient;
DictionaryOIDList fDictionaryOIDList; DictionaryOIDList fDictionaryOIDList;
// store oids used during table and index creation // store oids used during table and index creation
@ -829,8 +846,8 @@ protected:
// is to make sure Calpont use the same system primary key name as Oracle // is to make sure Calpont use the same system primary key name as Oracle
unsigned const fDDLLoggingId; unsigned const fDDLLoggingId;
//std::ofstream fDDLLogFile; // std::ofstream fDDLLogFile;
//std::string fDDLLogFileName; // std::string fDDLLogFileName;
/** @brief convert absolute rid to relative rid in a segement file /** @brief convert absolute rid to relative rid in a segement file
* *
@ -840,43 +857,37 @@ protected:
* @param startDBRoot the dbroot this table starts * @param startDBRoot the dbroot this table starts
* @param dbrootCnt the number of dbroot in db * @param dbrootCnt the number of dbroot in db
*/ */
void convertRidToColumn(uint64_t& rid, unsigned& dbRoot, unsigned& partition, void convertRidToColumn(uint64_t& rid, unsigned& dbRoot, unsigned& partition, unsigned& segment,
unsigned& segment, unsigned filesPerColumnPartition, unsigned filesPerColumnPartition, unsigned extentsPerSegmentFile,
unsigned extentsPerSegmentFile, unsigned extentRows, unsigned extentRows, unsigned startDBRoot, unsigned dbrootCnt);
unsigned startDBRoot, unsigned dbrootCnt);
int rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID); int rollBackTransaction(uint64_t uniqueId, BRM::TxnID txnID, uint32_t sessionID);
int commitTransaction(uint64_t uniqueId, BRM::TxnID txnID); int commitTransaction(uint64_t uniqueId, BRM::TxnID txnID);
// MCOL-66 The DBRM can't handle concurrent DDL // MCOL-66 The DBRM can't handle concurrent DDL
static boost::mutex dbrmMutex; static boost::mutex dbrmMutex;
private:
private:
/** @brief clean beginning and ending glitches and spaces from string /** @brief clean beginning and ending glitches and spaces from string
* *
* @param s string to be cleaned * @param s string to be cleaned
*/ */
void cleanString(std::string& s); void cleanString(std::string& s);
//std::string fDDLLogFileName; // std::string fDDLLogFileName;
DebugLevel fDebugLevel; // internal use debug level DebugLevel fDebugLevel; // internal use debug level
}; };
/** @brief helper template function to do safe from string to type conversions /** @brief helper template function to do safe from string to type conversions
* *
*/ */
template <class T> template <class T>
bool from_string(T& t, bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&))
const std::string& s,
std::ios_base & (*f)(std::ios_base&))
{ {
std::istringstream iss(s); std::istringstream iss(s);
return !(iss >> f >> t).fail(); return !(iss >> f >> t).fail();
} }
} } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT
// vim:ts=4 sw=4: // vim:ts=4 sw=4:

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: ddlpackageprocessorfactory.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: ddlpackageprocessorfactory.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "ddlpackageprocessorfactory.h" #include "ddlpackageprocessorfactory.h"
#include "ddlpackage.h" #include "ddlpackage.h"
#include "alterpackageprocessor.h" #include "alterpackageprocessor.h"
@ -30,26 +30,18 @@ using namespace ddlpackage;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
DDLPackageProcessor* DDLPackageProcessorFactory::makePackageProcessor(int packageType,
DDLPackageProcessor* DDLPackageProcessorFactory:: ddlpackage::CalpontDDLPackage& cpackage)
makePackageProcessor(int packageType, ddlpackage::CalpontDDLPackage& cpackage)
{ {
DDLPackageProcessor* ddlProcPtr = 0; DDLPackageProcessor* ddlProcPtr = 0;
switch ( packageType ) switch (packageType)
{ {
case DDL_CREATE: case DDL_CREATE: ddlProcPtr = new CreatePackageProcessor(); break;
ddlProcPtr = new CreatePackageProcessor();
break;
case DDL_ALTER: case DDL_ALTER: ddlProcPtr = new AlterPackageProcessor(); break;
ddlProcPtr = new AlterPackageProcessor();
break;
case DDL_DROP:
ddlProcPtr = new DropPackageProcessor();
break;
case DDL_DROP: ddlProcPtr = new DropPackageProcessor(); break;
} }
return ddlProcPtr; return ddlProcPtr;

View File

@ -16,40 +16,33 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: ddlpackageprocessorfactory.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: ddlpackageprocessorfactory.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
#include <string> #include <string>
#include "ddlpkg.h" #include "ddlpkg.h"
#include "ddlpackageprocessor.h" #include "ddlpackageprocessor.h"
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
/** @brief create a ddlPackageProcessor object from a CalpontddlPackage object /** @brief create a ddlPackageProcessor object from a CalpontddlPackage object
* *
*/ */
class DDLPackageProcessorFactory class DDLPackageProcessorFactory
{ {
public:
public:
/** @brief static ddlPackageProcessor constructor method /** @brief static ddlPackageProcessor constructor method
* *
* @param packageType the ddl Package type * @param packageType the ddl Package type
* @param cpackage the CalpontddlPackage from which the ddlPackageProcessor is constructed * @param cpackage the CalpontddlPackage from which the ddlPackageProcessor is constructed
*/ */
static DDLPackageProcessor* static DDLPackageProcessor* makePackageProcessor(int packageType, ddlpackage::CalpontDDLPackage& cpackage);
makePackageProcessor( int packageType, ddlpackage::CalpontDDLPackage& cpackage );
protected: protected:
private:
private:
}; };
} } // namespace ddlpackageprocessor

View File

@ -30,11 +30,13 @@ using namespace logging;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(ddlpackage::DropIndexStatement& dropIndexStmt) DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(
ddlpackage::DropIndexStatement& dropIndexStmt)
{ {
SUMMARY_INFO("DropIndexProcessor::processPackage"); SUMMARY_INFO("DropIndexProcessor::processPackage");
boost::shared_ptr<CalpontSystemCatalog> sysCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog( dropIndexStmt.fSessionID ); boost::shared_ptr<CalpontSystemCatalog> sysCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(dropIndexStmt.fSessionID);
CalpontSystemCatalog::IndexName indexName; CalpontSystemCatalog::IndexName indexName;
CalpontSystemCatalog::IndexOID indexOID; CalpontSystemCatalog::IndexOID indexOID;
@ -53,8 +55,9 @@ DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(ddlpackage::Dro
indexName.schema = dropIndexStmt.fIndexName->fSchema; indexName.schema = dropIndexStmt.fIndexName->fSchema;
indexName.index = dropIndexStmt.fIndexName->fName; indexName.index = dropIndexStmt.fIndexName->fName;
//Look up table name from indexname. Oracle will error out if same constraintname or indexname exists. // Look up table name from indexname. Oracle will error out if same constraintname or indexname exists.
CalpontSystemCatalog::TableName tableName = sysCatalogPtr->lookupTableForIndex (dropIndexStmt.fIndexName->fName, dropIndexStmt.fIndexName->fSchema ); CalpontSystemCatalog::TableName tableName =
sysCatalogPtr->lookupTableForIndex(dropIndexStmt.fIndexName->fName, dropIndexStmt.fIndexName->fSchema);
indexName.table = tableName.table; indexName.table = tableName.table;
indexOID = sysCatalogPtr->lookupIndexNbr(indexName); indexOID = sysCatalogPtr->lookupIndexNbr(indexName);
@ -76,7 +79,6 @@ DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(ddlpackage::Dro
goto rollback; goto rollback;
} }
VERBOSE_INFO("Removing the index files"); VERBOSE_INFO("Removing the index files");
err = fWriteEngine.dropIndex(txnID.id, indexOID.objnum, indexOID.listOID); err = fWriteEngine.dropIndex(txnID.id, indexOID.objnum, indexOID.listOID);
@ -90,7 +92,7 @@ DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(ddlpackage::Dro
logging::logDDL(dropIndexStmt.fSessionID, txnID.id, dropIndexStmt.fSql, dropIndexStmt.fOwner); logging::logDDL(dropIndexStmt.fSessionID, txnID.id, dropIndexStmt.fSql, dropIndexStmt.fOwner);
// register the changes // register the changes
err = fWriteEngine.commit( txnID.id ); err = fWriteEngine.commit(txnID.id);
if (err) if (err)
{ {
@ -99,8 +101,8 @@ DropIndexProcessor::DDLResult DropIndexProcessor::processPackage(ddlpackage::Dro
} }
fSessionManager.committed(txnID); fSessionManager.committed(txnID);
//fObjectIDManager.returnOID(indexOID.objnum); // fObjectIDManager.returnOID(indexOID.objnum);
//fObjectIDManager.returnOID(indexOID.listOID); // fObjectIDManager.returnOID(indexOID.listOID);
return result; return result;
rollback: rollback:
@ -109,6 +111,4 @@ rollback:
return result; return result;
} }
} // namespace ddlpackageprocessor } // namespace ddlpackageprocessor

View File

@ -33,17 +33,15 @@ namespace ddlpackageprocessor
*/ */
class DropIndexProcessor : public DDLPackageProcessor class DropIndexProcessor : public DDLPackageProcessor
{ {
public: public:
/** @brief process a drop index statement /** @brief process a drop index statement
* *
* @param dropIndexStmt the drop index statement * @param dropIndexStmt the drop index statement
*/ */
DDLResult processPackage(ddlpackage::DropIndexStatement& dropIndexStmt); DDLResult processPackage(ddlpackage::DropIndexStatement& dropIndexStmt);
protected: protected:
private:
private:
}; };
} //namespace ddlpackageprocessor } // namespace ddlpackageprocessor

View File

@ -37,8 +37,8 @@ using namespace oam;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(
DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpackage::DropPartitionStatement& dropPartitionStmt) ddlpackage::DropPartitionStatement& dropPartitionStmt)
{ {
SUMMARY_INFO("DropPartitionProcessor::processPackage"); SUMMARY_INFO("DropPartitionProcessor::processPackage");
@ -57,7 +57,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
txnID.id = fTxnid.id; txnID.id = fTxnid.id;
txnID.valid = fTxnid.valid; txnID.valid = fTxnid.valid;
if (rc != 0 ) if (rc != 0)
{ {
logging::Message::Args args; logging::Message::Args args;
logging::Message message(9); logging::Message message(9);
@ -69,8 +69,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
return result; return result;
} }
std::vector<CalpontSystemCatalog::OID> oidList;
std::vector <CalpontSystemCatalog::OID> oidList;
CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::RIDList tableColRidList;
CalpontSystemCatalog::DictOIDList dictOIDList; CalpontSystemCatalog::DictOIDList dictOIDList;
execplan::CalpontSystemCatalog::ROPair roPair; execplan::CalpontSystemCatalog::ROPair roPair;
@ -80,7 +79,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
std::string processName("DDLProc"); std::string processName("DDLProc");
uint64_t uniqueId = 0; uint64_t uniqueId = 0;
//Bug 5070. Added exception handling // Bug 5070. Added exception handling
try try
{ {
uniqueId = fDbrm->getUnique64(); uniqueId = fDbrm->getUnique64();
@ -96,7 +95,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
catch ( ... ) catch (...)
{ {
logging::Message::Args args; logging::Message::Args args;
logging::Message message(9); logging::Message message(9);
@ -113,17 +112,18 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
try try
{ {
//check table lock // check table lock
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropPartitionStmt.fSessionID); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(dropPartitionStmt.fSessionID);
systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->identity(CalpontSystemCatalog::EC);
systemCatalogPtr->sessionID(dropPartitionStmt.fSessionID); systemCatalogPtr->sessionID(dropPartitionStmt.fSessionID);
CalpontSystemCatalog::TableName tableName; CalpontSystemCatalog::TableName tableName;
tableName.schema = dropPartitionStmt.fTableName->fSchema; tableName.schema = dropPartitionStmt.fTableName->fSchema;
tableName.table = dropPartitionStmt.fTableName->fName; tableName.table = dropPartitionStmt.fTableName->fName;
roPair = systemCatalogPtr->tableRID( tableName ); roPair = systemCatalogPtr->tableRID(tableName);
//@Bug 3054 check for system catalog //@Bug 3054 check for system catalog
if ( roPair.objnum < 3000 ) if (roPair.objnum < 3000)
{ {
throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog."); throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog.");
} }
@ -141,7 +141,8 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
try try
{ {
uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID,
(int32_t*)&txnID.id, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -152,7 +153,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
return result; return result;
} }
if ( uniqueID == 0 ) if (uniqueID == 0)
{ {
int waitPeriod = 10; int waitPeriod = 10;
int sleepTime = 100; // sleep 100 milliseconds between checks int sleepTime = 100; // sleep 100 milliseconds between checks
@ -175,8 +176,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
{ {
abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_sec = rm_ts.tv_sec;
abs_ts.tv_nsec = rm_ts.tv_nsec; abs_ts.tv_nsec = rm_ts.tv_nsec;
} } while (nanosleep(&abs_ts, &rm_ts) < 0);
while (nanosleep(&abs_ts, &rm_ts) < 0);
#endif #endif
// reset // reset
@ -188,7 +188,8 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
try try
{ {
uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID,
(int32_t*)&txnID.id, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -202,7 +203,7 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
break; break;
} }
if (i >= numTries) //error out if (i >= numTries) // error out
{ {
result.result = DROP_ERROR; result.result = DROP_ERROR;
logging::Message::Args args; logging::Message::Args args;
@ -229,29 +230,28 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
userTableName.schema = dropPartitionStmt.fTableName->fSchema; userTableName.schema = dropPartitionStmt.fTableName->fSchema;
userTableName.table = dropPartitionStmt.fTableName->fName; userTableName.table = dropPartitionStmt.fTableName->fName;
tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); tableColRidList = systemCatalogPtr->columnRIDs(userTableName);
dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); dictOIDList = systemCatalogPtr->dictOIDs(userTableName);
//Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format // Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format
for ( unsigned i = 0; i < tableColRidList.size(); i++ ) for (unsigned i = 0; i < tableColRidList.size(); i++)
{ {
if ( tableColRidList[i].objnum > 3000 ) if (tableColRidList[i].objnum > 3000)
oidList.push_back( tableColRidList[i].objnum ); oidList.push_back(tableColRidList[i].objnum);
} }
for ( unsigned i = 0; i < dictOIDList.size(); i++ ) for (unsigned i = 0; i < dictOIDList.size(); i++)
{ {
if ( dictOIDList[i].dictOID > 3000 ) if (dictOIDList[i].dictOID > 3000)
oidList.push_back( dictOIDList[i].dictOID ); oidList.push_back(dictOIDList[i].dictOID);
} }
//Mark the partition disabled from extent map // Mark the partition disabled from extent map
string emsg; string emsg;
rc = fDbrm->markPartitionForDeletion( oidList, dropPartitionStmt.fPartitions, emsg); rc = fDbrm->markPartitionForDeletion(oidList, dropPartitionStmt.fPartitions, emsg);
if (rc != 0 && rc != BRM::ERR_PARTITION_DISABLED && if (rc != 0 && rc != BRM::ERR_PARTITION_DISABLED && rc != BRM::ERR_INVALID_OP_LAST_PARTITION &&
rc != BRM::ERR_INVALID_OP_LAST_PARTITION &&
rc != BRM::ERR_NOT_EXIST_PARTITION) rc != BRM::ERR_NOT_EXIST_PARTITION)
{ {
throw std::runtime_error(emsg); throw std::runtime_error(emsg);
@ -280,19 +280,19 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
markedPartitions.insert(*it); markedPartitions.insert(*it);
} }
//Save the oids to a file // Save the oids to a file
createWritePartitionLogFile( roPair.objnum, markedPartitions, oidList, uniqueId); createWritePartitionLogFile(roPair.objnum, markedPartitions, oidList, uniqueId);
VERBOSE_INFO("Removing files"); VERBOSE_INFO("Removing files");
removePartitionFiles( oidList, markedPartitions, uniqueId ); removePartitionFiles(oidList, markedPartitions, uniqueId);
//Flush PrimProc cache for those lbids // Flush PrimProc cache for those lbids
rc = cacheutils::flushPartition( oidList, markedPartitions ); rc = cacheutils::flushPartition(oidList, markedPartitions);
//Remove the partition from extent map // Remove the partition from extent map
emsg.clear(); emsg.clear();
rc = fDbrm->deletePartition( oidList, dropPartitionStmt.fPartitions, emsg); rc = fDbrm->deletePartition(oidList, dropPartitionStmt.fPartitions, emsg);
if ( rc != 0 ) if (rc != 0)
throw std::runtime_error(emsg); throw std::runtime_error(emsg);
} }
catch (exception& ex) catch (exception& ex)
@ -333,10 +333,10 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
logging::Message::Args args; logging::Message::Args args;
logging::Message message(1); logging::Message message(1);
args.add("Drop partition failed: "); args.add("Drop partition failed: ");
args.add( "encountered unkown exception" ); args.add("encountered unkown exception");
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = DROP_ERROR; result.result = DROP_ERROR;
result.message = message; result.message = message;
@ -358,8 +358,8 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
// Log the DDL statement // Log the DDL statement
logging::logDDL(dropPartitionStmt.fSessionID, txnID.id, dropPartitionStmt.fSql, dropPartitionStmt.fOwner); logging::logDDL(dropPartitionStmt.fSessionID, txnID.id, dropPartitionStmt.fSql, dropPartitionStmt.fOwner);
//Remove the log file // Remove the log file
//release the transaction // release the transaction
try try
{ {
fDbrm->releaseTableLock(uniqueID); fDbrm->releaseTableLock(uniqueID);
@ -377,4 +377,4 @@ DropPartitionProcessor::DDLResult DropPartitionProcessor::processPackage(ddlpack
return result; return result;
} }
} } // namespace ddlpackageprocessor

View File

@ -39,20 +39,19 @@ namespace ddlpackageprocessor
*/ */
class DropPartitionProcessor : public DDLPackageProcessor class DropPartitionProcessor : public DDLPackageProcessor
{ {
public: public:
DropPartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} DropPartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
{
}
/** @brief process a drop table statement /** @brief process a drop table statement
* *
* @param dropTableStmt the drop table statement * @param dropTableStmt the drop table statement
*/ */
EXPORT DDLResult processPackage(ddlpackage::DropPartitionStatement& dropPartitionStmt); EXPORT DDLResult processPackage(ddlpackage::DropPartitionStatement& dropPartitionStmt);
protected: protected:
private:
private:
}; };
} // namespace ddlpackageprocessor } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT

View File

@ -50,8 +50,8 @@ using namespace oam;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
DropTableProcessor::DDLResult DropTableProcessor::processPackage(
DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::DropTableStatement& dropTableStmt) ddlpackage::DropTableStatement& dropTableStmt)
{ {
SUMMARY_INFO("DropTableProcessor::processPackage"); SUMMARY_INFO("DropTableProcessor::processPackage");
@ -70,7 +70,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
int rc1 = 0; int rc1 = 0;
rc1 = fDbrm->isReadWrite(); rc1 = fDbrm->isReadWrite();
if (rc1 != 0 ) if (rc1 != 0)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
@ -85,7 +85,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
string stmt = dropTableStmt.fSql + "|" + dropTableStmt.fTableName->fSchema + "|"; string stmt = dropTableStmt.fSql + "|" + dropTableStmt.fTableName->fSchema + "|";
SQLLogger logger(stmt, fDDLLoggingId, dropTableStmt.fSessionID, txnID.id); SQLLogger logger(stmt, fDDLLoggingId, dropTableStmt.fSessionID, txnID.id);
std::vector <CalpontSystemCatalog::OID> oidList; std::vector<CalpontSystemCatalog::OID> oidList;
CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::RIDList tableColRidList;
CalpontSystemCatalog::DictOIDList dictOIDList; CalpontSystemCatalog::DictOIDList dictOIDList;
execplan::CalpontSystemCatalog::ROPair roPair; execplan::CalpontSystemCatalog::ROPair roPair;
@ -93,7 +93,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
ByteStream bytestream; ByteStream bytestream;
uint64_t uniqueId = 0; uint64_t uniqueId = 0;
//Bug 5070. Added exception handling // Bug 5070. Added exception handling
try try
{ {
uniqueId = fDbrm->getUnique64(); uniqueId = fDbrm->getUnique64();
@ -109,7 +109,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
catch ( ... ) catch (...)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
@ -133,8 +133,9 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
try try
{ {
//check table lock // check table lock
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(dropTableStmt.fSessionID); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(dropTableStmt.fSessionID);
systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->identity(CalpontSystemCatalog::EC);
systemCatalogPtr->sessionID(dropTableStmt.fSessionID); systemCatalogPtr->sessionID(dropTableStmt.fSessionID);
CalpontSystemCatalog::TableName tableName; CalpontSystemCatalog::TableName tableName;
@ -187,14 +188,15 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
try try
{ {
tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); tableLockId =
fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
} }
if ( tableLockId == 0 ) if (tableLockId == 0)
{ {
int waitPeriod = 10; int waitPeriod = 10;
int sleepTime = 100; // sleep 100 milliseconds between checks int sleepTime = 100; // sleep 100 milliseconds between checks
@ -217,8 +219,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
{ {
abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_sec = rm_ts.tv_sec;
abs_ts.tv_nsec = rm_ts.tv_nsec; abs_ts.tv_nsec = rm_ts.tv_nsec;
} } while (nanosleep(&abs_ts, &rm_ts) < 0);
while (nanosleep(&abs_ts, &rm_ts) < 0);
#endif #endif
@ -226,9 +227,11 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
{ {
processID = ::getpid(); processID = ::getpid();
txnid = txnID.id; txnid = txnID.id;
sessionId = dropTableStmt.fSessionID;; sessionId = dropTableStmt.fSessionID;
;
processName = "DDLProc"; processName = "DDLProc";
tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid,
BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -239,7 +242,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
break; break;
} }
if (i >= numTries) //error out if (i >= numTries) // error out
{ {
Message::Args args; Message::Args args;
string strOp("drop table"); string strOp("drop table");
@ -266,37 +269,37 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
userTableName.schema = dropTableStmt.fTableName->fSchema; userTableName.schema = dropTableStmt.fTableName->fSchema;
userTableName.table = dropTableStmt.fTableName->fName; userTableName.table = dropTableStmt.fTableName->fName;
tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); tableColRidList = systemCatalogPtr->columnRIDs(userTableName);
dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); dictOIDList = systemCatalogPtr->dictOIDs(userTableName);
Oam oam; Oam oam;
//Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format // Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format
for ( unsigned i = 0; i < tableColRidList.size(); i++ ) for (unsigned i = 0; i < tableColRidList.size(); i++)
{ {
if ( tableColRidList[i].objnum > 3000 ) if (tableColRidList[i].objnum > 3000)
oidList.push_back( tableColRidList[i].objnum ); oidList.push_back(tableColRidList[i].objnum);
} }
for ( unsigned i = 0; i < dictOIDList.size(); i++ ) for (unsigned i = 0; i < dictOIDList.size(); i++)
{ {
if ( dictOIDList[i].dictOID > 3000 ) if (dictOIDList[i].dictOID > 3000)
oidList.push_back( dictOIDList[i].dictOID ); oidList.push_back(dictOIDList[i].dictOID);
} }
//get a unique number // get a unique number
VERBOSE_INFO("Removing the SYSTABLE meta data"); VERBOSE_INFO("Removing the SYSTABLE meta data");
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Removing the SYSTABLEs meta data" << endl; cout << fTxnid.id << " Removing the SYSTABLEs meta data" << endl;
#endif #endif
bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSTABLE; bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSTABLE;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) dropTableStmt.fSessionID; bytestream << (uint32_t)dropTableStmt.fSessionID;
bytestream << (uint32_t)txnID.id; bytestream << (uint32_t)txnID.id;
bytestream << dropTableStmt.fTableName->fSchema; bytestream << dropTableStmt.fTableName->fSchema;
bytestream << dropTableStmt.fTableName->fName; bytestream << dropTableStmt.fTableName->fName;
//Find out where systable is // Find out where systable is
BRM::OID_t sysOid = 1001; BRM::OID_t sysOid = 1001;
ByteStream::byte rc = 0; ByteStream::byte rc = 0;
@ -305,13 +308,13 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
if (rc != 0) if (rc != 0)
{ {
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Error while calling getSysCatDBRoot"); args.add("Error while calling getSysCatDBRoot");
args.add(errorMsg); args.add(errorMsg);
result.message = message; result.message = message;
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -324,7 +327,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Drop table sending WE_SVR_DELETE_SYSTABLES to pm " << pmNum << endl; cout << fTxnid.id << " Drop table sending WE_SVR_DELETE_SYSTABLES to pm " << pmNum << endl;
#endif #endif
//cout << "deleting systable entries with txnid " << txnID.id << endl; // cout << "deleting systable entries with txnid " << txnID.id << endl;
fWEClient->write(bytestream, (uint32_t)pmNum); fWEClient->write(bytestream, (uint32_t)pmNum);
while (1) while (1)
@ -332,7 +335,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
@ -351,7 +354,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Drop table got exception" << endl; cout << fTxnid.id << " Drop table got exception" << endl;
@ -369,7 +372,8 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
if (rc != 0) if (rc != 0)
{ {
cout << fTxnid.id << " Error in dropping table from systables(" << (int)rc << ") " << errorMsg.c_str() << endl; cout << fTxnid.id << " Error in dropping table from systables(" << (int)rc << ") " << errorMsg.c_str()
<< endl;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Error in dropping table from systables."); args.add("Error in dropping table from systables.");
@ -377,35 +381,35 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
message.format(args); message.format(args);
result.result = (ResultCode)rc; result.result = (ResultCode)rc;
result.message = message; result.message = message;
//release table lock and session // release table lock and session
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
(void)fDbrm->releaseTableLock(tableLockId); (void)fDbrm->releaseTableLock(tableLockId);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
return result; return result;
} }
//remove from syscolumn // remove from syscolumn
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSCOLUMN; bytestream << (ByteStream::byte)WE_SVR_DELETE_SYSCOLUMN;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) dropTableStmt.fSessionID; bytestream << (uint32_t)dropTableStmt.fSessionID;
bytestream << (uint32_t)txnID.id; bytestream << (uint32_t)txnID.id;
bytestream << dropTableStmt.fTableName->fSchema; bytestream << dropTableStmt.fTableName->fSchema;
bytestream << dropTableStmt.fTableName->fName; bytestream << dropTableStmt.fTableName->fName;
//Find out where syscolumn is // Find out where syscolumn is
sysOid = 1021; sysOid = 1021;
rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot); rc = fDbrm->getSysCatDBRoot(sysOid, dbRoot);
if (rc != 0) if (rc != 0)
{ {
result.result = (ResultCode) rc; result.result = (ResultCode)rc;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Error while calling getSysCatDBRoot"); args.add("Error while calling getSysCatDBRoot");
args.add(errorMsg); args.add(errorMsg);
result.message = message; result.message = message;
//release transaction // release transaction
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -424,7 +428,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
@ -443,7 +447,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
} }
} }
} }
catch (runtime_error& ex) //write error catch (runtime_error& ex) // write error
{ {
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Drop table got exception" << endl; cout << fTxnid.id << " Drop table got exception" << endl;
@ -461,7 +465,8 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
if (rc != 0) if (rc != 0)
{ {
cout << fTxnid.id << " Error in dropping column from systables(" << (int)rc << ") " << errorMsg.c_str() << endl; cout << fTxnid.id << " Error in dropping column from systables(" << (int)rc << ") " << errorMsg.c_str()
<< endl;
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Error in dropping column from systables."); args.add("Error in dropping column from systables.");
@ -469,7 +474,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
message.format(args); message.format(args);
result.result = (ResultCode)rc; result.result = (ResultCode)rc;
result.message = message; result.message = message;
//release table lock and session // release table lock and session
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
(void)fDbrm->releaseTableLock(tableLockId); (void)fDbrm->releaseTableLock(tableLockId);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
@ -480,7 +485,8 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
if (rc != 0) if (rc != 0)
{ {
cout << txnID.id << " rolledback transaction " << " and valid is " << txnID.valid << endl; cout << txnID.id << " rolledback transaction "
<< " and valid is " << txnID.valid << endl;
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
} }
else else
@ -526,7 +532,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
} }
message.format( args ); message.format(args);
result.message = message; result.message = message;
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
return result; return result;
@ -550,7 +556,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
} }
message.format( args ); message.format(args);
result.message = message; result.message = message;
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
return result; return result;
@ -568,16 +574,16 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
args.add("Drop table failed due to "); args.add("Drop table failed due to ");
args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
message.format( args ); message.format(args);
result.message = message; result.message = message;
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
return result; return result;
} }
//Save the oids to a file // Save the oids to a file
try try
{ {
createWriteDropLogFile( roPair.objnum, uniqueId, oidList ); createWriteDropLogFile(roPair.objnum, uniqueId, oidList);
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
@ -598,15 +604,15 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
// no open handles to hinder the deletion of the files. // no open handles to hinder the deletion of the files.
rc = cacheutils::dropPrimProcFdCache(); rc = cacheutils::dropPrimProcFdCache();
//Drop files // Drop files
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) oidList.size(); bytestream << (uint32_t)oidList.size();
for (unsigned i = 0; i < oidList.size(); i++) for (unsigned i = 0; i < oidList.size(); i++)
{ {
bytestream << (uint32_t) oidList[i]; bytestream << (uint32_t)oidList[i];
} }
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
@ -628,7 +634,7 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
@ -678,11 +684,11 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
return result; return result;
} }
//Drop PrimProc FD cache // Drop PrimProc FD cache
rc = cacheutils::dropPrimProcFdCache(); rc = cacheutils::dropPrimProcFdCache();
//Flush primProc cache // Flush primProc cache
rc = cacheutils::flushOIDsFromCache( oidList ); rc = cacheutils::flushOIDsFromCache(oidList);
//Delete extents from extent map // Delete extents from extent map
#ifdef IDB_DDL_DEBUG #ifdef IDB_DDL_DEBUG
cout << fTxnid.id << " Drop table deleteOIDs" << endl; cout << fTxnid.id << " Drop table deleteOIDs" << endl;
#endif #endif
@ -693,10 +699,10 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add("Table dropped with warning "); args.add("Table dropped with warning ");
args.add( "Remove from extent map failed." ); args.add("Remove from extent map failed.");
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = WARNING; result.result = WARNING;
result.message = message; result.message = message;
@ -705,17 +711,17 @@ DropTableProcessor::DDLResult DropTableProcessor::processPackage(ddlpackage::Dro
return result; return result;
} }
//Remove the log file // Remove the log file
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
deleteLogFile(DROPTABLE_LOG, roPair.objnum, uniqueId); deleteLogFile(DROPTABLE_LOG, roPair.objnum, uniqueId);
//release the transaction // release the transaction
//fSessionManager.committed(txnID); // fSessionManager.committed(txnID);
returnOIDs( tableColRidList, dictOIDList ); returnOIDs(tableColRidList, dictOIDList);
return result; return result;
} }
TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::TruncTableStatement& truncTableStmt) TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(
ddlpackage::TruncTableStatement& truncTableStmt)
{ {
SUMMARY_INFO("TruncTableProcessor::processPackage"); SUMMARY_INFO("TruncTableProcessor::processPackage");
// 1. lock the table // 1. lock the table
@ -741,7 +747,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
txnID.id = fTxnid.id; txnID.id = fTxnid.id;
txnID.valid = fTxnid.valid; txnID.valid = fTxnid.valid;
if (rc != 0 ) if (rc != 0)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
@ -757,21 +763,23 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
string stmt = truncTableStmt.fSql + "|" + truncTableStmt.fTableName->fSchema + "|"; string stmt = truncTableStmt.fSql + "|" + truncTableStmt.fTableName->fSchema + "|";
SQLLogger logger(stmt, fDDLLoggingId, truncTableStmt.fSessionID, txnID.id); SQLLogger logger(stmt, fDDLLoggingId, truncTableStmt.fSessionID, txnID.id);
std::vector <CalpontSystemCatalog::OID> columnOidList; std::vector<CalpontSystemCatalog::OID> columnOidList;
std::vector <CalpontSystemCatalog::OID> allOidList; std::vector<CalpontSystemCatalog::OID> allOidList;
CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::RIDList tableColRidList;
CalpontSystemCatalog::DictOIDList dictOIDList; CalpontSystemCatalog::DictOIDList dictOIDList;
execplan::CalpontSystemCatalog::ROPair roPair; execplan::CalpontSystemCatalog::ROPair roPair;
std::string processName("DDLProc"); std::string processName("DDLProc");
uint32_t processID = ::getpid();; uint32_t processID = ::getpid();
;
int32_t txnid = txnID.id; int32_t txnid = txnID.id;
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(truncTableStmt.fSessionID); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(truncTableStmt.fSessionID);
systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->identity(CalpontSystemCatalog::EC);
systemCatalogPtr->sessionID(truncTableStmt.fSessionID); systemCatalogPtr->sessionID(truncTableStmt.fSessionID);
CalpontSystemCatalog::TableInfo tableInfo; CalpontSystemCatalog::TableInfo tableInfo;
uint64_t uniqueId = 0; uint64_t uniqueId = 0;
//Bug 5070. Added exception handling // Bug 5070. Added exception handling
try try
{ {
uniqueId = fDbrm->getUnique64(); uniqueId = fDbrm->getUnique64();
@ -787,7 +795,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
catch ( ... ) catch (...)
{ {
Message::Args args; Message::Args args;
Message message(9); Message message(9);
@ -810,12 +818,12 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
try try
{ {
//check table lock // check table lock
CalpontSystemCatalog::TableName tableName; CalpontSystemCatalog::TableName tableName;
tableName.schema = truncTableStmt.fTableName->fSchema; tableName.schema = truncTableStmt.fTableName->fSchema;
tableName.table = truncTableStmt.fTableName->fName; tableName.table = truncTableStmt.fTableName->fName;
roPair = systemCatalogPtr->tableRID( tableName ); roPair = systemCatalogPtr->tableRID(tableName);
int32_t sessionId = truncTableStmt.fSessionID; int32_t sessionId = truncTableStmt.fSessionID;
std::string processName("DDLProc"); std::string processName("DDLProc");
int i = 0; int i = 0;
@ -829,14 +837,15 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
try try
{ {
tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); tableLockId =
fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); throw std::runtime_error(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
} }
if ( tableLockId == 0 ) if (tableLockId == 0)
{ {
int waitPeriod = 10; int waitPeriod = 10;
int sleepTime = 100; // sleep 100 milliseconds between checks int sleepTime = 100; // sleep 100 milliseconds between checks
@ -859,8 +868,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
{ {
abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_sec = rm_ts.tv_sec;
abs_ts.tv_nsec = rm_ts.tv_nsec; abs_ts.tv_nsec = rm_ts.tv_nsec;
} } while (nanosleep(&abs_ts, &rm_ts) < 0);
while (nanosleep(&abs_ts, &rm_ts) < 0);
#endif #endif
@ -870,7 +878,8 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
txnid = txnID.id; txnid = txnID.id;
sessionId = truncTableStmt.fSessionID; sessionId = truncTableStmt.fSessionID;
processName = "DDLProc"; processName = "DDLProc";
tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid, BRM::LOADING ); tableLockId = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, &sessionId, &txnid,
BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -881,7 +890,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
break; break;
} }
if (i >= numTries) //error out if (i >= numTries) // error out
{ {
Message::Args args; Message::Args args;
args.add(processName); args.add(processName);
@ -895,26 +904,26 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
userTableName.schema = truncTableStmt.fTableName->fSchema; userTableName.schema = truncTableStmt.fTableName->fSchema;
userTableName.table = truncTableStmt.fTableName->fName; userTableName.table = truncTableStmt.fTableName->fName;
tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); tableColRidList = systemCatalogPtr->columnRIDs(userTableName);
dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); dictOIDList = systemCatalogPtr->dictOIDs(userTableName);
for ( unsigned i = 0; i < tableColRidList.size(); i++ ) for (unsigned i = 0; i < tableColRidList.size(); i++)
{ {
if ( tableColRidList[i].objnum > 3000 ) if (tableColRidList[i].objnum > 3000)
{ {
columnOidList.push_back( tableColRidList[i].objnum ); columnOidList.push_back(tableColRidList[i].objnum);
allOidList.push_back( tableColRidList[i].objnum ); allOidList.push_back(tableColRidList[i].objnum);
} }
} }
for ( unsigned i = 0; i < dictOIDList.size(); i++ ) for (unsigned i = 0; i < dictOIDList.size(); i++)
{ {
if ( dictOIDList[i].dictOID > 3000 ) if (dictOIDList[i].dictOID > 3000)
allOidList.push_back( dictOIDList[i].dictOID ); allOidList.push_back(dictOIDList[i].dictOID);
} }
//Check whether the table has autoincrement column // Check whether the table has autoincrement column
tableInfo = systemCatalogPtr->tableInfo(userTableName); tableInfo = systemCatalogPtr->tableInfo(userTableName);
} }
catch (std::exception& ex) catch (std::exception& ex)
@ -924,7 +933,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
Message::Args args; Message::Args args;
Message message(9); Message message(9);
args.add("Truncate table failed: "); args.add("Truncate table failed: ");
args.add( ex.what() ); args.add(ex.what());
args.add(""); args.add("");
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
@ -938,7 +947,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
} }
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
@ -951,7 +960,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add("Truncate table failed: "); args.add("Truncate table failed: ");
args.add( "encountered unkown exception" ); args.add("encountered unkown exception");
args.add(""); args.add("");
try try
@ -964,17 +973,17 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
} }
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
return result; return result;
} }
//Save the oids to a file // Save the oids to a file
try try
{ {
createWriteTruncateTableLogFile( roPair.objnum, uniqueId, allOidList); createWriteTruncateTableLogFile(roPair.objnum, uniqueId, allOidList);
} }
catch (std::exception& ex) catch (std::exception& ex)
{ {
@ -984,14 +993,16 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
args.add(ex.what()); args.add(ex.what());
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
message.format( args ); message.format(args);
//@bug 4515 Release the tablelock as nothing has done to this table. //@bug 4515 Release the tablelock as nothing has done to this table.
try try
{ {
(void)fDbrm->releaseTableLock(tableLockId); (void)fDbrm->releaseTableLock(tableLockId);
} }
catch (std::exception&) {} catch (std::exception&)
{
}
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
@ -1006,8 +1017,8 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
try try
{ {
//Disable extents first // Disable extents first
int rc1 = fDbrm->markAllPartitionForDeletion( allOidList); int rc1 = fDbrm->markAllPartitionForDeletion(allOidList);
if (rc1 != 0) if (rc1 != 0)
{ {
@ -1024,11 +1035,11 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
VERBOSE_INFO("Removing files"); VERBOSE_INFO("Removing files");
bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t) allOidList.size(); bytestream << (uint32_t)allOidList.size();
for (unsigned i = 0; i < allOidList.size(); i++) for (unsigned i = 0; i < allOidList.size(); i++)
{ {
bytestream << (uint32_t) allOidList[i]; bytestream << (uint32_t)allOidList[i];
} }
uint32_t msgRecived = 0; uint32_t msgRecived = 0;
@ -1046,7 +1057,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
@ -1076,7 +1087,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
args.add(ex.what()); args.add(ex.what());
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
@ -1093,7 +1104,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
args.add(errorMsg); args.add(errorMsg);
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
@ -1101,11 +1112,11 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
return result; return result;
} }
//Drop PrimProc FD cache // Drop PrimProc FD cache
rc = cacheutils::dropPrimProcFdCache(); rc = cacheutils::dropPrimProcFdCache();
//Flush primProc cache // Flush primProc cache
rc = cacheutils::flushOIDsFromCache( allOidList ); rc = cacheutils::flushOIDsFromCache(allOidList);
//Delete extents from extent map // Delete extents from extent map
rc = fDbrm->deleteOIDs(allOidList); rc = fDbrm->deleteOIDs(allOidList);
if (rc != 0) if (rc != 0)
@ -1113,10 +1124,10 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add("Table truncated with warning "); args.add("Table truncated with warning ");
args.add( "Remove from extent map failed." ); args.add("Remove from extent map failed.");
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = WARNING; result.result = WARNING;
result.message = message; result.message = message;
@ -1125,18 +1136,18 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
return result; return result;
} }
//Get the number of tables in the database, the current table is included. // Get the number of tables in the database, the current table is included.
int tableCount = systemCatalogPtr->getTableCount(); int tableCount = systemCatalogPtr->getTableCount();
Oam oam; Oam oam;
//Calculate which dbroot the columns should start // Calculate which dbroot the columns should start
DBRootConfigList dbRootList = oamcache->getDBRootNums(); DBRootConfigList dbRootList = oamcache->getDBRootNums();
uint16_t useDBRootIndex = tableCount % dbRootList.size(); uint16_t useDBRootIndex = tableCount % dbRootList.size();
//Find out the dbroot# corresponding the useDBRootIndex from oam // Find out the dbroot# corresponding the useDBRootIndex from oam
uint16_t useDBRoot = dbRootList[useDBRootIndex]; uint16_t useDBRoot = dbRootList[useDBRootIndex];
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte) WE_SVR_WRITE_CREATETABLEFILES; bytestream << (ByteStream::byte)WE_SVR_WRITE_CREATETABLEFILES;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t)txnID.id; bytestream << (uint32_t)txnID.id;
uint32_t numOids = columnOidList.size() + dictOIDList.size(); uint32_t numOids = columnOidList.size() + dictOIDList.size();
@ -1151,22 +1162,22 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
autoIncColOid = colType.columnOID; autoIncColOid = colType.columnOID;
bytestream << (uint32_t)columnOidList[col]; bytestream << (uint32_t)columnOidList[col];
bytestream << (uint8_t) colType.colDataType; bytestream << (uint8_t)colType.colDataType;
bytestream << (uint8_t) false; bytestream << (uint8_t) false;
bytestream << (uint32_t) colType.colWidth; bytestream << (uint32_t)colType.colWidth;
bytestream << (uint16_t) useDBRoot; bytestream << (uint16_t)useDBRoot;
bytestream << (uint32_t) colType.compressionType; bytestream << (uint32_t)colType.compressionType;
} }
for (unsigned col = 0; col < dictOIDList.size(); col++) for (unsigned col = 0; col < dictOIDList.size(); col++)
{ {
colType = systemCatalogPtr->colTypeDct(dictOIDList[col].dictOID); colType = systemCatalogPtr->colTypeDct(dictOIDList[col].dictOID);
bytestream << (uint32_t) dictOIDList[col].dictOID; bytestream << (uint32_t)dictOIDList[col].dictOID;
bytestream << (uint8_t) colType.colDataType; bytestream << (uint8_t)colType.colDataType;
bytestream << (uint8_t) true; bytestream << (uint8_t) true;
bytestream << (uint32_t) colType.colWidth; bytestream << (uint32_t)colType.colWidth;
bytestream << (uint16_t) useDBRoot; bytestream << (uint16_t)useDBRoot;
bytestream << (uint32_t) colType.compressionType; bytestream << (uint32_t)colType.compressionType;
} }
boost::shared_ptr<std::map<int, int> > dbRootPMMap = oamcache->getDBRootToPMMap(); boost::shared_ptr<std::map<int, int> > dbRootPMMap = oamcache->getDBRootToPMMap();
@ -1184,7 +1195,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
rc = NETWORK_ERROR; rc = NETWORK_ERROR;
errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES"; errorMsg = "Lost connection to Write Engine Server while updating SYSTABLES";
@ -1206,9 +1217,9 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
if (rc != 0) if (rc != 0)
{ {
//drop the newly created files // drop the newly created files
bytestream.restart(); bytestream.restart();
bytestream << (ByteStream::byte) WE_SVR_WRITE_DROPFILES; bytestream << (ByteStream::byte)WE_SVR_WRITE_DROPFILES;
bytestream << uniqueId; bytestream << uniqueId;
bytestream << (uint32_t)(allOidList.size()); bytestream << (uint32_t)(allOidList.size());
@ -1224,28 +1235,29 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
bsIn.reset(new ByteStream()); bsIn.reset(new ByteStream());
fWEClient->read(uniqueId, bsIn); fWEClient->read(uniqueId, bsIn);
if ( bsIn->length() == 0 ) //read error if (bsIn->length() == 0) // read error
{ {
break; break;
} }
else else
{ {
*bsIn >> tmp8; *bsIn >> tmp8;
//rc = tmp8; // rc = tmp8;
break; break;
} }
} }
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add( "Truncate table failed." ); args.add("Truncate table failed.");
args.add( errorMsg); args.add(errorMsg);
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
//rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); // rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID,
// processName, false );
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
@ -1260,7 +1272,7 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
#ifdef _MSC_VER #ifdef _MSC_VER
catch (std::exception&) catch (std::exception&)
{ {
//FIXME: Windows can't delete a file that's still open by another process // FIXME: Windows can't delete a file that's still open by another process
} }
#else #else
@ -1268,46 +1280,48 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
{ {
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add( "Truncate table failed." ); args.add("Truncate table failed.");
args.add( ex.what() ); args.add(ex.what());
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
//rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); // rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName,
// false );
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
#endif #endif
catch ( ... ) catch (...)
{ {
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add("Truncate table failed: "); args.add("Truncate table failed: ");
args.add( "Remove column files failed." ); args.add("Remove column files failed.");
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = TRUNC_ERROR; result.result = TRUNC_ERROR;
result.message = message; result.message = message;
//rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName, false ); // rc = fSessionManager.setTableLock( roPair.objnum, truncTableStmt.fSessionID, processID, processName,
// false );
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
return result; return result;
} }
if (rc != 0) if (rc != 0)
{ {
rollBackTransaction( uniqueId, txnID, truncTableStmt.fSessionID); //What to do with the error code rollBackTransaction(uniqueId, txnID, truncTableStmt.fSessionID); // What to do with the error code
fSessionManager.rolledback(txnID); fSessionManager.rolledback(txnID);
} }
//Check whether the table has autoincrement column // Check whether the table has autoincrement column
if (tableInfo.tablewithautoincr == 1) if (tableInfo.tablewithautoincr == 1)
{ {
//reset nextvalue to 1 // reset nextvalue to 1
WE_DDLCommandClient commandClient; WE_DDLCommandClient commandClient;
rc = commandClient.UpdateSyscolumnNextval(autoIncColOid, 1); rc = commandClient.UpdateSyscolumnNextval(autoIncColOid, 1);
} }
@ -1324,10 +1338,10 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
Message::Args args; Message::Args args;
Message message(1); Message message(1);
args.add("Table truncated with warning "); args.add("Table truncated with warning ");
args.add( "Release table failed." ); args.add("Release table failed.");
args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); args.add(IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE));
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = WARNING; result.result = WARNING;
result.message = message; result.message = message;
@ -1335,23 +1349,22 @@ TruncTableProcessor::DDLResult TruncTableProcessor::processPackage(ddlpackage::T
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
} }
//release the transaction // release the transaction
fSessionManager.committed(txnID); fSessionManager.committed(txnID);
fWEClient->removeQueue(uniqueId); fWEClient->removeQueue(uniqueId);
//Remove the log file // Remove the log file
try try
{ {
deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId); deleteLogFile(TRUNCATE_LOG, roPair.objnum, uniqueId);
} }
catch ( ... ) catch (...)
{ {
} }
return result; return result;
} }
} //namespace ddlpackageprocessor } // namespace ddlpackageprocessor
// vim:ts=4 sw=4: // vim:ts=4 sw=4:

View File

@ -39,18 +39,18 @@ namespace ddlpackageprocessor
*/ */
class DropTableProcessor : public DDLPackageProcessor class DropTableProcessor : public DDLPackageProcessor
{ {
public: public:
DropTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} DropTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
{
}
/** @brief process a drop table statement /** @brief process a drop table statement
* *
* @param dropTableStmt the drop table statement * @param dropTableStmt the drop table statement
*/ */
EXPORT DDLResult processPackage(ddlpackage::DropTableStatement& dropTableStmt); EXPORT DDLResult processPackage(ddlpackage::DropTableStatement& dropTableStmt);
protected: protected:
private:
private:
}; };
/** @brief specialization of a DDLPacakageProcessor /** @brief specialization of a DDLPacakageProcessor
@ -59,21 +59,20 @@ private:
*/ */
class TruncTableProcessor : public DDLPackageProcessor class TruncTableProcessor : public DDLPackageProcessor
{ {
public: public:
TruncTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} TruncTableProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
{
}
/** @brief process a truncate table statement /** @brief process a truncate table statement
* *
* @param truncTableStmt the truncate table statement * @param truncTableStmt the truncate table statement
*/ */
EXPORT DDLResult processPackage(ddlpackage::TruncTableStatement& truncTableStmt); EXPORT DDLResult processPackage(ddlpackage::TruncTableStatement& truncTableStmt);
protected: protected:
private:
private:
}; };
} // namespace ddlpackageprocessor } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT

View File

@ -34,8 +34,8 @@ using namespace oam;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(
MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpackage::MarkPartitionStatement& markPartitionStmt) ddlpackage::MarkPartitionStatement& markPartitionStmt)
{ {
SUMMARY_INFO("RestorePartitionProcessor::processPackage"); SUMMARY_INFO("RestorePartitionProcessor::processPackage");
@ -51,7 +51,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
int rc = 0; int rc = 0;
rc = fDbrm->isReadWrite(); rc = fDbrm->isReadWrite();
if (rc != 0 ) if (rc != 0)
{ {
logging::Message::Args args; logging::Message::Args args;
logging::Message message(9); logging::Message message(9);
@ -63,7 +63,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
return result; return result;
} }
std::vector <CalpontSystemCatalog::OID> oidList; std::vector<CalpontSystemCatalog::OID> oidList;
CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::RIDList tableColRidList;
CalpontSystemCatalog::DictOIDList dictOIDList; CalpontSystemCatalog::DictOIDList dictOIDList;
std::string processName("DDLProc"); std::string processName("DDLProc");
@ -78,17 +78,18 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
try try
{ {
//check table lock // check table lock
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(markPartitionStmt.fSessionID); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(markPartitionStmt.fSessionID);
systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->identity(CalpontSystemCatalog::EC);
systemCatalogPtr->sessionID(markPartitionStmt.fSessionID); systemCatalogPtr->sessionID(markPartitionStmt.fSessionID);
CalpontSystemCatalog::TableName tableName; CalpontSystemCatalog::TableName tableName;
tableName.schema = markPartitionStmt.fTableName->fSchema; tableName.schema = markPartitionStmt.fTableName->fSchema;
tableName.table = markPartitionStmt.fTableName->fName; tableName.table = markPartitionStmt.fTableName->fName;
roPair = systemCatalogPtr->tableRID( tableName ); roPair = systemCatalogPtr->tableRID(tableName);
//@Bug 3054 check for system catalog //@Bug 3054 check for system catalog
if ( roPair.objnum < 3000 ) if (roPair.objnum < 3000)
{ {
throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog."); throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog.");
} }
@ -106,7 +107,8 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
try try
{ {
uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID,
(int32_t*)&txnID.id, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -116,7 +118,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
return result; return result;
} }
if ( uniqueID == 0 ) if (uniqueID == 0)
{ {
int waitPeriod = 10; int waitPeriod = 10;
int sleepTime = 100; // sleep 100 milliseconds between checks int sleepTime = 100; // sleep 100 milliseconds between checks
@ -139,8 +141,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
{ {
abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_sec = rm_ts.tv_sec;
abs_ts.tv_nsec = rm_ts.tv_nsec; abs_ts.tv_nsec = rm_ts.tv_nsec;
} } while (nanosleep(&abs_ts, &rm_ts) < 0);
while (nanosleep(&abs_ts, &rm_ts) < 0);
#endif #endif
// reset // reset
@ -152,7 +153,8 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
try try
{ {
uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID,
(int32_t*)&txnID.id, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -166,7 +168,7 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
break; break;
} }
if (i >= numTries) //error out if (i >= numTries) // error out
{ {
result.result = DROP_ERROR; result.result = DROP_ERROR;
logging::Message::Args args; logging::Message::Args args;
@ -190,28 +192,28 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
userTableName.schema = markPartitionStmt.fTableName->fSchema; userTableName.schema = markPartitionStmt.fTableName->fSchema;
userTableName.table = markPartitionStmt.fTableName->fName; userTableName.table = markPartitionStmt.fTableName->fName;
tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); tableColRidList = systemCatalogPtr->columnRIDs(userTableName);
dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); dictOIDList = systemCatalogPtr->dictOIDs(userTableName);
//Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format // Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format
for ( unsigned i = 0; i < tableColRidList.size(); i++ ) for (unsigned i = 0; i < tableColRidList.size(); i++)
{ {
if ( tableColRidList[i].objnum > 3000 ) if (tableColRidList[i].objnum > 3000)
oidList.push_back( tableColRidList[i].objnum ); oidList.push_back(tableColRidList[i].objnum);
} }
for ( unsigned i = 0; i < dictOIDList.size(); i++ ) for (unsigned i = 0; i < dictOIDList.size(); i++)
{ {
if ( dictOIDList[i].dictOID > 3000 ) if (dictOIDList[i].dictOID > 3000)
oidList.push_back( dictOIDList[i].dictOID ); oidList.push_back(dictOIDList[i].dictOID);
} }
//Remove the partition from extent map // Remove the partition from extent map
string emsg; string emsg;
rc = fDbrm->markPartitionForDeletion( oidList, markPartitionStmt.fPartitions, emsg); rc = fDbrm->markPartitionForDeletion(oidList, markPartitionStmt.fPartitions, emsg);
if ( rc != 0 ) if (rc != 0)
{ {
throw std::runtime_error(emsg); throw std::runtime_error(emsg);
} }
@ -248,15 +250,15 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
} }
catch (...) catch (...)
{ {
//cerr << "MarkPartitionProcessor::processPackage: caught unknown exception!" << endl; // cerr << "MarkPartitionProcessor::processPackage: caught unknown exception!" << endl;
logging::Message::Args args; logging::Message::Args args;
logging::Message message(1); logging::Message message(1);
args.add("Disable partition failed: "); args.add("Disable partition failed: ");
args.add( "encountered unkown exception" ); args.add("encountered unkown exception");
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = DROP_ERROR; result.result = DROP_ERROR;
result.message = message; result.message = message;
@ -294,4 +296,4 @@ MarkPartitionProcessor::DDLResult MarkPartitionProcessor::processPackage(ddlpack
return result; return result;
} }
} } // namespace ddlpackageprocessor

View File

@ -33,29 +33,26 @@
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
/** @brief specialization of a DDLPackageProcessor /** @brief specialization of a DDLPackageProcessor
* for interacting with the Write Engine * for interacting with the Write Engine
* to process create table ddl statements. * to process create table ddl statements.
*/ */
class MarkPartitionProcessor : public DDLPackageProcessor class MarkPartitionProcessor : public DDLPackageProcessor
{ {
public: public:
MarkPartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} MarkPartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
{
}
/** @brief process a create table statement /** @brief process a create table statement
* *
* @param createTableStmt the CreateTableStatement * @param createTableStmt the CreateTableStatement
*/ */
EXPORT DDLResult processPackage(ddlpackage::MarkPartitionStatement& MarkPartitionStmt); EXPORT DDLResult processPackage(ddlpackage::MarkPartitionStatement& MarkPartitionStmt);
protected: protected:
private:
private:
}; };
} // namespace ddlpackageprocessor } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT

View File

@ -60,9 +60,10 @@ using namespace joblist;
class PopulateIndexTest class PopulateIndexTest
{ {
public: public:
PopulateIndexTest(DistributedEngineComm* ec) : fEC(ec)
PopulateIndexTest(DistributedEngineComm* ec) : fEC(ec) { } {
}
DistributedEngineComm* fEC; DistributedEngineComm* fEC;
void test_createindex() void test_createindex()
@ -79,7 +80,8 @@ public:
const ParseTree& ptree = parser.GetParseTree(); const ParseTree& ptree = parser.GetParseTree();
cout << "Parser succeeded." << endl; cout << "Parser succeeded." << endl;
cout << ptree.fList.size() << " " << "SQL statements" << endl; cout << ptree.fList.size() << " "
<< "SQL statements" << endl;
cout << ptree.fSqlText << endl; cout << ptree.fSqlText << endl;
try try
@ -152,7 +154,8 @@ public:
processor.setDebugLevel(CreateIndexProcessor::VERBOSE); processor.setDebugLevel(CreateIndexProcessor::VERBOSE);
SqlStatement& stmt = *ptree.fList[0]; SqlStatement& stmt = *ptree.fList[0];
CreateIndexProcessor::DDLResult result = processor.processPackage(dynamic_cast<CreateIndexStatement&>(stmt)); CreateIndexProcessor::DDLResult result =
processor.processPackage(dynamic_cast<CreateIndexStatement&>(stmt));
std::cout << "return: " << result.result << std::endl; std::cout << "return: " << result.result << std::endl;
} }
catch (...) catch (...)
@ -162,7 +165,6 @@ public:
} }
} }
void test_createtabletest(const string& sqlbuf) void test_createtabletest(const string& sqlbuf)
{ {
cout << "Begining create table test: " << sqlbuf << endl; cout << "Begining create table test: " << sqlbuf << endl;
@ -225,7 +227,7 @@ public:
void test_altertable_addtablenullconstraint() void test_altertable_addtablenullconstraint()
{ {
//sql syntax error? (Does not build index test.) // sql syntax error? (Does not build index test.)
cout << "Begining Alter Table add table not null constraint test ... " << endl; cout << "Begining Alter Table add table not null constraint test ... " << endl;
std::string sqlbuf = "ALTER TABLE tpch.region add CONSTRAINT not null(r_regionkey);"; std::string sqlbuf = "ALTER TABLE tpch.region add CONSTRAINT not null(r_regionkey);";
cout << sqlbuf << endl; cout << sqlbuf << endl;
@ -255,12 +257,9 @@ public:
} }
} }
} }
}; };
int main(int argc, char** argv)
int main( int argc, char** argv)
{ {
int DoAll = 0; int DoAll = 0;
int Do1 = 0; int Do1 = 0;
@ -309,45 +308,80 @@ int main( int argc, char** argv)
if (argc > 1) if (argc > 1)
{ {
if (strcmp(argv[1], "All") == 0) DoAll = 1; if (strcmp(argv[1], "All") == 0)
else if (strcmp(argv[1], "t1") == 0) Do1 = 1; DoAll = 1;
else if (strcmp(argv[1], "t2") == 0) Do2 = 1; else if (strcmp(argv[1], "t1") == 0)
else if (strcmp(argv[1], "t3") == 0) Do3 = 1; Do1 = 1;
else if (strcmp(argv[1], "t4") == 0) Do4 = 1; else if (strcmp(argv[1], "t2") == 0)
else if (strcmp(argv[1], "t5") == 0) Do5 = 1; Do2 = 1;
else if (strcmp(argv[1], "t6") == 0) Do6 = 1; else if (strcmp(argv[1], "t3") == 0)
else if (strcmp(argv[1], "t7") == 0) Do7 = 1; Do3 = 1;
else if (strcmp(argv[1], "t8") == 0) Do8 = 1; else if (strcmp(argv[1], "t4") == 0)
else if (strcmp(argv[1], "t9") == 0) Do9 = 1; Do4 = 1;
else if (strcmp(argv[1], "t10") == 0) Do10 = 1; else if (strcmp(argv[1], "t5") == 0)
else if (strcmp(argv[1], "t11") == 0) Do11 = 1; Do5 = 1;
else if (strcmp(argv[1], "t12") == 0) Do12 = 1; else if (strcmp(argv[1], "t6") == 0)
else if (strcmp(argv[1], "t13") == 0) Do13 = 1; Do6 = 1;
else if (strcmp(argv[1], "t14") == 0) Do14 = 1; else if (strcmp(argv[1], "t7") == 0)
else if (strcmp(argv[1], "t15") == 0) Do15 = 1; Do7 = 1;
else if (strcmp(argv[1], "t16") == 0) Do16 = 1; else if (strcmp(argv[1], "t8") == 0)
else if (strcmp(argv[1], "t17") == 0) Do17 = 1; Do8 = 1;
else if (strcmp(argv[1], "t18") == 0) Do18 = 1; else if (strcmp(argv[1], "t9") == 0)
else if (strcmp(argv[1], "t19") == 0) Do19 = 1; Do9 = 1;
else if (strcmp(argv[1], "t20") == 0) Do20 = 1; else if (strcmp(argv[1], "t10") == 0)
else if (strcmp(argv[1], "t21") == 0) Do21 = 1; Do10 = 1;
else if (strcmp(argv[1], "t22") == 0) Do22 = 1; else if (strcmp(argv[1], "t11") == 0)
else if (strcmp(argv[1], "t23") == 0) Do23 = 1; Do11 = 1;
else if (strcmp(argv[1], "t24") == 0) Do24 = 1; else if (strcmp(argv[1], "t12") == 0)
else if (strcmp(argv[1], "t25") == 0) Do25 = 1; Do12 = 1;
else if (strcmp(argv[1], "t26") == 0) Do26 = 1; else if (strcmp(argv[1], "t13") == 0)
else if (strcmp(argv[1], "t27") == 0) Do27 = 1; Do13 = 1;
else if (strcmp(argv[1], "t28") == 0) Do28 = 1; else if (strcmp(argv[1], "t14") == 0)
else if (strcmp(argv[1], "t29") == 0) Do29 = 1; Do14 = 1;
else if (strcmp(argv[1], "t30") == 0) Do30 = 1; else if (strcmp(argv[1], "t15") == 0)
else if (strcmp(argv[1], "t31") == 0) Do31 = 1; Do15 = 1;
else if (strcmp(argv[1], "t32") == 0) Do32 = 1; else if (strcmp(argv[1], "t16") == 0)
else if (strcmp(argv[1], "t33") == 0) Do33 = 1; Do16 = 1;
else if (strcmp(argv[1], "t34") == 0) Do34 = 1; else if (strcmp(argv[1], "t17") == 0)
else if (strcmp(argv[1], "t35") == 0) Do35 = 1; Do17 = 1;
else if (strcmp(argv[1], "t36") == 0) Do35 = 1; else if (strcmp(argv[1], "t18") == 0)
Do18 = 1;
else if (strcmp(argv[1], "t19") == 0)
Do19 = 1;
else if (strcmp(argv[1], "t20") == 0)
Do20 = 1;
else if (strcmp(argv[1], "t21") == 0)
Do21 = 1;
else if (strcmp(argv[1], "t22") == 0)
Do22 = 1;
else if (strcmp(argv[1], "t23") == 0)
Do23 = 1;
else if (strcmp(argv[1], "t24") == 0)
Do24 = 1;
else if (strcmp(argv[1], "t25") == 0)
Do25 = 1;
else if (strcmp(argv[1], "t26") == 0)
Do26 = 1;
else if (strcmp(argv[1], "t27") == 0)
Do27 = 1;
else if (strcmp(argv[1], "t28") == 0)
Do28 = 1;
else if (strcmp(argv[1], "t29") == 0)
Do29 = 1;
else if (strcmp(argv[1], "t30") == 0)
Do30 = 1;
else if (strcmp(argv[1], "t31") == 0)
Do31 = 1;
else if (strcmp(argv[1], "t32") == 0)
Do32 = 1;
else if (strcmp(argv[1], "t33") == 0)
Do33 = 1;
else if (strcmp(argv[1], "t34") == 0)
Do34 = 1;
else if (strcmp(argv[1], "t35") == 0)
Do35 = 1;
else if (strcmp(argv[1], "t36") == 0)
Do35 = 1;
} }
PopulateIndexTest pit(DistributedEngineComm::instance()); PopulateIndexTest pit(DistributedEngineComm::instance());
@ -508,13 +542,15 @@ int main( int argc, char** argv)
} }
else if (Do24) else if (Do24)
{ {
std::string sql("CREATE INDEX multi_cust_idx ON tpch.customer (c_name, c_address, c_phone, c_mktsegment)"); std::string sql(
"CREATE INDEX multi_cust_idx ON tpch.customer (c_name, c_address, c_phone, c_mktsegment)");
pit.test_createindextest(sql); pit.test_createindextest(sql);
cout << "Finished add table index test: " << sql << endl; cout << "Finished add table index test: " << sql << endl;
} }
else if (Do25) else if (Do25)
{ {
std::string sql("CREATE INDEX multi_part_no_idx ON tpch.part (p_name, p_mfgr, p_brand, p_container, p_size)"); std::string sql(
"CREATE INDEX multi_part_no_idx ON tpch.part (p_name, p_mfgr, p_brand, p_container, p_size)");
pit.test_createindextest(sql); pit.test_createindextest(sql);
cout << "Finished add table index test: " << sql << endl; cout << "Finished add table index test: " << sql << endl;
} }
@ -537,7 +573,6 @@ int main( int argc, char** argv)
std::string sqlbuf = "ALTER TABLE tpch.tablea add CONSTRAINT tablea_cstr1 unique(c2);"; std::string sqlbuf = "ALTER TABLE tpch.tablea add CONSTRAINT tablea_cstr1 unique(c2);";
pit.test_altertable_addtableconstraint(sqlbuf); pit.test_altertable_addtableconstraint(sqlbuf);
cout << "Finished add table constraint test" << endl; cout << "Finished add table constraint test" << endl;
} }
else if (Do29) else if (Do29)
{ {
@ -600,7 +635,4 @@ int main( int argc, char** argv)
} }
cout << "Create index test took :" << theTimer.elapsed() << " seconds to complete." << endl; cout << "Create index test took :" << theTimer.elapsed() << " seconds to complete." << endl;
} }

View File

@ -34,8 +34,8 @@ using namespace WriteEngine;
namespace ddlpackageprocessor namespace ddlpackageprocessor
{ {
RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(
RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(ddlpackage::RestorePartitionStatement& restorePartitionStmt) ddlpackage::RestorePartitionStatement& restorePartitionStmt)
{ {
SUMMARY_INFO("RestorePartitionProcessor::processPackage"); SUMMARY_INFO("RestorePartitionProcessor::processPackage");
@ -51,7 +51,7 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
int rc = 0; int rc = 0;
rc = fDbrm->isReadWrite(); rc = fDbrm->isReadWrite();
if (rc != 0 ) if (rc != 0)
{ {
logging::Message::Args args; logging::Message::Args args;
logging::Message message(9); logging::Message message(9);
@ -63,7 +63,7 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
return result; return result;
} }
std::vector <CalpontSystemCatalog::OID> oidList; std::vector<CalpontSystemCatalog::OID> oidList;
CalpontSystemCatalog::RIDList tableColRidList; CalpontSystemCatalog::RIDList tableColRidList;
CalpontSystemCatalog::DictOIDList dictOIDList; CalpontSystemCatalog::DictOIDList dictOIDList;
std::string processName("DDLProc"); std::string processName("DDLProc");
@ -78,17 +78,18 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
try try
{ {
//check table lock // check table lock
boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr = CalpontSystemCatalog::makeCalpontSystemCatalog(restorePartitionStmt.fSessionID); boost::shared_ptr<CalpontSystemCatalog> systemCatalogPtr =
CalpontSystemCatalog::makeCalpontSystemCatalog(restorePartitionStmt.fSessionID);
systemCatalogPtr->identity(CalpontSystemCatalog::EC); systemCatalogPtr->identity(CalpontSystemCatalog::EC);
systemCatalogPtr->sessionID(restorePartitionStmt.fSessionID); systemCatalogPtr->sessionID(restorePartitionStmt.fSessionID);
CalpontSystemCatalog::TableName tableName; CalpontSystemCatalog::TableName tableName;
tableName.schema = restorePartitionStmt.fTableName->fSchema; tableName.schema = restorePartitionStmt.fTableName->fSchema;
tableName.table = restorePartitionStmt.fTableName->fName; tableName.table = restorePartitionStmt.fTableName->fName;
roPair = systemCatalogPtr->tableRID( tableName ); roPair = systemCatalogPtr->tableRID(tableName);
//@Bug 3054 check for system catalog //@Bug 3054 check for system catalog
if ( roPair.objnum < 3000 ) if (roPair.objnum < 3000)
{ {
throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog."); throw std::runtime_error("Drop partition cannot be operated on Calpont system catalog.");
} }
@ -106,7 +107,8 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
try try
{ {
uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID,
(int32_t*)&txnID.id, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -116,7 +118,7 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
return result; return result;
} }
if ( uniqueID == 0 ) if (uniqueID == 0)
{ {
int waitPeriod = 10; int waitPeriod = 10;
int sleepTime = 100; // sleep 100 milliseconds between checks int sleepTime = 100; // sleep 100 milliseconds between checks
@ -139,8 +141,7 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
{ {
abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_sec = rm_ts.tv_sec;
abs_ts.tv_nsec = rm_ts.tv_nsec; abs_ts.tv_nsec = rm_ts.tv_nsec;
} } while (nanosleep(&abs_ts, &rm_ts) < 0);
while (nanosleep(&abs_ts, &rm_ts) < 0);
#endif #endif
// reset // reset
@ -152,7 +153,8 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
try try
{ {
uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID, (int32_t*)&txnID.id, BRM::LOADING ); uniqueID = fDbrm->getTableLock(pms, roPair.objnum, &processName, &processID, (int32_t*)&sessionID,
(int32_t*)&txnID.id, BRM::LOADING);
} }
catch (std::exception&) catch (std::exception&)
{ {
@ -166,7 +168,7 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
break; break;
} }
if (i >= numTries) //error out if (i >= numTries) // error out
{ {
result.result = DROP_ERROR; result.result = DROP_ERROR;
logging::Message::Args args; logging::Message::Args args;
@ -192,28 +194,28 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
userTableName.schema = restorePartitionStmt.fTableName->fSchema; userTableName.schema = restorePartitionStmt.fTableName->fSchema;
userTableName.table = restorePartitionStmt.fTableName->fName; userTableName.table = restorePartitionStmt.fTableName->fName;
tableColRidList = systemCatalogPtr->columnRIDs( userTableName ); tableColRidList = systemCatalogPtr->columnRIDs(userTableName);
dictOIDList = systemCatalogPtr->dictOIDs( userTableName ); dictOIDList = systemCatalogPtr->dictOIDs(userTableName);
//Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format // Save qualified tablename, all column, dictionary OIDs, and transaction ID into a file in ASCII format
for ( unsigned i = 0; i < tableColRidList.size(); i++ ) for (unsigned i = 0; i < tableColRidList.size(); i++)
{ {
if ( tableColRidList[i].objnum > 3000 ) if (tableColRidList[i].objnum > 3000)
oidList.push_back( tableColRidList[i].objnum ); oidList.push_back(tableColRidList[i].objnum);
} }
for ( unsigned i = 0; i < dictOIDList.size(); i++ ) for (unsigned i = 0; i < dictOIDList.size(); i++)
{ {
if ( dictOIDList[i].dictOID > 3000 ) if (dictOIDList[i].dictOID > 3000)
oidList.push_back( dictOIDList[i].dictOID ); oidList.push_back(dictOIDList[i].dictOID);
} }
//Remove the partition from extent map // Remove the partition from extent map
string emsg; string emsg;
rc = fDbrm->restorePartition( oidList, restorePartitionStmt.fPartitions, emsg); rc = fDbrm->restorePartition(oidList, restorePartitionStmt.fPartitions, emsg);
if ( rc != 0 ) if (rc != 0)
{ {
throw std::runtime_error(emsg); throw std::runtime_error(emsg);
} }
@ -223,7 +225,7 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
logging::Message::Args args; logging::Message::Args args;
logging::Message message(ex.what()); logging::Message message(ex.what());
if (( rc == BRM::ERR_NOT_EXIST_PARTITION) || (rc == BRM::ERR_INVALID_OP_LAST_PARTITION) || if ((rc == BRM::ERR_NOT_EXIST_PARTITION) || (rc == BRM::ERR_INVALID_OP_LAST_PARTITION) ||
(rc == BRM::ERR_PARTITION_DISABLED) || (rc == BRM::ERR_TABLE_NOT_LOCKED)) (rc == BRM::ERR_PARTITION_DISABLED) || (rc == BRM::ERR_TABLE_NOT_LOCKED))
result.result = USER_ERROR; result.result = USER_ERROR;
else if (rc == BRM::ERR_PARTITION_ENABLED) else if (rc == BRM::ERR_PARTITION_ENABLED)
@ -248,15 +250,15 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
} }
catch (...) catch (...)
{ {
//cerr << "RestorePartitionProcessor::processPackage: caught unknown exception!" << endl; // cerr << "RestorePartitionProcessor::processPackage: caught unknown exception!" << endl;
logging::Message::Args args; logging::Message::Args args;
logging::Message message(1); logging::Message message(1);
args.add("Enable partition: "); args.add("Enable partition: ");
args.add( "encountered unkown exception" ); args.add("encountered unkown exception");
args.add(""); args.add("");
args.add(""); args.add("");
message.format( args ); message.format(args);
result.result = DROP_ERROR; result.result = DROP_ERROR;
result.message = message; result.message = message;
@ -276,7 +278,8 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
} }
// Log the DDL statement // Log the DDL statement
logging::logDDL(restorePartitionStmt.fSessionID, txnID.id, restorePartitionStmt.fSql, restorePartitionStmt.fOwner); logging::logDDL(restorePartitionStmt.fSessionID, txnID.id, restorePartitionStmt.fSql,
restorePartitionStmt.fOwner);
try try
{ {
@ -293,4 +296,4 @@ RestorePartitionProcessor::DDLResult RestorePartitionProcessor::processPackage(d
fSessionManager.committed(txnID); fSessionManager.committed(txnID);
return result; return result;
} }
} } // namespace ddlpackageprocessor

View File

@ -39,20 +39,19 @@ namespace ddlpackageprocessor
*/ */
class RestorePartitionProcessor : public DDLPackageProcessor class RestorePartitionProcessor : public DDLPackageProcessor
{ {
public: public:
RestorePartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm) {} RestorePartitionProcessor(BRM::DBRM* aDbrm) : DDLPackageProcessor(aDbrm)
{
}
/** @brief process a drop table statement /** @brief process a drop table statement
* *
* @param dropTableStmt the drop table statement * @param dropTableStmt the drop table statement
*/ */
EXPORT DDLResult processPackage(ddlpackage::RestorePartitionStatement& RestorePartitionStmt); EXPORT DDLResult processPackage(ddlpackage::RestorePartitionStatement& RestorePartitionStmt);
protected: protected:
private:
private:
}; };
} // namespace ddlpackageprocessor } // namespace ddlpackageprocessor
#undef EXPORT #undef EXPORT

View File

@ -55,7 +55,7 @@ using namespace WriteEngine;
#include "messagelog.h" #include "messagelog.h"
class SystemCatalogBuilder class SystemCatalogBuilder
{ {
public: public:
static void build() static void build()
{ {
ColumnOp colOp; ColumnOp colOp;
@ -66,342 +66,341 @@ public:
remove(); remove();
colOp.initColumn( curCol ); colOp.initColumn(curCol);
// SYSTABLE // SYSTABLE
cout << "Creating System Catalog..." << endl; cout << "Creating System Catalog..." << endl;
// TableName // TableName
rc = colOp.createColumn( curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1001 ); rc = colOp.createColumn(curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1001);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2001, 2002, 2003); rc = fWriteEngine.createStore(txnID, 2001, 2002, 2003);
// Schema // Schema
rc = colOp.createColumn( curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1002 ); rc = colOp.createColumn(curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1002);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2004, 2005, 2006); rc = fWriteEngine.createStore(txnID, 2004, 2005, 2006);
// CreateDate // CreateDate
rc = colOp.createColumn( curCol, 2, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1003 ); rc = colOp.createColumn(curCol, 2, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1003);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// LastUpdateDate // LastUpdateDate
rc = colOp.createColumn( curCol, 3, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1004 ); rc = colOp.createColumn(curCol, 3, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1004);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// INIT // INIT
rc = colOp.createColumn( curCol, 4, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1005 ); rc = colOp.createColumn(curCol, 4, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1005);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// NEXT // NEXT
rc = colOp.createColumn( curCol, 5, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1006 ); rc = colOp.createColumn(curCol, 5, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1006);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
//SYSCOLUMN // SYSCOLUMN
// Shema // Shema
rc = colOp.createColumn( curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1007 ); rc = colOp.createColumn(curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1007);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2007, 2008, 2009); rc = fWriteEngine.createStore(txnID, 2007, 2008, 2009);
// TableName // TableName
rc = colOp.createColumn( curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1008 ); rc = colOp.createColumn(curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1008);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2010, 2011, 2012); rc = fWriteEngine.createStore(txnID, 2010, 2011, 2012);
// ColumnName // ColumnName
rc = colOp.createColumn( curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1009 ); rc = colOp.createColumn(curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1009);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2013, 2014, 2015); rc = fWriteEngine.createStore(txnID, 2013, 2014, 2015);
// ObjectID // ObjectID
rc = colOp.createColumn( curCol, 3, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1010 ); rc = colOp.createColumn(curCol, 3, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1010);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// DictOID // DictOID
rc = colOp.createColumn( curCol, 4, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1011 ); rc = colOp.createColumn(curCol, 4, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1011);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// ListOID // ListOID
rc = colOp.createColumn( curCol, 5, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1012 ); rc = colOp.createColumn(curCol, 5, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1012);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// TreeOID // TreeOID
rc = colOp.createColumn( curCol, 6, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1013 ); rc = colOp.createColumn(curCol, 6, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1013);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// DataType // DataType
rc = colOp.createColumn( curCol, 7, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1014 ); rc = colOp.createColumn(curCol, 7, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1014);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// ColumnLength // ColumnLength
rc = colOp.createColumn( curCol, 8, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1015 ); rc = colOp.createColumn(curCol, 8, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1015);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// ColumnPos // ColumnPos
rc = colOp.createColumn( curCol, 9, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1016 ); rc = colOp.createColumn(curCol, 9, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1016);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// LastUpdate // LastUpdate
rc = colOp.createColumn( curCol, 10, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1017 ); rc = colOp.createColumn(curCol, 10, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1017);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// DefaultValue // DefaultValue
rc = colOp.createColumn( curCol, 11, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1018 ); rc = colOp.createColumn(curCol, 11, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1018);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2016, 2017, 2018); rc = fWriteEngine.createStore(txnID, 2016, 2017, 2018);
// Nullable // Nullable
rc = colOp.createColumn( curCol, 12, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1019 ); rc = colOp.createColumn(curCol, 12, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1019);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// Scale // Scale
rc = colOp.createColumn( curCol, 13, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1020 ); rc = colOp.createColumn(curCol, 13, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1020);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// Precision // Precision
rc = colOp.createColumn( curCol, 14, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1021 ); rc = colOp.createColumn(curCol, 14, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1021);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// AutoInc // AutoInc
rc = colOp.createColumn( curCol, 15, 1, WriteEngine::CHAR, WriteEngine::WR_CHAR, 1022 ); rc = colOp.createColumn(curCol, 15, 1, WriteEngine::CHAR, WriteEngine::WR_CHAR, 1022);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// SYSCONSTRAINT // SYSCONSTRAINT
// ConstraintName // ConstraintName
rc = colOp.createColumn( curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1023 ); rc = colOp.createColumn(curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1023);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2019, 2020, 2021); rc = fWriteEngine.createStore(txnID, 2019, 2020, 2021);
// Schema // Schema
rc = colOp.createColumn( curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1024 ); rc = colOp.createColumn(curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1024);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2022, 2023, 2024); rc = fWriteEngine.createStore(txnID, 2022, 2023, 2024);
// TableName // TableName
rc = colOp.createColumn( curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1025 ); rc = colOp.createColumn(curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1025);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2025, 2026, 2027); rc = fWriteEngine.createStore(txnID, 2025, 2026, 2027);
// ConstraintType // ConstraintType
rc = colOp.createColumn( curCol, 3, 1, WriteEngine::CHAR, WriteEngine::WR_CHAR, 1026 ); rc = colOp.createColumn(curCol, 3, 1, WriteEngine::CHAR, WriteEngine::WR_CHAR, 1026);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// ConstraintPrim // ConstraintPrim
rc = colOp.createColumn( curCol, 4, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1027 ); rc = colOp.createColumn(curCol, 4, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1027);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2028, 2029, 2030); rc = fWriteEngine.createStore(txnID, 2028, 2029, 2030);
// ConstraintText // ConstraintText
rc = colOp.createColumn( curCol, 5, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1028 ); rc = colOp.createColumn(curCol, 5, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1028);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2031, 2032, 2033); rc = fWriteEngine.createStore(txnID, 2031, 2032, 2033);
// ConstraintStatus // ConstraintStatus
rc = colOp.createColumn( curCol, 6, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1029 ); rc = colOp.createColumn(curCol, 6, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1029);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2034, 2035, 2036); rc = fWriteEngine.createStore(txnID, 2034, 2035, 2036);
// IndexName // IndexName
rc = colOp.createColumn( curCol, 7, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1030 ); rc = colOp.createColumn(curCol, 7, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1030);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2037, 2038, 2039); rc = fWriteEngine.createStore(txnID, 2037, 2038, 2039);
//SYSCONSTRAINTCOL // SYSCONSTRAINTCOL
// Schema // Schema
rc = colOp.createColumn( curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1031 ); rc = colOp.createColumn(curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1031);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2040, 2041, 2042); rc = fWriteEngine.createStore(txnID, 2040, 2041, 2042);
// TableName // TableName
rc = colOp.createColumn( curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1032 ); rc = colOp.createColumn(curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1032);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2043, 2044, 2045); rc = fWriteEngine.createStore(txnID, 2043, 2044, 2045);
// ColumnName // ColumnName
rc = colOp.createColumn( curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1033 ); rc = colOp.createColumn(curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1033);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2046, 2047, 2048); rc = fWriteEngine.createStore(txnID, 2046, 2047, 2048);
// ConstraintName // ConstraintName
rc = colOp.createColumn( curCol, 3, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1034 ); rc = colOp.createColumn(curCol, 3, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1034);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2049, 2050, 2051); rc = fWriteEngine.createStore(txnID, 2049, 2050, 2051);
// SYSINDEX // SYSINDEX
// Schema // Schema
rc = colOp.createColumn( curCol, 4, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1035 ); rc = colOp.createColumn(curCol, 4, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1035);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2052, 2053, 2054); rc = fWriteEngine.createStore(txnID, 2052, 2053, 2054);
//TableName // TableName
rc = colOp.createColumn( curCol, 5, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1036 ); rc = colOp.createColumn(curCol, 5, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1036);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2055, 2056, 2057); rc = fWriteEngine.createStore(txnID, 2055, 2056, 2057);
// IndexName // IndexName
rc = colOp.createColumn( curCol, 6, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1037 ); rc = colOp.createColumn(curCol, 6, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1037);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2058, 2059, 2060); rc = fWriteEngine.createStore(txnID, 2058, 2059, 2060);
// ListOID // ListOID
rc = colOp.createColumn( curCol, 7, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1038 ); rc = colOp.createColumn(curCol, 7, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1038);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// TreeOID // TreeOID
rc = colOp.createColumn( curCol, 8, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1039 ); rc = colOp.createColumn(curCol, 8, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1039);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// IndexType // IndexType
rc = colOp.createColumn( curCol, 9, 1, WriteEngine::CHAR, WriteEngine::WR_CHAR, 1040 ); rc = colOp.createColumn(curCol, 9, 1, WriteEngine::CHAR, WriteEngine::WR_CHAR, 1040);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// CreateDate // CreateDate
rc = colOp.createColumn( curCol, 10, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1041 ); rc = colOp.createColumn(curCol, 10, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1041);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// LastUpdateDate // LastUpdateDate
rc = colOp.createColumn( curCol, 11, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1042 ); rc = colOp.createColumn(curCol, 11, 8, WriteEngine::DATE, WriteEngine::WR_CHAR, 1042);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// RecordCount // RecordCount
rc = colOp.createColumn( curCol, 12, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1043 ); rc = colOp.createColumn(curCol, 12, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1043);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// TreeLevel // TreeLevel
rc = colOp.createColumn( curCol, 13, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1044 ); rc = colOp.createColumn(curCol, 13, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1044);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// LeafCount // LeafCount
rc = colOp.createColumn( curCol, 14, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1045 ); rc = colOp.createColumn(curCol, 14, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1045);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// DistinctKeys // DistinctKeys
rc = colOp.createColumn( curCol, 15, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1046 ); rc = colOp.createColumn(curCol, 15, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1046);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// LeafBlocks // LeafBlocks
rc = colOp.createColumn( curCol, 16, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1047 ); rc = colOp.createColumn(curCol, 16, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1047);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// AvgLeafCount // AvgLeafCount
rc = colOp.createColumn( curCol, 17, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1048 ); rc = colOp.createColumn(curCol, 17, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1048);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// AvgDataBlock // AvgDataBlock
rc = colOp.createColumn( curCol, 18, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1049 ); rc = colOp.createColumn(curCol, 18, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1049);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// SampleSize // SampleSize
rc = colOp.createColumn( curCol, 19, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1050 ); rc = colOp.createColumn(curCol, 19, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1050);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// ClusterFactor // ClusterFactor
rc = colOp.createColumn( curCol, 20, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1051 ); rc = colOp.createColumn(curCol, 20, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1051);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// LastAnalysisDate // LastAnalysisDate
rc = colOp.createColumn( curCol, 21, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1052 ); rc = colOp.createColumn(curCol, 21, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1052);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
// SYSINDEXCOL // SYSINDEXCOL
// Schema // Schema
rc = colOp.createColumn( curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1053 ); rc = colOp.createColumn(curCol, 0, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1053);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2061, 2062, 2063); rc = fWriteEngine.createStore(txnID, 2061, 2062, 2063);
// TableName // TableName
rc = colOp.createColumn( curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1054 ); rc = colOp.createColumn(curCol, 1, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1054);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2064, 2065, 2066); rc = fWriteEngine.createStore(txnID, 2064, 2065, 2066);
// ColumnName // ColumnName
rc = colOp.createColumn( curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1055 ); rc = colOp.createColumn(curCol, 2, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1055);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2067, 2068, 2069); rc = fWriteEngine.createStore(txnID, 2067, 2068, 2069);
// IndexName // IndexName
rc = colOp.createColumn( curCol, 3, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1056 ); rc = colOp.createColumn(curCol, 3, 8, WriteEngine::VARCHAR, WriteEngine::WR_CHAR, 1056);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
cout << "Creating Dictionary..." << endl; cout << "Creating Dictionary..." << endl;
//Dictionary files // Dictionary files
rc = fWriteEngine.createStore (txnID, 2070, 2071, 2072); rc = fWriteEngine.createStore(txnID, 2070, 2071, 2072);
// ColumnPos // ColumnPos
rc = colOp.createColumn( curCol, 4, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1057 ); rc = colOp.createColumn(curCol, 4, 4, WriteEngine::INT, WriteEngine::WR_CHAR, 1057);
CPPUNIT_ASSERT( rc == NO_ERROR ); CPPUNIT_ASSERT(rc == NO_ERROR);
} }
static void remove() static void remove()
{ {
ColumnOp colOp; ColumnOp colOp;
for ( int i = 1001; i <= 1057; i++ ) for (int i = 1001; i <= 1057; i++)
colOp.deleteFile( i ); colOp.deleteFile(i);
} }
}; };
void destroySemaphores() void destroySemaphores()
@ -421,8 +420,6 @@ void destroySemaphores()
} }
} }
void destroyShmseg() void destroyShmseg()
{ {
key_t shmkey; key_t shmkey;
@ -486,10 +483,9 @@ class DDLPackageProcessorTest : public CppUnit::TestFixture
CPPUNIT_TEST( test_droptable ); */ CPPUNIT_TEST( test_droptable ); */
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private:
public:
private:
public:
/* /*
* destroySemaphores() and destroyShmseg() will print error messages * destroySemaphores() and destroyShmseg() will print error messages
* if there are no objects to destroy. That's OK. * if there are no objects to destroy. That's OK.
@ -497,7 +493,8 @@ public:
void test_createtable_region() void test_createtable_region()
{ {
cout << "Begining create region table testing..." << endl; cout << "Begining create region table testing..." << endl;
std::string sqlbuf = "create table region( r_regionkey integer NOT NULL, r_name char(25) ,r_comment varchar(152));"; std::string sqlbuf =
"create table region( r_regionkey integer NOT NULL, r_name char(25) ,r_comment varchar(152));";
SqlParser parser; SqlParser parser;
parser.Parse(sqlbuf.c_str()); parser.Parse(sqlbuf.c_str());
@ -528,11 +525,15 @@ public:
void test_createtable() void test_createtable()
{ {
//setUp(); // setUp();
//removeSystemCatalog(); // removeSystemCatalog();
//createSystemCatalog(); // createSystemCatalog();
cout << "Begining create table testing..." << endl; cout << "Begining create table testing..." << endl;
std::string sqlbuf = "create table tpch.part( p_partkey integer NOT NULL ,p_name varchar(55) default 'helloworld', p_mfgr char(6), p_brand char(10) , p_type varchar(25) default 'foobar' , p_size integer , p_container char(10) ,p_retailprice integer , p_comment varchar(23), CONSTRAINT PK_PART PRIMARY KEY(p_partkey) )"; std::string sqlbuf =
"create table tpch.part( p_partkey integer NOT NULL ,p_name varchar(55) default 'helloworld', p_mfgr "
"char(6), p_brand char(10) , p_type varchar(25) default 'foobar' , p_size integer , p_container "
"char(10) ,p_retailprice integer , p_comment varchar(23), CONSTRAINT PK_PART PRIMARY KEY(p_partkey) "
")";
SqlParser parser; SqlParser parser;
parser.Parse(sqlbuf.c_str()); parser.Parse(sqlbuf.c_str());
@ -797,7 +798,8 @@ public:
void test_altertable_addcolumns() void test_altertable_addcolumns()
{ {
cout << "Begining Alter Table add columns test ..." << endl; cout << "Begining Alter Table add columns test ..." << endl;
std::string sqlbuf = "ALTER TABLE test ADD COLUMN c3 char(50), ADD COLUMN c4 char(10), ADD COLUMN C5 int;"; std::string sqlbuf =
"ALTER TABLE test ADD COLUMN c3 char(50), ADD COLUMN c4 char(10), ADD COLUMN C5 int;";
SqlParser parser; SqlParser parser;
parser.Parse(sqlbuf.c_str()); parser.Parse(sqlbuf.c_str());
@ -891,7 +893,6 @@ public:
tearDown(); tearDown();
} }
void test_altertable_renamecolumnwithcons() void test_altertable_renamecolumnwithcons()
{ {
cout << "Begining Alter Table rename a column with constraints ..." << endl; cout << "Begining Alter Table rename a column with constraints ..." << endl;
@ -1120,21 +1121,20 @@ public:
tearDown(); tearDown();
} }
}; };
CPPUNIT_TEST_SUITE_REGISTRATION( DDLPackageProcessorTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DDLPackageProcessorTest);
#include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h> #include <cppunit/ui/text/TestRunner.h>
int main( int argc, char** argv) int main(int argc, char** argv)
{ {
// Uncomment before running tests // Uncomment before running tests
//setUp(); // setUp();
CppUnit::TextUi::TestRunner runner; CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() ); runner.addTest(registry.makeTest());
bool wasSuccessful = runner.run( "", false ); bool wasSuccessful = runner.run("", false);
return (wasSuccessful ? 0 : 1); return (wasSuccessful ? 0 : 1);
} }

View File

@ -46,8 +46,8 @@ namespace dmlpackage
{ {
boost::mutex CalpontDMLFactory::fParserLock; boost::mutex CalpontDMLFactory::fParserLock;
dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpackage::VendorDMLStatement& vpackage, dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(
std::string defaultSchema /*= ""*/) dmlpackage::VendorDMLStatement& vpackage, std::string defaultSchema /*= ""*/)
{ {
CalpontDMLPackage* packagePtr = 0; CalpontDMLPackage* packagePtr = 0;
@ -67,7 +67,6 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka
if (parser.good()) if (parser.good())
{ {
const ParseTree& ptree = parser.getParseTree(); const ParseTree& ptree = parser.getParseTree();
SqlStatement* statementPtr = ptree[0]; SqlStatement* statementPtr = ptree[0];
@ -77,21 +76,21 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka
{ {
case DML_INSERT: case DML_INSERT:
packagePtr = new InsertDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(), packagePtr = new InsertDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(),
ptree.fSqlText, vpackage.get_SessionID() ); ptree.fSqlText, vpackage.get_SessionID());
packagePtr->set_SQLStatement(dmlStatement); packagePtr->set_SQLStatement(dmlStatement);
(void)packagePtr->buildFromSqlStatement(*statementPtr); (void)packagePtr->buildFromSqlStatement(*statementPtr);
break; break;
case DML_UPDATE: case DML_UPDATE:
packagePtr = new UpdateDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(), packagePtr = new UpdateDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(),
ptree.fSqlText, vpackage.get_SessionID() ); ptree.fSqlText, vpackage.get_SessionID());
packagePtr->set_SQLStatement(dmlStatement); packagePtr->set_SQLStatement(dmlStatement);
(void)packagePtr->buildFromSqlStatement(*statementPtr); (void)packagePtr->buildFromSqlStatement(*statementPtr);
break; break;
case DML_DELETE: case DML_DELETE:
packagePtr = new DeleteDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(), packagePtr = new DeleteDMLPackage(statementPtr->getSchemaName(), statementPtr->getTableName(),
ptree.fSqlText, vpackage.get_SessionID() ); ptree.fSqlText, vpackage.get_SessionID());
packagePtr->set_SQLStatement(dmlStatement); packagePtr->set_SQLStatement(dmlStatement);
(void)packagePtr->buildFromSqlStatement(*statementPtr); (void)packagePtr->buildFromSqlStatement(*statementPtr);
break; break;
@ -101,12 +100,8 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka
(void)packagePtr->buildFromSqlStatement(*statementPtr); (void)packagePtr->buildFromSqlStatement(*statementPtr);
break; break;
default: default: cerr << "makeCalpontDMLPackage: invalid statement type" << endl; break;
cerr << "makeCalpontDMLPackage: invalid statement type" << endl;
break;
} }
} }
} }
catch (std::exception& ex) catch (std::exception& ex)
@ -119,10 +114,10 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackage(dmlpacka
} }
return packagePtr; return packagePtr;
} }
dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromBuffer(dmlpackage::VendorDMLStatement& vpackage) dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromBuffer(
dmlpackage::VendorDMLStatement& vpackage)
{ {
CalpontDMLPackage* packagePtr = 0; CalpontDMLPackage* packagePtr = 0;
@ -133,75 +128,32 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromBuffe
switch (dmlStatementType) switch (dmlStatementType)
{ {
case DML_INSERT: case DML_INSERT:
packagePtr = new InsertDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID()); packagePtr = new InsertDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),
(void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer vpackage.get_DMLStatement(), vpackage.get_SessionID());
(), vpackage.get_Columns(), vpackage.get_Rows()); (void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer(), vpackage.get_Columns(),
vpackage.get_Rows());
break; break;
case DML_UPDATE: case DML_UPDATE:
packagePtr = new UpdateDMLPackage(vpackage.get_SchemaName(), packagePtr = new UpdateDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),
vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID()); vpackage.get_DMLStatement(), vpackage.get_SessionID());
(void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer (void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer(), vpackage.get_Columns(),
(), vpackage.get_Columns(), vpackage.get_Rows()); vpackage.get_Rows());
break;
case DML_DELETE:
packagePtr = new DeleteDMLPackage(vpackage.get_SchemaName(),
vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID());
(void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer
(), vpackage.get_Columns(), vpackage.get_Rows());
break;
case DML_COMMAND:
packagePtr = new CommandDMLPackage(vpackage.get_DMLStatement(), vpackage.get_SessionID() );
break;
default:
cerr << "makeCalpontDMLPackage: invalid statement type" << endl;
break;
}
}
catch (std::exception& ex)
{
cerr << "makeCalpontDMLPackage:" << ex.what() << endl;
}
catch (...)
{
cerr << "makeCalpontDMLPackage: caught unknown exception!" << endl;
}
return packagePtr;
}
dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(dmlpackage::VendorDMLStatement& vpackage)
{
CalpontDMLPackage* packagePtr = 0;
try
{
int dmlStatementType = vpackage.get_DMLStatementType();
switch (dmlStatementType)
{
case DML_INSERT:
packagePtr = new InsertDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(), vpackage.get_DMLStatement(), vpackage.get_SessionID());
(void)packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(), vpackage.get_Columns(), vpackage.get_Rows(), vpackage.get_nullValues());
break;
case DML_COMMAND:
packagePtr = new CommandDMLPackage(vpackage.get_DMLStatement(), vpackage.get_SessionID() );
break; break;
case DML_DELETE: case DML_DELETE:
packagePtr = new DeleteDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(), packagePtr = new DeleteDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),
vpackage.get_DMLStatement(), vpackage.get_SessionID() ); vpackage.get_DMLStatement(), vpackage.get_SessionID());
(void)packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(), vpackage.get_Columns(), vpackage.get_Rows(), vpackage.get_nullValues()); (void)packagePtr->buildFromBuffer(vpackage.get_DataBuffer(), vpackage.get_Columns(),
vpackage.get_Rows());
break; break;
default: case DML_COMMAND:
cerr << "makeCalpontDMLPackage: invalid statement type" << endl; packagePtr = new CommandDMLPackage(vpackage.get_DMLStatement(), vpackage.get_SessionID());
break; break;
default: cerr << "makeCalpontDMLPackage: invalid statement type" << endl; break;
} }
} }
catch (std::exception& ex) catch (std::exception& ex)
@ -216,13 +168,61 @@ dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromMysql
return packagePtr; return packagePtr;
} }
dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontUpdatePackageFromMysqlBuffer(dmlpackage::VendorDMLStatement& vpackage, dmlpackage::UpdateSqlStatement& updateStmt) dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontDMLPackageFromMysqlBuffer(
dmlpackage::VendorDMLStatement& vpackage)
{ {
CalpontDMLPackage* packagePtr = new UpdateDMLPackage((updateStmt.fNamePtr)->fSchema, (updateStmt.fNamePtr)->fName, CalpontDMLPackage* packagePtr = 0;
vpackage.get_DMLStatement(), vpackage.get_SessionID() );
try
{
int dmlStatementType = vpackage.get_DMLStatementType();
switch (dmlStatementType)
{
case DML_INSERT:
packagePtr = new InsertDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),
vpackage.get_DMLStatement(), vpackage.get_SessionID());
(void)packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(),
vpackage.get_Columns(), vpackage.get_Rows(),
vpackage.get_nullValues());
break;
case DML_COMMAND:
packagePtr = new CommandDMLPackage(vpackage.get_DMLStatement(), vpackage.get_SessionID());
break;
case DML_DELETE:
packagePtr = new DeleteDMLPackage(vpackage.get_SchemaName(), vpackage.get_TableName(),
vpackage.get_DMLStatement(), vpackage.get_SessionID());
(void)packagePtr->buildFromMysqlBuffer(vpackage.get_ColNames(), vpackage.get_values(),
vpackage.get_Columns(), vpackage.get_Rows(),
vpackage.get_nullValues());
break;
default: cerr << "makeCalpontDMLPackage: invalid statement type" << endl; break;
}
}
catch (std::exception& ex)
{
cerr << "makeCalpontDMLPackage:" << ex.what() << endl;
}
catch (...)
{
cerr << "makeCalpontDMLPackage: caught unknown exception!" << endl;
}
return packagePtr;
}
dmlpackage::CalpontDMLPackage* CalpontDMLFactory::makeCalpontUpdatePackageFromMysqlBuffer(
dmlpackage::VendorDMLStatement& vpackage, dmlpackage::UpdateSqlStatement& updateStmt)
{
CalpontDMLPackage* packagePtr =
new UpdateDMLPackage((updateStmt.fNamePtr)->fSchema, (updateStmt.fNamePtr)->fName,
vpackage.get_DMLStatement(), vpackage.get_SessionID());
UpdateDMLPackage* updatePkgPtr = dynamic_cast<UpdateDMLPackage*>(packagePtr); UpdateDMLPackage* updatePkgPtr = dynamic_cast<UpdateDMLPackage*>(packagePtr);
updatePkgPtr->buildUpdateFromMysqlBuffer(updateStmt); updatePkgPtr->buildUpdateFromMysqlBuffer(updateStmt);
packagePtr = dynamic_cast<CalpontDMLPackage*>(updatePkgPtr); packagePtr = dynamic_cast<CalpontDMLPackage*>(updatePkgPtr);
return packagePtr; return packagePtr;
} }
} //namespace dmlpackage } // namespace dmlpackage

View File

@ -35,39 +35,38 @@
#endif #endif
namespace dmlpackage namespace dmlpackage
{ {
class CalpontDMLFactory class CalpontDMLFactory
{ {
/** @brief a concrete implementation responsible for creating /** @brief a concrete implementation responsible for creating
* the proper concrete realization of a CalpontDMLPackage * the proper concrete realization of a CalpontDMLPackage
* given a VendorDMLStatement. * given a VendorDMLStatement.
*/ */
public: public:
/** @brief factory method /** @brief factory method
* *
* @param vpackage the VendorDMLStatement * @param vpackage the VendorDMLStatement
* @param defaultSchema the default schema to be used for DML statements * @param defaultSchema the default schema to be used for DML statements
*/ */
EXPORT static dmlpackage::CalpontDMLPackage* makeCalpontDMLPackage (dmlpackage::VendorDMLStatement& vpackage, EXPORT static dmlpackage::CalpontDMLPackage* makeCalpontDMLPackage(dmlpackage::VendorDMLStatement& vpackage,
std::string defaultSchema = "" ); std::string defaultSchema = "");
/** @brief old factory method! /** @brief old factory method!
* *
* @param vpackage the VendorDMLStatement * @param vpackage the VendorDMLStatement
*/ */
EXPORT static dmlpackage::CalpontDMLPackage* makeCalpontDMLPackageFromBuffer(dmlpackage::VendorDMLStatement& vpackage); EXPORT static dmlpackage::CalpontDMLPackage* makeCalpontDMLPackageFromBuffer(
dmlpackage::VendorDMLStatement& vpackage);
EXPORT static dmlpackage::CalpontDMLPackage* makeCalpontDMLPackageFromMysqlBuffer(dmlpackage::VendorDMLStatement& vpackage); EXPORT static dmlpackage::CalpontDMLPackage* makeCalpontDMLPackageFromMysqlBuffer(
static dmlpackage::CalpontDMLPackage* makeCalpontUpdatePackageFromMysqlBuffer(dmlpackage::VendorDMLStatement& vpackage, dmlpackage::UpdateSqlStatement& updateStmt); dmlpackage::VendorDMLStatement& vpackage);
static dmlpackage::CalpontDMLPackage* makeCalpontUpdatePackageFromMysqlBuffer(
dmlpackage::VendorDMLStatement& vpackage, dmlpackage::UpdateSqlStatement& updateStmt);
protected: protected:
private:
private:
static boost::mutex fParserLock; static boost::mutex fParserLock;
}; };
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -31,40 +31,56 @@ namespace dmlpackage
*/ */
CalpontDMLPackage::CalpontDMLPackage() CalpontDMLPackage::CalpontDMLPackage()
: fPlan(new messageqcpp::ByteStream()), : fPlan(new messageqcpp::ByteStream())
fTable(0), fHasFilter(0), fLogging(true), fIsInsertSelect(false), , fTable(0)
fIsBatchInsert(false), fIsCacheInsert(false), fIsAutocommitOn(false), fIsWarnToError(false), fTableOid(0) , fHasFilter(0)
, fLogging(true)
, fIsInsertSelect(false)
, fIsBatchInsert(false)
, fIsCacheInsert(false)
, fIsAutocommitOn(false)
, fIsWarnToError(false)
, fTableOid(0)
{ {
} }
CalpontDMLPackage::CalpontDMLPackage( std::string schemaName, std::string tableName, CalpontDMLPackage::CalpontDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID ) int sessionID)
: fSchemaName(schemaName), fTableName( tableName ), fDMLStatement( dmlStatement ), : fSchemaName(schemaName)
fSessionID(sessionID), fPlan(new messageqcpp::ByteStream()), fTable(0), fHasFilter(false), fLogging(true), fIsInsertSelect(false), , fTableName(tableName)
fIsBatchInsert(false), fIsCacheInsert(false), fIsAutocommitOn(false), fIsWarnToError(false), fTableOid(0) , fDMLStatement(dmlStatement)
, fSessionID(sessionID)
, fPlan(new messageqcpp::ByteStream())
, fTable(0)
, fHasFilter(false)
, fLogging(true)
, fIsInsertSelect(false)
, fIsBatchInsert(false)
, fIsCacheInsert(false)
, fIsAutocommitOn(false)
, fIsWarnToError(false)
, fTableOid(0)
{ {
} }
CalpontDMLPackage::~CalpontDMLPackage() CalpontDMLPackage::~CalpontDMLPackage()
{ {
if ( 0 != fTable ) if (0 != fTable)
delete fTable; delete fTable;
} }
/* /*
* strip off whitespaces from a string * strip off whitespaces from a string
*/ */
std::string CalpontDMLPackage::StripLeadingWhitespace( std::string value ) std::string CalpontDMLPackage::StripLeadingWhitespace(std::string value)
{ {
for (;;) for (;;)
{ {
string::size_type pos = value.find (' ', 0); string::size_type pos = value.find(' ', 0);
if (pos == 0) if (pos == 0)
{ {
value = value.substr (pos + 1, 10000); value = value.substr(pos + 1, 10000);
} }
else else
{ {

View File

@ -40,8 +40,7 @@ namespace dmlpackage
*/ */
class CalpontDMLPackage class CalpontDMLPackage
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
CalpontDMLPackage(); CalpontDMLPackage();
@ -53,8 +52,7 @@ public:
* @param dmlStatement the dml statement * @param dmlStatement the dml statement
* @param sessionID the session id * @param sessionID the session id
*/ */
CalpontDMLPackage( std::string schemaName, std::string tableName, CalpontDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement, int sessionID);
std::string dmlStatement, int sessionID );
/** @brief dtor /** @brief dtor
*/ */
@ -64,13 +62,13 @@ public:
* *
* @param bytestream the ByteStream to write to * @param bytestream the ByteStream to write to
*/ */
virtual int write( messageqcpp::ByteStream& bytestream ) = 0; virtual int write(messageqcpp::ByteStream& bytestream) = 0;
/** @brief read a CalpontDMLPackage from a ByteStream /** @brief read a CalpontDMLPackage from a ByteStream
* *
* @param bytestream the ByteStream to read from * @param bytestream the ByteStream to read from
*/ */
virtual int read( messageqcpp::ByteStream& bytestream ) = 0; virtual int read(messageqcpp::ByteStream& bytestream) = 0;
/** @brief build a CalpontDMLPackage from a string buffer /** @brief build a CalpontDMLPackage from a string buffer
* *
@ -78,13 +76,13 @@ public:
* @param columns the number of columns in the buffer * @param columns the number of columns in the buffer
* @param rows the number of rows in the buffer * @param rows the number of rows in the buffer
*/ */
virtual int buildFromBuffer( std::string& buffer, int columns, int rows ) = 0; virtual int buildFromBuffer(std::string& buffer, int columns, int rows) = 0;
/** @brief build a CalpontDMLPackage from a parsed SqlStatement /** @brief build a CalpontDMLPackage from a parsed SqlStatement
* *
* @param sqlStatement the parsed SqlStatement * @param sqlStatement the parsed SqlStatement
*/ */
virtual int buildFromSqlStatement( SqlStatement& sqlStatement ) = 0; virtual int buildFromSqlStatement(SqlStatement& sqlStatement) = 0;
/** @brief build a CalpontDMLPackage from valuelist built from mysql table fields /** @brief build a CalpontDMLPackage from valuelist built from mysql table fields
* *
@ -93,7 +91,8 @@ public:
* @param columns number of columns in the table * @param columns number of columns in the table
* @param rows number of rows to be touched * @param rows number of rows to be touched
*/ */
virtual int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues) = 0; virtual int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns,
int rows, NullValuesBitset& nullValues) = 0;
/** @brief get the table object /** @brief get the table object
*/ */
@ -106,7 +105,7 @@ public:
* *
* @param statement the dml statement to set * @param statement the dml statement to set
*/ */
void set_DMLStatement( const std::string& statement ) void set_DMLStatement(const std::string& statement)
{ {
fDMLStatement = statement; fDMLStatement = statement;
} }
@ -122,7 +121,7 @@ public:
* *
* @param statement the SQL statement to set (the original SQL statement with quotes) * @param statement the SQL statement to set (the original SQL statement with quotes)
*/ */
void set_SQLStatement( const std::string& statement ) void set_SQLStatement(const std::string& statement)
{ {
fSQLStatement = statement; fSQLStatement = statement;
} }
@ -145,7 +144,7 @@ public:
* *
* @param logging the logging flag to set * @param logging the logging flag to set
*/ */
void set_Logging( bool logging ) void set_Logging(bool logging)
{ {
fLogging = logging; fLogging = logging;
} }
@ -161,7 +160,7 @@ public:
* *
* @param logending the logending flag to set * @param logending the logending flag to set
*/ */
void set_Logending( bool logending ) void set_Logending(bool logending)
{ {
fLogending = logending; fLogending = logending;
} }
@ -177,7 +176,7 @@ public:
* *
* @param logging the logging flag to set * @param logging the logging flag to set
*/ */
void set_IsFromCol ( bool isFromCol ) void set_IsFromCol(bool isFromCol)
{ {
fIsFromCol = isFromCol; fIsFromCol = isFromCol;
} }
@ -185,7 +184,7 @@ public:
* *
* @param tableName the name to set * @param tableName the name to set
*/ */
void set_TableName( std::string& tableName ) void set_TableName(std::string& tableName)
{ {
fTableName = tableName; fTableName = tableName;
@ -204,7 +203,7 @@ public:
* *
* @param the schema to set * @param the schema to set
*/ */
void set_SchemaName( std::string& schemaName ) void set_SchemaName(std::string& schemaName)
{ {
fSchemaName = schemaName; fSchemaName = schemaName;
@ -223,7 +222,7 @@ public:
* *
* @param the timezone to set * @param the timezone to set
*/ */
void set_TimeZone( const std::string& timeZone ) void set_TimeZone(const std::string& timeZone)
{ {
fTimeZone = timeZone; fTimeZone = timeZone;
} }
@ -241,7 +240,7 @@ public:
{ {
return fHasFilter; return fHasFilter;
} }
void HasFilter( bool hasFilter) void HasFilter(bool hasFilter)
{ {
fHasFilter = hasFilter; fHasFilter = hasFilter;
} }
@ -255,7 +254,7 @@ public:
/** @brief set the sessionID associated with this package /** @brief set the sessionID associated with this package
*/ */
void set_SessionID( int sessionID ) void set_SessionID(int sessionID)
{ {
fSessionID = sessionID; fSessionID = sessionID;
} }
@ -269,7 +268,7 @@ public:
/** @brief set the transaction ID associated with this package /** @brief set the transaction ID associated with this package
*/ */
void set_TxnID( execplan::CalpontSystemCatalog::SCN txnID ) void set_TxnID(execplan::CalpontSystemCatalog::SCN txnID)
{ {
fTxnId = txnID; fTxnId = txnID;
} }
@ -282,7 +281,7 @@ public:
} }
/** @brief set the chunkmanager associated with this package /** @brief set the chunkmanager associated with this package
*/ */
void set_ChunkManager( WriteEngine::ChunkManager* cm ) void set_ChunkManager(WriteEngine::ChunkManager* cm)
{ {
fCM = cm; fCM = cm;
} }
@ -305,7 +304,7 @@ public:
{ {
return fIsInsertSelect; return fIsInsertSelect;
} }
void set_isInsertSelect( const bool isInsertSelect ) void set_isInsertSelect(const bool isInsertSelect)
{ {
fIsInsertSelect = isInsertSelect; fIsInsertSelect = isInsertSelect;
} }
@ -314,7 +313,7 @@ public:
{ {
return fIsBatchInsert; return fIsBatchInsert;
} }
void set_isBatchInsert( const bool isBatchInsert ) void set_isBatchInsert(const bool isBatchInsert)
{ {
fIsBatchInsert = isBatchInsert; fIsBatchInsert = isBatchInsert;
} }
@ -323,7 +322,7 @@ public:
{ {
return fIsCacheInsert; return fIsCacheInsert;
} }
void set_isCacheInsert( const bool isCacheInsert ) void set_isCacheInsert(const bool isCacheInsert)
{ {
fIsCacheInsert = isCacheInsert; fIsCacheInsert = isCacheInsert;
} }
@ -332,7 +331,7 @@ public:
{ {
return fIsAutocommitOn; return fIsAutocommitOn;
} }
void set_isAutocommitOn( const bool isAutocommitOn ) void set_isAutocommitOn(const bool isAutocommitOn)
{ {
fIsAutocommitOn = isAutocommitOn; fIsAutocommitOn = isAutocommitOn;
} }
@ -341,7 +340,7 @@ public:
{ {
return fIsWarnToError; return fIsWarnToError;
} }
void set_isWarnToError( const bool isWarnToError ) void set_isWarnToError(const bool isWarnToError)
{ {
fIsWarnToError = isWarnToError; fIsWarnToError = isWarnToError;
} }
@ -350,7 +349,7 @@ public:
{ {
return fTableOid; return fTableOid;
} }
void setTableOid( const uint32_t tableOid ) void setTableOid(const uint32_t tableOid)
{ {
fTableOid = tableOid; fTableOid = tableOid;
} }
@ -364,8 +363,7 @@ public:
return fUuid; return fUuid;
} }
protected: protected:
void initializeTable(); void initializeTable();
std::string fSchemaName; std::string fSchemaName;
@ -383,7 +381,7 @@ protected:
bool fLogging; bool fLogging;
bool fLogending; bool fLogending;
bool fIsFromCol; bool fIsFromCol;
std::string StripLeadingWhitespace( std::string value ); std::string StripLeadingWhitespace(std::string value);
bool fIsInsertSelect; bool fIsInsertSelect;
bool fIsBatchInsert; bool fIsBatchInsert;
bool fIsCacheInsert; bool fIsCacheInsert;
@ -392,4 +390,4 @@ protected:
uint32_t fTableOid; uint32_t fTableOid;
WriteEngine::ChunkManager* fCM; WriteEngine::ChunkManager* fCM;
}; };
} } // namespace dmlpackage

View File

@ -31,16 +31,18 @@ using namespace std;
#undef COMMANDDMLPKG_DLLEXPORT #undef COMMANDDMLPKG_DLLEXPORT
namespace dmlpackage namespace dmlpackage
{ {
CommandDMLPackage::CommandDMLPackage() CommandDMLPackage::CommandDMLPackage()
{} {
}
CommandDMLPackage::CommandDMLPackage( std::string dmlStatement, int sessionID) CommandDMLPackage::CommandDMLPackage(std::string dmlStatement, int sessionID)
: CalpontDMLPackage( "", "", dmlStatement, sessionID) : CalpontDMLPackage("", "", dmlStatement, sessionID)
{} {
}
CommandDMLPackage::~CommandDMLPackage() CommandDMLPackage::~CommandDMLPackage()
{} {
}
int CommandDMLPackage::write(messageqcpp::ByteStream& bytestream) int CommandDMLPackage::write(messageqcpp::ByteStream& bytestream)
{ {
@ -84,8 +86,8 @@ int CommandDMLPackage::read(messageqcpp::ByteStream& bytestream)
bytestream >> fTimeZone; bytestream >> fTimeZone;
bytestream >> fTableName; bytestream >> fTableName;
bytestream >> fTableOid; bytestream >> fTableOid;
bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsAutocommitOn); bytestream >> reinterpret_cast<messageqcpp::ByteStream::byte&>(fIsAutocommitOn);
bytestream >> reinterpret_cast< messageqcpp::ByteStream::byte&>(fIsBatchInsert); bytestream >> reinterpret_cast<messageqcpp::ByteStream::byte&>(fIsBatchInsert);
return retval; return retval;
} }

View File

@ -40,15 +40,14 @@ namespace dmlpackage
*/ */
class CommandDMLPackage : public CalpontDMLPackage class CommandDMLPackage : public CalpontDMLPackage
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT CommandDMLPackage(); EXPORT CommandDMLPackage();
/** @brief ctor /** @brief ctor
*/ */
EXPORT CommandDMLPackage( std::string dmlStatement, int sessionID ); EXPORT CommandDMLPackage(std::string dmlStatement, int sessionID);
/** @brief dtor /** @brief dtor
*/ */
@ -85,18 +84,16 @@ public:
* @param colNameList, tableValuesMap * @param colNameList, tableValuesMap
* @param rows the number of rows in the buffer * @param rows the number of rows in the buffer
*/ */
int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues) int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows,
NullValuesBitset& nullValues)
{ {
return 1; return 1;
}; };
protected: protected:
private:
private:
}; };
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -32,17 +32,19 @@ using namespace std;
namespace dmlpackage namespace dmlpackage
{ {
DeleteDMLPackage::DeleteDMLPackage() DeleteDMLPackage::DeleteDMLPackage()
{} {
}
DeleteDMLPackage::DeleteDMLPackage(std::string schemaName, std::string tableName, DeleteDMLPackage::DeleteDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID) int sessionID)
: CalpontDMLPackage( schemaName, tableName, dmlStatement, sessionID ) : CalpontDMLPackage(schemaName, tableName, dmlStatement, sessionID)
{} {
}
DeleteDMLPackage::~DeleteDMLPackage() DeleteDMLPackage::~DeleteDMLPackage()
{} {
}
int DeleteDMLPackage::write(messageqcpp::ByteStream& bytestream) int DeleteDMLPackage::write(messageqcpp::ByteStream& bytestream)
{ {
@ -141,7 +143,7 @@ int DeleteDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
int DeleteDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows) int DeleteDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows)
{ {
#ifdef DML_PACKAGE_DEBUG #ifdef DML_PACKAGE_DEBUG
//cout << "The data buffer received: " << buffer << endl; // cout << "The data buffer received: " << buffer << endl;
#endif #endif
int retval = 1; int retval = 1;
@ -156,25 +158,24 @@ int DeleteDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows
for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
{ {
dataList.push_back(StripLeadingWhitespace(*tok_iter)); dataList.push_back(StripLeadingWhitespace(*tok_iter));
} }
int n = 0; int n = 0;
for (int i = 0; i < rows; i++) for (int i = 0; i < rows; i++)
{ {
//get a new row // get a new row
Row aRow; Row aRow;
//Row *aRowPtr = new Row(); // Row *aRowPtr = new Row();
//std::string colName; // std::string colName;
//std::string colValue; // std::string colValue;
//get row ID from the buffer // get row ID from the buffer
std::string rowid = dataList[n++]; std::string rowid = dataList[n++];
aRow.set_RowID(atoll(rowid.c_str())); aRow.set_RowID(atoll(rowid.c_str()));
//aRowPtr->set_RowID(atol(rowid.c_str())); // aRowPtr->set_RowID(atol(rowid.c_str()));
#ifdef DML_PACKAGE_DEBUG #ifdef DML_PACKAGE_DEBUG
//cout << "The row ID is " << rowid << endl; // cout << "The row ID is " << rowid << endl;
#endif #endif
/* /*
for (int j = 0; j < columns; j++) for (int j = 0; j < columns; j++)
@ -194,15 +195,15 @@ int DeleteDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows
} }
return retval; return retval;
} }
int DeleteDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues ) int DeleteDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap,
int columns, int rows, NullValuesBitset& nullValues)
{ {
int retval = 1; int retval = 1;
initializeTable(); initializeTable();
//The row already built from MySql parser. // The row already built from MySql parser.
/* Row *aRowPtr = new Row(); /* Row *aRowPtr = new Row();
std::string colName; std::string colName;
std::vector<std::string> colValList; std::vector<std::string> colValList;

View File

@ -40,9 +40,7 @@ namespace dmlpackage
*/ */
class DeleteDMLPackage : public CalpontDMLPackage class DeleteDMLPackage : public CalpontDMLPackage
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT DeleteDMLPackage(); EXPORT DeleteDMLPackage();
@ -54,8 +52,8 @@ public:
* @param dmlStatement the dml statement * @param dmlStatement the dml statement
* @param sessionID the session ID * @param sessionID the session ID
*/ */
EXPORT DeleteDMLPackage( std::string schemaName, std::string tableName, EXPORT DeleteDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID ); int sessionID);
/** @brief dtor /** @brief dtor
*/ */
@ -91,14 +89,12 @@ public:
* @param colNameList, tableValuesMap * @param colNameList, tableValuesMap
* @param rows the number of rows in the buffer * @param rows the number of rows in the buffer
*/ */
EXPORT int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues); EXPORT int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns,
int rows, NullValuesBitset& nullValues);
protected:
private:
protected:
private:
}; };
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,6 @@
This special exception was added by the Free Software Foundation in This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */ version 2.2 of Bison. */
/* Tokens. */ /* Tokens. */
#pragma once #pragma once
/* Put the tokens into the symbol table, so that GDB and other debuggers /* Put the tokens into the symbol table, so that GDB and other debuggers
@ -130,13 +129,9 @@ enum yytokentype
}; };
#endif #endif
#if !defined YYSTYPE && !defined YYSTYPE_IS_DECLARED
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE typedef union YYSTYPE
{ {
int intval; int intval;
double floatval; double floatval;
char* strval; char* strval;
@ -169,13 +164,9 @@ typedef union YYSTYPE
dmlpackage::ColumnAssignment* colAssignment; dmlpackage::ColumnAssignment* colAssignment;
dmlpackage::ColumnAssignmentList* colAssignmentList; dmlpackage::ColumnAssignmentList* colAssignmentList;
} YYSTYPE; } YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1 #define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */ #define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1 #define YYSTYPE_IS_DECLARED 1
extern YYSTYPE dmllval; extern YYSTYPE dmllval;

File diff suppressed because it is too large Load Diff

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dmlcolumn.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dmlcolumn.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#define DMLPKGCOLUMN_DLLEXPORT #define DMLPKGCOLUMN_DLLEXPORT
#include "dmlcolumn.h" #include "dmlcolumn.h"
@ -31,17 +31,16 @@
namespace dmlpackage namespace dmlpackage
{ {
DMLColumn::DMLColumn() DMLColumn::DMLColumn()
{} {
}
DMLColumn::DMLColumn(std::string name, std::string value, bool isFromCol, uint32_t funcScale, bool isNULL) DMLColumn::DMLColumn(std::string name, std::string value, bool isFromCol, uint32_t funcScale, bool isNULL)
{ {
fName = name; fName = name;
fData = value; fData = value;
if (( strcasecmp(value.c_str(), "NULL") == 0) || (value.length() == 0) ) if ((strcasecmp(value.c_str(), "NULL") == 0) || (value.length() == 0))
{ {
isNULL = true; isNULL = true;
} }
@ -49,10 +48,10 @@ DMLColumn::DMLColumn(std::string name, std::string value, bool isFromCol, uint32
fisNULL = isNULL; fisNULL = isNULL;
fIsFromCol = isFromCol; fIsFromCol = isFromCol;
fFuncScale = funcScale; fFuncScale = funcScale;
} }
DMLColumn::DMLColumn(std::string name, std::vector<std::string>& valueList, bool isFromCol, uint32_t funcScale, bool isNULL) DMLColumn::DMLColumn(std::string name, std::vector<std::string>& valueList, bool isFromCol,
uint32_t funcScale, bool isNULL)
{ {
fName = name; fName = name;
fColValuesList = valueList; fColValuesList = valueList;
@ -62,7 +61,8 @@ DMLColumn::DMLColumn(std::string name, std::vector<std::string>& valueList, bool
} }
DMLColumn::~DMLColumn() DMLColumn::~DMLColumn()
{} {
}
int DMLColumn::read(messageqcpp::ByteStream& bytestream) int DMLColumn::read(messageqcpp::ByteStream& bytestream)
{ {
@ -72,28 +72,27 @@ int DMLColumn::read(messageqcpp::ByteStream& bytestream)
uint32_t vectorSize; uint32_t vectorSize;
bytestream >> vectorSize; bytestream >> vectorSize;
if (vectorSize > 0 ) if (vectorSize > 0)
{ {
for ( uint32_t i = 0; i < vectorSize; i++ ) for (uint32_t i = 0; i < vectorSize; i++)
{ {
std::string dataStr; std::string dataStr;
bytestream >> dataStr; bytestream >> dataStr;
// if ( !fisNULL && (dataStr.length() == 0 )) // if ( !fisNULL && (dataStr.length() == 0 ))
// dataStr = (char) 0; // dataStr = (char) 0;
fColValuesList.push_back( dataStr); fColValuesList.push_back(dataStr);
} }
} }
else else
bytestream >> fData; //deprecated. bytestream >> fData; // deprecated.
if ( (fColValuesList.size() < 1) && (fColValuesList.size() > 0) ) //deprecated. if ((fColValuesList.size() < 1) && (fColValuesList.size() > 0)) // deprecated.
fData = fColValuesList[0] ; //deprecated. fData = fColValuesList[0]; // deprecated.
//bytestream >> reinterpret_cast<messageqcpp::ByteStream::byte&>(fisNULL); // bytestream >> reinterpret_cast<messageqcpp::ByteStream::byte&>(fisNULL);
bytestream >> reinterpret_cast<messageqcpp::ByteStream::byte&>(fIsFromCol); bytestream >> reinterpret_cast<messageqcpp::ByteStream::byte&>(fIsFromCol);
bytestream >> (uint32_t&) fFuncScale; bytestream >> (uint32_t&)fFuncScale;
return retval; return retval;
} }
@ -105,21 +104,20 @@ int DMLColumn::write(messageqcpp::ByteStream& bytestream)
uint32_t vectorSize = fColValuesList.size(); uint32_t vectorSize = fColValuesList.size();
bytestream << vectorSize; bytestream << vectorSize;
if (vectorSize > 0 ) if (vectorSize > 0)
{ {
for ( uint32_t i = 0; i < vectorSize; i++ ) for (uint32_t i = 0; i < vectorSize; i++)
{ {
bytestream << fColValuesList[i]; bytestream << fColValuesList[i];
} }
} }
else else
bytestream << fData; //deprecated. bytestream << fData; // deprecated.
//bytestream << static_cast<uint8_t>(fisNULL); // bytestream << static_cast<uint8_t>(fisNULL);
bytestream << static_cast<uint8_t>(fIsFromCol); bytestream << static_cast<uint8_t>(fIsFromCol);
bytestream << (uint32_t)fFuncScale; bytestream << (uint32_t)fFuncScale;
return retval; return retval;
} }
} //namespace dmlpackage } // namespace dmlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dmlcolumn.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dmlcolumn.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
@ -42,8 +42,7 @@ namespace dmlpackage
*/ */
class DMLColumn : public DMLObject class DMLColumn : public DMLObject
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT DMLColumn(); EXPORT DMLColumn();
@ -51,12 +50,14 @@ public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT DMLColumn(std::string name, std::string value, bool isFromCol = false, uint32_t funcScale = 0, bool isNULL = false); EXPORT DMLColumn(std::string name, std::string value, bool isFromCol = false, uint32_t funcScale = 0,
bool isNULL = false);
/** @brief new ctor /** @brief new ctor
* isNUll is currently not in use. It supposed to indicate whether each value is null or not. * isNUll is currently not in use. It supposed to indicate whether each value is null or not.
*/ */
EXPORT DMLColumn(std::string name, std::vector<std::string>& valueList, bool isFromCol = false, uint32_t funcScale = 0, bool isNULL = false ); EXPORT DMLColumn(std::string name, std::vector<std::string>& valueList, bool isFromCol = false,
uint32_t funcScale = 0, bool isNULL = false);
/** @brief dtor /** @brief dtor
*/ */
@ -81,7 +82,6 @@ public:
return fData; return fData;
} }
const std::vector<std::string>& get_DataVector() const const std::vector<std::string>& get_DataVector() const
{ {
return fColValuesList; return fColValuesList;
@ -113,57 +113,53 @@ public:
} }
/** @brief set the column name /** @brief set the column name
*/ */
EXPORT void set_Name( std::string name) EXPORT void set_Name(std::string name)
{ {
boost::algorithm::to_lower(name); boost::algorithm::to_lower(name);
fName = name; fName = name;
} }
/** @brief set the NULL flag /** @brief set the NULL flag
*/ */
void set_isnull( bool isNULL) void set_isnull(bool isNULL)
{ {
fisNULL = isNULL; fisNULL = isNULL;
} }
/** @brief set the fIsFromCol flag /** @brief set the fIsFromCol flag
*/ */
void set_isFromCol( bool isFromCol) void set_isFromCol(bool isFromCol)
{ {
fIsFromCol = isFromCol; fIsFromCol = isFromCol;
} }
/** @brief set the fFuncScale /** @brief set the fFuncScale
*/ */
void set_funcScale( uint32_t funcScale) void set_funcScale(uint32_t funcScale)
{ {
fFuncScale = funcScale; fFuncScale = funcScale;
} }
void set_Data ( std::string data) void set_Data(std::string data)
{ {
fData = data; fData = data;
} }
void set_DataVector ( std::vector<std::string>& dataVec) void set_DataVector(std::vector<std::string>& dataVec)
{ {
fColValuesList = dataVec; fColValuesList = dataVec;
} }
protected: protected:
private:
private:
std::string fName; std::string fName;
std::string fData; std::string fData;
std::vector<std::string> fColValuesList; std::vector<std::string> fColValuesList;
bool fisNULL; bool fisNULL;
bool fIsFromCol; bool fIsFromCol;
uint32_t fFuncScale; uint32_t fFuncScale;
}; };
/** @brief a vector of DMLColumns /** @brief a vector of DMLColumns
*/ */
typedef std::vector<DMLColumn*>ColumnList; typedef std::vector<DMLColumn*> ColumnList;
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -16,24 +16,20 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dmlobject.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dmlobject.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "dmlobject.h" #include "dmlobject.h"
namespace dmlpackage namespace dmlpackage
{ {
DMLObject::DMLObject() DMLObject::DMLObject()
{ {
} }
DMLObject::~DMLObject() DMLObject::~DMLObject()
{ {
} }
} // namespace dmlpackage } // namespace dmlpackage

View File

@ -16,17 +16,15 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dmlobject.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dmlobject.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
#include <string> #include <string>
#include"bytestream.h" #include "bytestream.h"
namespace dmlpackage namespace dmlpackage
{ {
@ -36,9 +34,7 @@ namespace dmlpackage
*/ */
class DMLObject class DMLObject
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
DMLObject(); DMLObject();
@ -59,12 +55,8 @@ public:
*/ */
virtual int write(messageqcpp::ByteStream& bytestream) = 0; virtual int write(messageqcpp::ByteStream& bytestream) = 0;
protected: protected:
private:
private:
}; };
} } // namespace dmlpackage

View File

@ -27,10 +27,9 @@
namespace dmlpackage namespace dmlpackage
{ {
#define DML_DEBUG 0 // debug flag 0 for off, 1 for on #define DML_DEBUG 0 // debug flag 0 for off, 1 for on
const std::string nullValue = "nvl"; const std::string nullValue = "nvl";
//const size_t maxThreads = 100; // const size_t maxThreads = 100;
//const size_t queueSize = 200; // const size_t queueSize = 200;
} // namespace dmlpackage } // namespace dmlpackage

View File

@ -54,9 +54,9 @@ valbuf_t get_valbuffer(void);
void free_copybuffer(); void free_copybuffer();
void set_defaultSchema(std::string schema); void set_defaultSchema(std::string schema);
DMLParser::DMLParser() : DMLParser::DMLParser() : fStatus(-1), fDebug(false)
fStatus(-1), fDebug(false) {
{} }
DMLParser::~DMLParser() DMLParser::~DMLParser()
{ {
@ -107,7 +107,6 @@ const ParseTree& DMLParser::getParseTree()
} }
return fParseTree; return fParseTree;
} }
bool DMLParser::good() bool DMLParser::good()
@ -120,9 +119,9 @@ void DMLParser::setDefaultSchema(std::string schema)
set_defaultSchema(schema); set_defaultSchema(schema);
} }
DMLFileParser::DMLFileParser() DMLFileParser::DMLFileParser() : DMLParser()
: DMLParser() {
{} }
int DMLFileParser::parse(const string& fileName) int DMLFileParser::parse(const string& fileName)
{ {
@ -157,15 +156,14 @@ int DMLFileParser::parse(const string& fileName)
dmlbuf[rcount] = 0; dmlbuf[rcount] = 0;
// cout << endl << fileName << "(" << rcount << ")" << endl; // cout << endl << fileName << "(" << rcount << ")" << endl;
//cout << "-----------------------------" << endl; // cout << "-----------------------------" << endl;
//cout << dmlbuf << endl; // cout << dmlbuf << endl;
return DMLParser::parse(dmlbuf); return DMLParser::parse(dmlbuf);
} }
void end_sql(void) void end_sql(void)
{ {
} /* end_sql */ } /* end_sql */
} // dmlpackage } // namespace dmlpackage

View File

@ -32,7 +32,6 @@ namespace dmlpackage
{ {
typedef std::vector<char*> valbuf_t; typedef std::vector<char*> valbuf_t;
typedef SqlStatementList ParseTree; typedef SqlStatementList ParseTree;
// instance data for the parser // instance data for the parser
@ -50,7 +49,7 @@ struct scan_data
*/ */
class DMLParser class DMLParser
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
DMLParser(); DMLParser();
@ -80,15 +79,14 @@ public:
*/ */
void setDebug(bool debug); void setDebug(bool debug);
protected: protected:
ParseTree fParseTree; ParseTree fParseTree;
int fStatus; int fStatus;
bool fDebug; bool fDebug;
void* scanner; // yyscan_t * needed for re-entrant flex scanner void* scanner; // yyscan_t * needed for re-entrant flex scanner
scan_data scanData; scan_data scanData;
private: private:
}; };
/** @brief specialization of the DMLParser class /** @brief specialization of the DMLParser class
@ -97,7 +95,7 @@ private:
*/ */
class DMLFileParser : public DMLParser class DMLFileParser : public DMLParser
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
DMLFileParser(); DMLFileParser();
@ -110,9 +108,8 @@ public:
*/ */
int parse(const std::string& fileName); int parse(const std::string& fileName);
protected: protected:
private:
private:
}; };
} } // namespace dmlpackage

View File

@ -58,10 +58,8 @@ SqlStatementList::~SqlStatementList()
/** SqlStatement /** SqlStatement
*/ */
SqlStatement::SqlStatement() SqlStatement::SqlStatement() : fNamePtr(0)
: fNamePtr(0)
{ {
} }
SqlStatement::~SqlStatement() SqlStatement::~SqlStatement()
@ -97,10 +95,8 @@ std::string SqlStatement::getTableName() const
/** InsertSqlStatement /** InsertSqlStatement
*/ */
InsertSqlStatement::InsertSqlStatement() InsertSqlStatement::InsertSqlStatement() : fValuesOrQueryPtr(0)
: fValuesOrQueryPtr(0)
{ {
} }
InsertSqlStatement::InsertSqlStatement(TableName* tableNamePtr, ValuesOrQuery* valsOrQueryPtr) InsertSqlStatement::InsertSqlStatement(TableName* tableNamePtr, ValuesOrQuery* valsOrQueryPtr)
@ -128,7 +124,7 @@ ostream& InsertSqlStatement::put(ostream& os) const
{ {
os << "Insert " << endl; os << "Insert " << endl;
if (0 != fNamePtr ) if (0 != fNamePtr)
{ {
fNamePtr->put(os); fNamePtr->put(os);
} }
@ -140,10 +136,9 @@ ostream& InsertSqlStatement::put(ostream& os) const
os << *itr << endl; os << *itr << endl;
} }
if (0 != fValuesOrQueryPtr ) if (0 != fValuesOrQueryPtr)
{ {
fValuesOrQueryPtr->put(os); fValuesOrQueryPtr->put(os);
} }
return os; return os;
@ -163,16 +158,13 @@ string InsertSqlStatement::getQueryString() const
/** UpdateSqlStatement /** UpdateSqlStatement
*/ */
UpdateSqlStatement::UpdateSqlStatement() UpdateSqlStatement::UpdateSqlStatement() : fColAssignmentListPtr(0), fWhereClausePtr(0)
: fColAssignmentListPtr(0), fWhereClausePtr(0)
{ {
} }
UpdateSqlStatement::UpdateSqlStatement(TableName* tableNamePtr, UpdateSqlStatement::UpdateSqlStatement(TableName* tableNamePtr, ColumnAssignmentList* colAssignmentListPtr,
ColumnAssignmentList* colAssignmentListPtr, WhereClause* whereClausePtr /*=0*/) WhereClause* whereClausePtr /*=0*/)
: fColAssignmentListPtr(colAssignmentListPtr), : fColAssignmentListPtr(colAssignmentListPtr), fWhereClausePtr(whereClausePtr)
fWhereClausePtr(whereClausePtr)
{ {
fNamePtr = tableNamePtr; fNamePtr = tableNamePtr;
} }
@ -261,17 +253,14 @@ string UpdateSqlStatement::getQueryString() const
/** DeleteSqlStatement /** DeleteSqlStatement
*/ */
DeleteSqlStatement::DeleteSqlStatement() DeleteSqlStatement::DeleteSqlStatement() : fWhereClausePtr(0)
: fWhereClausePtr(0)
{ {
} }
DeleteSqlStatement::DeleteSqlStatement(TableName* tableNamePtr, WhereClause* whereClausePtr /*=0*/) DeleteSqlStatement::DeleteSqlStatement(TableName* tableNamePtr, WhereClause* whereClausePtr /*=0*/)
: fWhereClausePtr(whereClausePtr) : fWhereClausePtr(whereClausePtr)
{ {
fNamePtr = tableNamePtr; fNamePtr = tableNamePtr;
} }
DeleteSqlStatement::~DeleteSqlStatement() DeleteSqlStatement::~DeleteSqlStatement()
@ -280,7 +269,6 @@ DeleteSqlStatement::~DeleteSqlStatement()
{ {
delete fWhereClausePtr; delete fWhereClausePtr;
} }
} }
ostream& DeleteSqlStatement::put(ostream& os) const ostream& DeleteSqlStatement::put(ostream& os) const
@ -314,10 +302,8 @@ string DeleteSqlStatement::getQueryString() const
/** CommandSqlStatement /** CommandSqlStatement
*/ */
CommandSqlStatement::CommandSqlStatement(std::string command) CommandSqlStatement::CommandSqlStatement(std::string command) : fCommandText(command)
: fCommandText(command)
{ {
} }
ostream& CommandSqlStatement::put(ostream& os) const ostream& CommandSqlStatement::put(ostream& os) const
@ -336,13 +322,11 @@ string CommandSqlStatement::getQueryString() const
*/ */
TableName::TableName() TableName::TableName()
{ {
} }
TableName::TableName(char* name) TableName::TableName(char* name)
{ {
fName = name; fName = name;
} }
TableName::TableName(char* schema, char* name) TableName::TableName(char* schema, char* name)
@ -383,13 +367,11 @@ string ColumnAssignment::getColumnAssignmentString() const
/** ValuesOrQuery /** ValuesOrQuery
*/ */
ValuesOrQuery::ValuesOrQuery() ValuesOrQuery::ValuesOrQuery() : fQuerySpecPtr(0)
: fQuerySpecPtr(0)
{ {
} }
ValuesOrQuery::ValuesOrQuery(ValuesList* valuesPtr) ValuesOrQuery::ValuesOrQuery(ValuesList* valuesPtr) : fQuerySpecPtr(0)
: fQuerySpecPtr(0)
{ {
fValuesList = *valuesPtr; fValuesList = *valuesPtr;
delete valuesPtr; delete valuesPtr;
@ -410,7 +392,7 @@ ostream& ValuesOrQuery::put(ostream& os) const
{ {
ValuesList::const_iterator iter = fValuesList.begin(); ValuesList::const_iterator iter = fValuesList.begin();
while ( iter != fValuesList.end() ) while (iter != fValuesList.end())
{ {
os << *iter << endl; os << *iter << endl;
++iter; ++iter;
@ -438,19 +420,16 @@ string ValuesOrQuery::getQueryString() const
/** QuerySpec /** QuerySpec
*/ */
QuerySpec::QuerySpec() QuerySpec::QuerySpec() : fSelectFilterPtr(0), fTableExpressionPtr(0)
: fSelectFilterPtr(0), fTableExpressionPtr(0)
{ {
} }
QuerySpec::QuerySpec(SelectFilter* selectFilter, TableExpression* tableExpression) QuerySpec::QuerySpec(SelectFilter* selectFilter, TableExpression* tableExpression)
: fSelectFilterPtr(selectFilter), fTableExpressionPtr(tableExpression) : fSelectFilterPtr(selectFilter), fTableExpressionPtr(tableExpression)
{ {
} }
QuerySpec::QuerySpec(SelectFilter* selectFilter, TableExpression* tableExpression, QuerySpec::QuerySpec(SelectFilter* selectFilter, TableExpression* tableExpression, char* allOrDistinct)
char* allOrDistinct)
: fSelectFilterPtr(selectFilter), fTableExpressionPtr(tableExpression) : fSelectFilterPtr(selectFilter), fTableExpressionPtr(tableExpression)
{ {
fOptionAllOrDistinct = allOrDistinct; fOptionAllOrDistinct = allOrDistinct;
@ -511,8 +490,7 @@ string QuerySpec::getQueryString() const
/** SelectFilter /** SelectFilter
*/ */
SelectFilter::SelectFilter() SelectFilter::SelectFilter() : fColumnList(0)
: fColumnList(0)
{ {
} }
@ -525,7 +503,6 @@ SelectFilter::SelectFilter(ColumnNameList* columnListPtr)
SelectFilter::~SelectFilter() SelectFilter::~SelectFilter()
{ {
} }
ostream& SelectFilter::put(ostream& os) const ostream& SelectFilter::put(ostream& os) const
@ -533,7 +510,7 @@ ostream& SelectFilter::put(ostream& os) const
os << "SELECT" << endl; os << "SELECT" << endl;
ColumnNameList::const_iterator iter = fColumnList.begin(); ColumnNameList::const_iterator iter = fColumnList.begin();
while ( iter != fColumnList.end() ) while (iter != fColumnList.end())
{ {
os << *iter << endl; os << *iter << endl;
++iter; ++iter;
@ -550,7 +527,7 @@ string SelectFilter::getSelectString() const
std::string select_filter = "SELECT "; std::string select_filter = "SELECT ";
ColumnNameList::const_iterator iter = fColumnList.begin(); ColumnNameList::const_iterator iter = fColumnList.begin();
while ( iter != fColumnList.end() ) while (iter != fColumnList.end())
{ {
select_filter += *iter; select_filter += *iter;
++iter; ++iter;
@ -567,19 +544,17 @@ string SelectFilter::getSelectString() const
/** TableExpression /** TableExpression
*/ */
TableExpression::TableExpression() TableExpression::TableExpression() : fFromClausePtr(0), fWhereClausePtr(0), fGroupByPtr(0), fHavingPtr(0)
: fFromClausePtr(0), fWhereClausePtr(0),
fGroupByPtr(0), fHavingPtr(0)
{ {
} }
TableExpression::TableExpression(FromClause* fromClausePtr, WhereClause* whereClausePtr, TableExpression::TableExpression(FromClause* fromClausePtr, WhereClause* whereClausePtr,
GroupByClause* groupByPtr, HavingClause* havingPtr) GroupByClause* groupByPtr, HavingClause* havingPtr)
: fFromClausePtr(fromClausePtr), fWhereClausePtr(whereClausePtr), : fFromClausePtr(fromClausePtr)
fGroupByPtr(groupByPtr), fHavingPtr(havingPtr) , fWhereClausePtr(whereClausePtr)
, fGroupByPtr(groupByPtr)
, fHavingPtr(havingPtr)
{ {
} }
TableExpression::~TableExpression() TableExpression::~TableExpression()
@ -595,7 +570,6 @@ TableExpression::~TableExpression()
if (0 != fHavingPtr) if (0 != fHavingPtr)
delete fHavingPtr; delete fHavingPtr;
} }
ostream& TableExpression::put(ostream& os) const ostream& TableExpression::put(ostream& os) const
@ -655,8 +629,7 @@ string TableExpression::getTableExpressionString() const
/** FromClause /** FromClause
*/ */
FromClause::FromClause() FromClause::FromClause() : fTableListPtr(0)
: fTableListPtr(0)
{ {
} }
@ -671,7 +644,7 @@ FromClause::~FromClause()
{ {
TableNameList::iterator iter = fTableListPtr->begin(); TableNameList::iterator iter = fTableListPtr->begin();
while ( iter != fTableListPtr->end() ) while (iter != fTableListPtr->end())
{ {
TableName* tableNamePtr = *iter; TableName* tableNamePtr = *iter;
delete tableNamePtr; delete tableNamePtr;
@ -691,7 +664,7 @@ ostream& FromClause::put(ostream& os) const
{ {
TableNameList::const_iterator iter = fTableListPtr->begin(); TableNameList::const_iterator iter = fTableListPtr->begin();
while ( iter != fTableListPtr->end() ) while (iter != fTableListPtr->end())
{ {
TableName* tableNamePtr = *iter; TableName* tableNamePtr = *iter;
tableNamePtr->put(os); tableNamePtr->put(os);
@ -734,10 +707,8 @@ string FromClause::getFromClauseString() const
/** WhereClause /** WhereClause
*/ */
WhereClause::WhereClause() WhereClause::WhereClause() : fSearchConditionPtr(0)
: fSearchConditionPtr(0)
{ {
} }
WhereClause::~WhereClause() WhereClause::~WhereClause()
@ -775,8 +746,7 @@ string WhereClause::getWhereClauseString() const
/** HavingClause /** HavingClause
*/ */
HavingClause::HavingClause() HavingClause::HavingClause() : fSearchConditionPtr(0)
: fSearchConditionPtr(0)
{ {
} }
@ -815,8 +785,7 @@ string HavingClause::getHavingClauseString() const
/** GroupByClause /** GroupByClause
*/ */
GroupByClause::GroupByClause() GroupByClause::GroupByClause() : fColumnNamesListPtr(0)
: fColumnNamesListPtr(0)
{ {
} }
@ -880,9 +849,7 @@ ostream& Escape::put(ostream& os) const
/** SearchCondition /** SearchCondition
*/ */
SearchCondition::SearchCondition() SearchCondition::SearchCondition() : fPredicatePtr(0), fLHSearchConditionPtr(0), fRHSearchConditionPtr(0)
: fPredicatePtr(0), fLHSearchConditionPtr(0),
fRHSearchConditionPtr(0)
{ {
} }
@ -902,7 +869,6 @@ SearchCondition::~SearchCondition()
{ {
delete fRHSearchConditionPtr; delete fRHSearchConditionPtr;
} }
} }
ostream& SearchCondition::put(ostream& os) const ostream& SearchCondition::put(ostream& os) const
@ -953,8 +919,7 @@ string SearchCondition::getSearchConditionString() const
/** ExistanceTestPredicate /** ExistanceTestPredicate
*/ */
ExistanceTestPredicate::ExistanceTestPredicate() ExistanceTestPredicate::ExistanceTestPredicate() : Predicate(EXIST_PREDICATE), fSubQuerySpecPtr(0)
: Predicate(EXIST_PREDICATE), fSubQuerySpecPtr(0)
{ {
} }
@ -968,14 +933,14 @@ ExistanceTestPredicate::~ExistanceTestPredicate()
ostream& ExistanceTestPredicate::put(ostream& os) const ostream& ExistanceTestPredicate::put(ostream& os) const
{ {
//cout << "EXISTS" << endl; // cout << "EXISTS" << endl;
//cout << "(" << endl; // cout << "(" << endl;
if (0 != fSubQuerySpecPtr) if (0 != fSubQuerySpecPtr)
{ {
fSubQuerySpecPtr->put(os); fSubQuerySpecPtr->put(os);
} }
//cout << ")" << endl; // cout << ")" << endl;
return os; return os;
} }
@ -996,10 +961,8 @@ string ExistanceTestPredicate::getPredicateString() const
/** AllOrAnyPredicate /** AllOrAnyPredicate
*/ */
AllOrAnyPredicate::AllOrAnyPredicate() AllOrAnyPredicate::AllOrAnyPredicate() : Predicate(ALLORANY_PREDICATE), fSubQuerySpecPtr(0)
: Predicate(ALLORANY_PREDICATE), fSubQuerySpecPtr(0)
{ {
} }
AllOrAnyPredicate::~AllOrAnyPredicate() AllOrAnyPredicate::~AllOrAnyPredicate()
@ -1042,10 +1005,8 @@ string AllOrAnyPredicate::getPredicateString() const
/** InPredicate /** InPredicate
*/ */
InPredicate::InPredicate() InPredicate::InPredicate() : Predicate(IN_PREDICATE), fSubQuerySpecPtr(0)
: Predicate(IN_PREDICATE), fSubQuerySpecPtr(0)
{ {
} }
InPredicate::~InPredicate() InPredicate::~InPredicate()
@ -1111,14 +1072,12 @@ string InPredicate::getPredicateString() const
/** NullTestPredicate /** NullTestPredicate
*/ */
NullTestPredicate::NullTestPredicate() NullTestPredicate::NullTestPredicate() : Predicate(NULLTEST_PREDICATE)
: Predicate(NULLTEST_PREDICATE)
{ {
} }
NullTestPredicate::~NullTestPredicate() NullTestPredicate::~NullTestPredicate()
{ {
} }
ostream& NullTestPredicate::put(ostream& os) const ostream& NullTestPredicate::put(ostream& os) const
@ -1140,10 +1099,8 @@ string NullTestPredicate::getPredicateString() const
/** LikePredicate /** LikePredicate
*/ */
LikePredicate::LikePredicate() LikePredicate::LikePredicate() : Predicate(LIKE_PREDICATE), fOptionalEscapePtr(0)
: Predicate(LIKE_PREDICATE), fOptionalEscapePtr(0)
{ {
} }
LikePredicate::~LikePredicate() LikePredicate::~LikePredicate()
@ -1180,19 +1137,16 @@ string LikePredicate::getPredicateString() const
/** BetweenPredicate /** BetweenPredicate
*/ */
BetweenPredicate::BetweenPredicate() BetweenPredicate::BetweenPredicate() : Predicate(BETWEEN_PREDICATE)
: Predicate(BETWEEN_PREDICATE)
{ {
} }
BetweenPredicate::~BetweenPredicate() BetweenPredicate::~BetweenPredicate()
{ {
} }
ostream& BetweenPredicate::put(ostream& os) const ostream& BetweenPredicate::put(ostream& os) const
{ {
os << fLHScalarExpression << endl; os << fLHScalarExpression << endl;
os << fOperator1 << endl; os << fOperator1 << endl;
os << fRH1ScalarExpression << endl; os << fRH1ScalarExpression << endl;
@ -1219,8 +1173,7 @@ string BetweenPredicate::getPredicateString() const
/** ComparisonPredicate /** ComparisonPredicate
*/ */
ComparisonPredicate::ComparisonPredicate() ComparisonPredicate::ComparisonPredicate() : Predicate(COMPARE_PREDICATE), fSubQuerySpec(0)
: Predicate(COMPARE_PREDICATE), fSubQuerySpec(0)
{ {
} }
@ -1261,20 +1214,16 @@ string ComparisonPredicate::getPredicateString() const
/** Predicate /** Predicate
*/ */
Predicate::Predicate() Predicate::Predicate() : fPredicateType(INVALID_PREDICATE)
: fPredicateType(INVALID_PREDICATE)
{ {
} }
Predicate::Predicate(PREDICATE_TYPE predicateType) Predicate::Predicate(PREDICATE_TYPE predicateType) : fPredicateType(predicateType)
: fPredicateType(predicateType)
{ {
} }
Predicate::~Predicate() Predicate::~Predicate()
{ {
} }
ostream& Predicate::put(ostream& os) const ostream& Predicate::put(ostream& os) const
@ -1289,4 +1238,4 @@ string Predicate::getPredicateString() const
return predicate; return predicate;
} }
} //namespace dmlpackage } // namespace dmlpackage

View File

@ -33,7 +33,6 @@
namespace dmlpackage namespace dmlpackage
{ {
class DeleteSqlStatement; class DeleteSqlStatement;
class UpdateSqlStatement; class UpdateSqlStatement;
class InsertSqlStatement; class InsertSqlStatement;
@ -111,7 +110,7 @@ enum DML_TYPE
*/ */
class SqlStatement class SqlStatement
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
SqlStatement(); SqlStatement();
@ -144,7 +143,6 @@ public:
virtual std::string getTableName() const; virtual std::string getTableName() const;
TableName* fNamePtr; TableName* fNamePtr;
}; };
/** @brief Collects SqlStatements so that we can support the /** @brief Collects SqlStatements so that we can support the
@ -156,11 +154,12 @@ public:
*/ */
class SqlStatementList class SqlStatementList
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
SqlStatementList() SqlStatementList()
{} {
}
/** @brief dtor /** @brief dtor
*/ */
@ -184,9 +183,8 @@ public:
std::vector<SqlStatement*> fList; std::vector<SqlStatement*> fList;
std::string fSqlText; std::string fSqlText;
private: private:
SqlStatementList(const SqlStatementList& x); SqlStatementList(const SqlStatementList& x);
}; };
/** @brief The representation of a parsed /** @brief The representation of a parsed
@ -197,7 +195,7 @@ private:
*/ */
class InsertSqlStatement : public SqlStatement class InsertSqlStatement : public SqlStatement
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
InsertSqlStatement(); InsertSqlStatement();
@ -215,8 +213,7 @@ public:
* @param columnNamesPtr pointer to ColumnNamesList object * @param columnNamesPtr pointer to ColumnNamesList object
* @param valsOrQueryPtr pointer to ValuesOrQueryObject * @param valsOrQueryPtr pointer to ValuesOrQueryObject
*/ */
InsertSqlStatement(TableName* tableNamePtr, ColumnNameList* columnNamesPtr, InsertSqlStatement(TableName* tableNamePtr, ColumnNameList* columnNamesPtr, ValuesOrQuery* valsOrQueryPtr);
ValuesOrQuery* valsOrQueryPtr);
/** @brief dtor /** @brief dtor
*/ */
@ -249,7 +246,7 @@ public:
*/ */
class UpdateSqlStatement : public SqlStatement class UpdateSqlStatement : public SqlStatement
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
UpdateSqlStatement(); UpdateSqlStatement();
@ -296,7 +293,7 @@ public:
*/ */
class DeleteSqlStatement : public SqlStatement class DeleteSqlStatement : public SqlStatement
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
DeleteSqlStatement(); DeleteSqlStatement();
@ -343,7 +340,7 @@ public:
*/ */
class CommandSqlStatement : public SqlStatement class CommandSqlStatement : public SqlStatement
{ {
public: public:
/** @brief ctor /** @brief ctor
* *
* @param command the COMMIT or ROLLBACK string * @param command the COMMIT or ROLLBACK string
@ -373,7 +370,7 @@ public:
*/ */
class TableName class TableName
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
TableName(); TableName();
@ -407,14 +404,15 @@ public:
*/ */
class ColumnAssignment class ColumnAssignment
{ {
public: public:
explicit ColumnAssignment( explicit ColumnAssignment(std::string const& column, std::string const& op = "=",
std::string const& column, std::string const& expr = "")
std::string const& op = "=", : fColumn(column)
std::string const& expr = "") : , fOperator(op)
fColumn(column), fOperator(op), fScalarExpression(expr), , fScalarExpression(expr)
fFromCol(false), fFuncScale(0), fIsNull(false) , fFromCol(false)
{}; , fFuncScale(0)
, fIsNull(false){};
/** @brief dump to stdout /** @brief dump to stdout
*/ */
@ -441,7 +439,7 @@ public:
*/ */
class ValuesOrQuery class ValuesOrQuery
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
ValuesOrQuery(); ValuesOrQuery();
@ -483,7 +481,7 @@ public:
*/ */
class SelectFilter class SelectFilter
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
SelectFilter(); SelectFilter();
@ -516,7 +514,7 @@ public:
*/ */
class FromClause class FromClause
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
FromClause(); FromClause();
@ -549,7 +547,7 @@ public:
*/ */
class WhereClause class WhereClause
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
WhereClause(); WhereClause();
@ -567,7 +565,6 @@ public:
std::string getWhereClauseString() const; std::string getWhereClauseString() const;
SearchCondition* fSearchConditionPtr; SearchCondition* fSearchConditionPtr;
}; };
/** @brief Stores a GROUP BY clause /** @brief Stores a GROUP BY clause
@ -578,7 +575,7 @@ public:
*/ */
class GroupByClause class GroupByClause
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
GroupByClause(); GroupByClause();
@ -606,7 +603,7 @@ public:
*/ */
class HavingClause class HavingClause
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
HavingClause(); HavingClause();
@ -635,7 +632,7 @@ public:
*/ */
class Escape class Escape
{ {
public: public:
/** @brief dump to stdout /** @brief dump to stdout
*/ */
std::ostream& put(std::ostream& os) const; std::ostream& put(std::ostream& os) const;
@ -656,7 +653,7 @@ public:
*/ */
class Predicate class Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
Predicate(); Predicate();
@ -691,7 +688,7 @@ public:
*/ */
class ComparisonPredicate : public Predicate class ComparisonPredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
ComparisonPredicate(); ComparisonPredicate();
@ -726,7 +723,7 @@ public:
*/ */
class BetweenPredicate : public Predicate class BetweenPredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
BetweenPredicate(); BetweenPredicate();
@ -761,7 +758,7 @@ public:
*/ */
class LikePredicate : public Predicate class LikePredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
LikePredicate(); LikePredicate();
@ -795,7 +792,7 @@ public:
*/ */
class NullTestPredicate : public Predicate class NullTestPredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
NullTestPredicate(); NullTestPredicate();
@ -829,7 +826,7 @@ public:
*/ */
class InPredicate : public Predicate class InPredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
InPredicate(); InPredicate();
@ -862,7 +859,7 @@ public:
*/ */
class AllOrAnyPredicate : public Predicate class AllOrAnyPredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
AllOrAnyPredicate(); AllOrAnyPredicate();
@ -895,7 +892,7 @@ public:
*/ */
class ExistanceTestPredicate : public Predicate class ExistanceTestPredicate : public Predicate
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
ExistanceTestPredicate(); ExistanceTestPredicate();
@ -928,7 +925,7 @@ public:
*/ */
class SearchCondition class SearchCondition
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
SearchCondition(); SearchCondition();
@ -964,7 +961,7 @@ public:
*/ */
class TableExpression class TableExpression
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
TableExpression(); TableExpression();
@ -976,8 +973,8 @@ public:
* @param groupByPtr pointer to a GroupByClause object * @param groupByPtr pointer to a GroupByClause object
* @param havingPtr pointer to a HavingClause object * @param havingPtr pointer to a HavingClause object
*/ */
TableExpression(FromClause* fromClausePtr, WhereClause* whereClausePtr, TableExpression(FromClause* fromClausePtr, WhereClause* whereClausePtr, GroupByClause* groupByPtr,
GroupByClause* groupByPtr, HavingClause* havingPtr); HavingClause* havingPtr);
/** @brief dtor /** @brief dtor
*/ */
@ -1006,7 +1003,7 @@ public:
*/ */
class QuerySpec class QuerySpec
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
QuerySpec(); QuerySpec();
@ -1024,8 +1021,7 @@ public:
* @param tableExpression pointer to a TableExpression object * @param tableExpression pointer to a TableExpression object
* @param allOrDistinct pointer to a ALL or DISTINCT string * @param allOrDistinct pointer to a ALL or DISTINCT string
*/ */
QuerySpec(SelectFilter* selectFilter, TableExpression* tableExpression, QuerySpec(SelectFilter* selectFilter, TableExpression* tableExpression, char* allOrDistinct);
char* allOrDistinct);
/** @brief dtor /** @brief dtor
*/ */

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dmltable.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dmltable.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "dmltable.h" #include "dmltable.h"
using namespace std; using namespace std;
@ -27,11 +27,11 @@ using namespace std;
namespace dmlpackage namespace dmlpackage
{ {
DMLTable::DMLTable() DMLTable::DMLTable()
{} {
}
DMLTable::~DMLTable() DMLTable::~DMLTable()
{ {
try try
{ {
RowList::iterator it = fRows.begin(); RowList::iterator it = fRows.begin();
@ -46,7 +46,6 @@ DMLTable::~DMLTable()
{ {
cout << "failed to delete the table rows" << endl; cout << "failed to delete the table rows" << endl;
} }
} }
int DMLTable::read(messageqcpp::ByteStream& bytestream) int DMLTable::read(messageqcpp::ByteStream& bytestream)
@ -97,13 +96,13 @@ void DMLTable::readRowData(messageqcpp::ByteStream& bytestream)
int DMLTable::write(messageqcpp::ByteStream& bytestream) int DMLTable::write(messageqcpp::ByteStream& bytestream)
{ {
int retval = 1; int retval = 1;
//write table name and schma name to the bytestream // write table name and schma name to the bytestream
bytestream << fName; bytestream << fName;
bytestream << fSchema; bytestream << fSchema;
messageqcpp::ByteStream::quadbyte rowNum; messageqcpp::ByteStream::quadbyte rowNum;
rowNum = fRows.size(); rowNum = fRows.size();
bytestream << rowNum; bytestream << rowNum;
//write the row list // write the row list
RowList::iterator rowListPtr; RowList::iterator rowListPtr;
rowListPtr = fRows.begin(); rowListPtr = fRows.begin();
@ -116,4 +115,3 @@ int DMLTable::write(messageqcpp::ByteStream& bytestream)
} }
} // namespace dmlpackage } // namespace dmlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: dmltable.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: dmltable.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
@ -37,9 +37,7 @@ namespace dmlpackage
*/ */
class DMLTable : public DMLObject class DMLTable : public DMLObject
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
DMLTable(); DMLTable();
@ -57,7 +55,7 @@ public:
/** @brief set the schema name /** @brief set the schema name
*/ */
inline void set_SchemaName( std::string& sName ) inline void set_SchemaName(std::string& sName)
{ {
fSchema = sName; fSchema = sName;
} }
@ -71,7 +69,7 @@ public:
/** @brief set the table name /** @brief set the table name
*/ */
inline void set_TableName( std::string& tName ) inline void set_TableName(std::string& tName)
{ {
fName = tName; fName = tName;
} }
@ -89,31 +87,26 @@ public:
*/ */
int read(messageqcpp::ByteStream& bytestream); int read(messageqcpp::ByteStream& bytestream);
/** @brief read a DMLTable metadata from a ByteStream /** @brief read a DMLTable metadata from a ByteStream
* *
* @param bytestream the ByteStream to read from * @param bytestream the ByteStream to read from
*/ */
void readMetaData(messageqcpp::ByteStream& bytestream); void readMetaData(messageqcpp::ByteStream& bytestream);
/** @brief read a DMLTable row data from a ByteStream /** @brief read a DMLTable row data from a ByteStream
* *
* @param bytestream the ByteStream to read from * @param bytestream the ByteStream to read from
*/ */
void readRowData(messageqcpp::ByteStream& bytestream); void readRowData(messageqcpp::ByteStream& bytestream);
/** @brief write a DMLTable to a ByteStream /** @brief write a DMLTable to a ByteStream
* *
* @param bytestream the ByteStream to write to * @param bytestream the ByteStream to write to
*/ */
int write(messageqcpp::ByteStream& bytestream); int write(messageqcpp::ByteStream& bytestream);
protected:
protected: private:
private:
std::string fName; std::string fName;
RowList fRows; RowList fRows;
std::string fSchema; std::string fSchema;
@ -123,5 +116,3 @@ private:
}; };
} // namespace dmlpackage } // namespace dmlpackage

View File

@ -35,25 +35,26 @@ int main(int argc, char* argv[])
string sqlfile; string sqlfile;
int count; int count;
po::options_description desc ("Allowed options"); po::options_description desc("Allowed options");
desc.add_options () desc.add_options()("help", "produce help message")(
("help", "produce help message") "bisond",
("bisond", /* po::value <string>(),*/ "Have bison produce debug output") /* po::value <string>(),*/ "Have bison produce debug output")("count", po::value<int>(),
("count", po::value <int>(), "number of runs") "number of runs")("sql",
("sql", po::value < string > (), "sql file"); po::value<string>(),
"sql file");
po::variables_map vm; po::variables_map vm;
po::store (po::parse_command_line (argc, argv, desc), vm); po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify (vm); po::notify(vm);
if (vm.count ("sql")) if (vm.count("sql"))
sqlfile = vm["sql"].as <string> (); sqlfile = vm["sql"].as<string>();
if (vm.count("count")) if (vm.count("count"))
count = vm["count"].as<int>(); count = vm["count"].as<int>();
DMLFileParser parser; DMLFileParser parser;
if (vm.count ("bisond")) if (vm.count("bisond"))
parser.setDebug(true); parser.setDebug(true);
parser.parse(sqlfile); parser.parse(sqlfile);
@ -63,7 +64,8 @@ int main(int argc, char* argv[])
const ParseTree& ptree = parser.getParseTree(); const ParseTree& ptree = parser.getParseTree();
cout << "Parser succeeded." << endl; cout << "Parser succeeded." << endl;
cout << ptree.fList.size() << " " << "SQL statements" << endl; cout << ptree.fList.size() << " "
<< "SQL statements" << endl;
cout << ptree.fSqlText << endl; cout << ptree.fSqlText << endl;
cout << ptree; cout << ptree;

View File

@ -35,17 +35,19 @@ using namespace std;
namespace dmlpackage namespace dmlpackage
{ {
InsertDMLPackage::InsertDMLPackage() InsertDMLPackage::InsertDMLPackage()
{} {
}
InsertDMLPackage::InsertDMLPackage( std::string schemaName, std::string tableName, InsertDMLPackage::InsertDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID ) int sessionID)
: CalpontDMLPackage( schemaName, tableName, dmlStatement, sessionID ) : CalpontDMLPackage(schemaName, tableName, dmlStatement, sessionID)
{} {
}
InsertDMLPackage::~InsertDMLPackage() InsertDMLPackage::~InsertDMLPackage()
{} {
}
int InsertDMLPackage::write(messageqcpp::ByteStream& bytestream) int InsertDMLPackage::write(messageqcpp::ByteStream& bytestream)
{ {
@ -164,40 +166,40 @@ int InsertDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows
for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
{ {
dataList.push_back(StripLeadingWhitespace(*tok_iter)); dataList.push_back(StripLeadingWhitespace(*tok_iter));
} }
int n = 0; int n = 0;
for (int i = 0; i < rows; i++) for (int i = 0; i < rows; i++)
{ {
//get a new row // get a new row
Row* aRowPtr = new Row(); Row* aRowPtr = new Row();
std::string colName; std::string colName;
std::string colValue; std::string colValue;
for (int j = 0; j < columns; j++) for (int j = 0; j < columns; j++)
{ {
//Build a column list // Build a column list
colName = dataList[n]; colName = dataList[n];
n++; n++;
colValue = dataList[n]; colValue = dataList[n];
n++; n++;
#ifdef DML_PACKAGE_DEBUG #ifdef DML_PACKAGE_DEBUG
//cout << "The column data: " << colName << " " << colValue << endl; // cout << "The column data: " << colName << " " << colValue << endl;
#endif #endif
DMLColumn* aColumn = new DMLColumn(colName, colValue, false); DMLColumn* aColumn = new DMLColumn(colName, colValue, false);
(aRowPtr->get_ColumnList()).push_back(aColumn); (aRowPtr->get_ColumnList()).push_back(aColumn);
} }
//build a row list for a table // build a row list for a table
fTable->get_RowList().push_back(aRowPtr); fTable->get_RowList().push_back(aRowPtr);
} }
return retval; return retval;
} }
int InsertDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues ) int InsertDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap,
int columns, int rows, NullValuesBitset& nullValues)
{ {
int retval = 1; int retval = 1;
@ -208,7 +210,7 @@ int InsertDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValues
for (int j = 0; j < columns; j++) for (int j = 0; j < columns; j++)
{ {
//Build a column list // Build a column list
colName = colNameList[j]; colName = colNameList[j];
colValList = tableValuesMap[j]; colValList = tableValuesMap[j];
@ -217,7 +219,7 @@ int InsertDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValues
(aRowPtr->get_ColumnList()).push_back(aColumn); (aRowPtr->get_ColumnList()).push_back(aColumn);
} }
//build a row list for a table // build a row list for a table
fTable->get_RowList().push_back(aRowPtr); fTable->get_RowList().push_back(aRowPtr);
aRowPtr = NULL; aRowPtr = NULL;
delete aRowPtr; delete aRowPtr;
@ -226,7 +228,6 @@ int InsertDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValues
int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement) int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
{ {
int retval = 1; int retval = 1;
InsertSqlStatement& insertStmt = dynamic_cast<InsertSqlStatement&>(sqlStatement); InsertSqlStatement& insertStmt = dynamic_cast<InsertSqlStatement&>(sqlStatement);
@ -240,12 +241,10 @@ int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
// only if we don't have a select statement // only if we don't have a select statement
if (0 == insertStmt.fValuesOrQueryPtr->fQuerySpecPtr) if (0 == insertStmt.fValuesOrQueryPtr->fQuerySpecPtr)
{ {
ColumnNameList columnNameList = insertStmt.fColumnList; ColumnNameList columnNameList = insertStmt.fColumnList;
if (columnNameList.size()) if (columnNameList.size())
{ {
ValuesList valuesList = insertStmt.fValuesOrQueryPtr->fValuesList; ValuesList valuesList = insertStmt.fValuesOrQueryPtr->fValuesList;
if (columnNameList.size() != valuesList.size()) if (columnNameList.size() != valuesList.size())
@ -262,7 +261,6 @@ int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
} }
fTable->get_RowList().push_back(aRow); fTable->get_RowList().push_back(aRow);
} }
else else
{ {
@ -276,7 +274,7 @@ int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
{ {
colValue = *iter; colValue = *iter;
if ( strcasecmp(colValue.c_str(), "NULL") == 0) if (strcasecmp(colValue.c_str(), "NULL") == 0)
{ {
isNULL = true; isNULL = true;
} }
@ -293,7 +291,6 @@ int InsertDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
fTable->get_RowList().push_back(aRow); fTable->get_RowList().push_back(aRow);
} }
} }
else else
{ {

View File

@ -40,8 +40,7 @@ namespace dmlpackage
*/ */
class InsertDMLPackage : public CalpontDMLPackage class InsertDMLPackage : public CalpontDMLPackage
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT InsertDMLPackage(); EXPORT InsertDMLPackage();
@ -53,8 +52,8 @@ public:
* @param dmlStatement the dml statement * @param dmlStatement the dml statement
* @param sessionID the session id * @param sessionID the session id
*/ */
EXPORT InsertDMLPackage(std::string schemaName, std::string tableName, EXPORT InsertDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID ); int sessionID);
/** @brief dtor /** @brief dtor
*/ */
@ -99,7 +98,8 @@ public:
* @param columns number of columns in the table * @param columns number of columns in the table
* @param rows number of rows to be touched * @param rows number of rows to be touched
*/ */
EXPORT int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues); EXPORT int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns,
int rows, NullValuesBitset& nullValues);
/** @brief build a InsertDMLPackage from a InsertSqlStatement /** @brief build a InsertDMLPackage from a InsertSqlStatement
* *
@ -111,13 +111,10 @@ public:
*/ */
EXPORT void Dump(); EXPORT void Dump();
protected: protected:
private:
private:
}; };
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: mysqldmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: mysqldmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "mysqldmlstatement.h" #include "mysqldmlstatement.h"
/** /**
@ -28,4 +28,3 @@
/** /**
* Methods * Methods
*/ */

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: mysqldmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: mysqldmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
#include <string> #include <string>
@ -32,14 +32,12 @@ namespace dmlpackage
*/ */
class MySQLDMLStatement : public VendorDMLStatement class MySQLDMLStatement : public VendorDMLStatement
{ {
public:
MySQLDMLStatement() : VendorDMLStatement("", 0)
{
}
public: protected:
MySQLDMLStatement() : VendorDMLStatement("", 0) {} private:
protected:
private:
}; };
} } // namespace dmlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: oracledmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: oracledmlstatement.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include "oracledmlstatement.h" #include "oracledmlstatement.h"
/** /**
@ -28,5 +28,3 @@
/** /**
* Methods * Methods
*/ */

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: oracledmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: oracledmlstatement.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
@ -33,14 +33,12 @@ namespace dmlpackage
*/ */
class OracleDMLStatement : public VendorDMLStatement class OracleDMLStatement : public VendorDMLStatement
{ {
public:
OracleDMLStatement() : VendorDMLStatement("", 0)
{
}
public: protected:
OracleDMLStatement() : VendorDMLStatement("", 0) {} private:
protected:
private:
}; };
} } // namespace dmlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: row.cpp 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: row.cpp 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
#include <limits> #include <limits>
#define DMLPKGROW_DLLEXPORT #define DMLPKGROW_DLLEXPORT
@ -28,14 +28,13 @@
namespace dmlpackage namespace dmlpackage
{ {
Row::Row() : fRowID(std::numeric_limits<WriteEngine::RID>::max())
Row::Row() {
: fRowID(std::numeric_limits<WriteEngine::RID>::max()) }
{}
Row::~Row() Row::~Row()
{ {
for ( unsigned int i = 0; i < fColumnList.size(); i++) for (unsigned int i = 0; i < fColumnList.size(); i++)
{ {
delete fColumnList[i]; delete fColumnList[i];
} }
@ -73,7 +72,6 @@ int Row::read(messageqcpp::ByteStream& bytestream)
return retval; return retval;
} }
int Row::write(messageqcpp::ByteStream& bytestream) int Row::write(messageqcpp::ByteStream& bytestream)
{ {
int retval = 1; int retval = 1;
@ -92,11 +90,11 @@ int Row::write(messageqcpp::ByteStream& bytestream)
return retval; return retval;
} }
const DMLColumn* Row::get_ColumnAt( unsigned int index ) const const DMLColumn* Row::get_ColumnAt(unsigned int index) const
{ {
const DMLColumn* columnPtr = 0; const DMLColumn* columnPtr = 0;
if ( index < fColumnList.size() ) if (index < fColumnList.size())
{ {
columnPtr = fColumnList[index]; columnPtr = fColumnList[index];
} }
@ -105,6 +103,3 @@ const DMLColumn* Row::get_ColumnAt( unsigned int index ) const
} }
} // namespace dmlpackage } // namespace dmlpackage

View File

@ -16,10 +16,10 @@
MA 02110-1301, USA. */ MA 02110-1301, USA. */
/*********************************************************************** /***********************************************************************
* $Id: row.h 9210 2013-01-21 14:10:42Z rdempsey $ * $Id: row.h 9210 2013-01-21 14:10:42Z rdempsey $
* *
* *
***********************************************************************/ ***********************************************************************/
/** @file */ /** @file */
#pragma once #pragma once
@ -42,8 +42,7 @@ namespace dmlpackage
*/ */
class Row : public DMLObject class Row : public DMLObject
{ {
public: public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT Row(); EXPORT Row();
@ -100,22 +99,18 @@ public:
* *
* @param index the index of the column to get * @param index the index of the column to get
*/ */
EXPORT const DMLColumn* get_ColumnAt( unsigned int index ) const; EXPORT const DMLColumn* get_ColumnAt(unsigned int index) const;
protected: protected:
private:
private:
WriteEngine::RID fRowID; WriteEngine::RID fRowID;
ColumnList fColumnList; ColumnList fColumnList;
Row& operator=(const Row&); Row& operator=(const Row&);
}; };
/** @brief a vector of Rows /** @brief a vector of Rows
*/ */
typedef std::vector<Row*>RowList; typedef std::vector<Row*> RowList;
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -52,7 +52,8 @@ bool parse_file(char* fileName)
const ParseTree& ptree = parser.getParseTree(); const ParseTree& ptree = parser.getParseTree();
cout << "Parser succeeded." << endl; cout << "Parser succeeded." << endl;
cout << ptree.fList.size() << " " << "SQL statements" << endl; cout << ptree.fList.size() << " "
<< "SQL statements" << endl;
cout << ptree.fSqlText << endl; cout << ptree.fSqlText << endl;
cout << ptree; cout << ptree;
@ -64,31 +65,33 @@ bool parse_file(char* fileName)
cout << endl; cout << endl;
} }
return good; return good;
} }
class DMLParserTest : public CppUnit::TestFixture class DMLParserTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE( DMLParserTest ); CPPUNIT_TEST_SUITE(DMLParserTest);
CPPUNIT_TEST( test_i01 ); CPPUNIT_TEST(test_i01);
CPPUNIT_TEST( test_i02 ); CPPUNIT_TEST(test_i02);
CPPUNIT_TEST( test_i03 ); CPPUNIT_TEST(test_i03);
CPPUNIT_TEST( test_i04 ); CPPUNIT_TEST(test_i04);
CPPUNIT_TEST( test_u01 ); CPPUNIT_TEST(test_u01);
CPPUNIT_TEST( test_u02 ); CPPUNIT_TEST(test_u02);
CPPUNIT_TEST( test_d01 ); CPPUNIT_TEST(test_d01);
CPPUNIT_TEST( test_d02 ); CPPUNIT_TEST(test_d02);
CPPUNIT_TEST( test_d03 ); CPPUNIT_TEST(test_d03);
CPPUNIT_TEST( test_d04 ); CPPUNIT_TEST(test_d04);
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public:
void setUp()
{
}
public: void tearDown()
void setUp() {} {
}
void tearDown() {}
void test_i01() void test_i01()
{ {
@ -143,11 +146,10 @@ public:
class DMLTest : public CppUnit::TestFixture class DMLTest : public CppUnit::TestFixture
{ {
CPPUNIT_TEST_SUITE(DMLTest);
CPPUNIT_TEST_SUITE( DMLTest );
// CPPUNIT_TEST( test_direct_insert ); // CPPUNIT_TEST( test_direct_insert );
// CPPUNIT_TEST( test_query_insert ); // CPPUNIT_TEST( test_query_insert );
CPPUNIT_TEST( test_direct_update ); CPPUNIT_TEST(test_direct_update);
// CPPUNIT_TEST( test_query_update ); // CPPUNIT_TEST( test_query_update );
// CPPUNIT_TEST( test_delete_all ); // CPPUNIT_TEST( test_delete_all );
// CPPUNIT_TEST( test_delete_query ); // CPPUNIT_TEST( test_delete_query );
@ -155,40 +157,44 @@ class DMLTest : public CppUnit::TestFixture
// CPPUNIT_TEST( test_rollback ); // CPPUNIT_TEST( test_rollback );
CPPUNIT_TEST_SUITE_END(); CPPUNIT_TEST_SUITE_END();
private: private:
public: public:
void setUp() {} void setUp()
{
}
void tearDown() {} void tearDown()
{
}
void test_direct_insert() void test_direct_insert()
{ {
ByteStream bytestream; ByteStream bytestream;
std::string dmlStatement = "INSERT INTO tpch.supplier (supplier_id, supplier_name) VALUES(24553, 'IBM');"; std::string dmlStatement = "INSERT INTO tpch.supplier (supplier_id, supplier_name) VALUES(24553, 'IBM');";
cout << dmlStatement << endl; cout << dmlStatement << endl;
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_insert_object(bytestream); read_insert_object(bytestream);
} }
void test_query_insert() void test_query_insert()
{ {
ByteStream bytestream; ByteStream bytestream;
std::string dmlStatement = "INSERT INTO supplier (supplier_id, supplier_name) SELECT account_no, name FROM customers WHERE city = 'Newark';"; std::string dmlStatement =
"INSERT INTO supplier (supplier_id, supplier_name) SELECT account_no, name FROM customers WHERE city "
"= 'Newark';";
cout << dmlStatement << endl; cout << dmlStatement << endl;
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
if ( pDMLPackage->HasFilter() ) if (pDMLPackage->HasFilter())
{ {
cout << "This INSERT statement has a filter:" << endl; cout << "This INSERT statement has a filter:" << endl;
cout << pDMLPackage->get_QueryString() << endl; cout << pDMLPackage->get_QueryString() << endl;
@ -197,34 +203,29 @@ public:
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_insert_object(bytestream); read_insert_object(bytestream);
} }
void write_DML_object( ByteStream& bs, CalpontDMLPackage* pDMLPackage ) void write_DML_object(ByteStream& bs, CalpontDMLPackage* pDMLPackage)
{ {
pDMLPackage->write(bs);
pDMLPackage->write( bs );
} }
void read_insert_object( ByteStream& bs ) void read_insert_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DML_INSERT == package_type ); CPPUNIT_ASSERT(DML_INSERT == package_type);
InsertDMLPackage* pObject = new InsertDMLPackage(); InsertDMLPackage* pObject = new InsertDMLPackage();
pObject->read( bs ); pObject->read(bs);
delete pObject; delete pObject;
} }
void test_delete_all() void test_delete_all()
{ {
ByteStream bytestream; ByteStream bytestream;
std::string dmlStatement = "DELETE FROM tpch.part;"; std::string dmlStatement = "DELETE FROM tpch.part;";
@ -233,7 +234,7 @@ public:
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_delete_object(bytestream); read_delete_object(bytestream);
@ -249,7 +250,7 @@ public:
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
if (pDMLPackage->HasFilter()) if (pDMLPackage->HasFilter())
{ {
@ -260,23 +261,20 @@ public:
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_delete_object(bytestream); read_delete_object(bytestream);
} }
void read_delete_object( ByteStream& bs ) void read_delete_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DML_DELETE == package_type ); CPPUNIT_ASSERT(DML_DELETE == package_type);
DeleteDMLPackage* pObject = new DeleteDMLPackage(); DeleteDMLPackage* pObject = new DeleteDMLPackage();
pObject->read( bs ); pObject->read(bs);
delete pObject; delete pObject;
} }
void test_direct_update() void test_direct_update()
@ -287,7 +285,7 @@ public:
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_update_object(bytestream); read_update_object(bytestream);
@ -295,14 +293,15 @@ public:
void test_query_update() void test_query_update()
{ {
ByteStream bytestream; ByteStream bytestream;
std::string dmlStatement = "UPDATE tpch.supplier SET supplier_name='joe',supplier_state='ca' WHERE EXISTS ( SELECT customer.name FROM customers WHERE customers.customer_id = supplier.supplier_id);"; std::string dmlStatement =
"UPDATE tpch.supplier SET supplier_name='joe',supplier_state='ca' WHERE EXISTS ( SELECT "
"customer.name FROM customers WHERE customers.customer_id = supplier.supplier_id);";
cout << dmlStatement << endl; cout << dmlStatement << endl;
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
if (pDMLPackage->HasFilter()) if (pDMLPackage->HasFilter())
{ {
@ -315,20 +314,18 @@ public:
read_update_object(bytestream); read_update_object(bytestream);
} }
void read_update_object( ByteStream& bs ) void read_update_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DML_UPDATE == package_type ); CPPUNIT_ASSERT(DML_UPDATE == package_type);
UpdateDMLPackage* pObject = new UpdateDMLPackage(); UpdateDMLPackage* pObject = new UpdateDMLPackage();
pObject->read( bs ); pObject->read(bs);
delete pObject; delete pObject;
} }
void test_commit() void test_commit()
@ -339,11 +336,10 @@ public:
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_command_object(bytestream); read_command_object(bytestream);
} }
void test_rollback() void test_rollback()
@ -354,40 +350,38 @@ public:
VendorDMLStatement dmlStmt(dmlStatement, 1); VendorDMLStatement dmlStmt(dmlStatement, 1);
CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt); CalpontDMLPackage* pDMLPackage = CalpontDMLFactory::makeCalpontDMLPackage(dmlStmt);
CPPUNIT_ASSERT( 0 != pDMLPackage ); CPPUNIT_ASSERT(0 != pDMLPackage);
write_DML_object(bytestream, pDMLPackage); write_DML_object(bytestream, pDMLPackage);
delete pDMLPackage; delete pDMLPackage;
read_command_object(bytestream); read_command_object(bytestream);
} }
void read_command_object( ByteStream& bs ) void read_command_object(ByteStream& bs)
{ {
ByteStream::byte package_type; ByteStream::byte package_type;
bs >> package_type; bs >> package_type;
CPPUNIT_ASSERT( DML_COMMAND == package_type ); CPPUNIT_ASSERT(DML_COMMAND == package_type);
CommandDMLPackage* pObject = new CommandDMLPackage(); CommandDMLPackage* pObject = new CommandDMLPackage();
pObject->read( bs ); pObject->read(bs);
delete pObject; delete pObject;
} }
}; };
//CPPUNIT_TEST_SUITE_REGISTRATION( DMLParserTest ); // CPPUNIT_TEST_SUITE_REGISTRATION( DMLParserTest );
CPPUNIT_TEST_SUITE_REGISTRATION( DMLTest ); CPPUNIT_TEST_SUITE_REGISTRATION(DMLTest);
#include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h> #include <cppunit/ui/text/TestRunner.h>
int main( int argc, char** argv) int main(int argc, char** argv)
{ {
CppUnit::TextUi::TestRunner runner; CppUnit::TextUi::TestRunner runner;
CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() ); runner.addTest(registry.makeTest());
bool wasSuccessful = runner.run( "", false ); bool wasSuccessful = runner.run("", false);
return (wasSuccessful ? 0 : 1); return (wasSuccessful ? 0 : 1);
} }

View File

@ -32,17 +32,19 @@ using namespace std;
namespace dmlpackage namespace dmlpackage
{ {
UpdateDMLPackage::UpdateDMLPackage() UpdateDMLPackage::UpdateDMLPackage()
{} {
}
UpdateDMLPackage::UpdateDMLPackage(std::string schemaName, std::string tableName, UpdateDMLPackage::UpdateDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID) int sessionID)
: CalpontDMLPackage( schemaName, tableName, dmlStatement, sessionID) : CalpontDMLPackage(schemaName, tableName, dmlStatement, sessionID)
{} {
}
UpdateDMLPackage::~UpdateDMLPackage() UpdateDMLPackage::~UpdateDMLPackage()
{} {
}
int UpdateDMLPackage::write(messageqcpp::ByteStream& bytestream) int UpdateDMLPackage::write(messageqcpp::ByteStream& bytestream)
{ {
@ -120,7 +122,6 @@ int UpdateDMLPackage::read(messageqcpp::ByteStream& bytestream)
int UpdateDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement) int UpdateDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
{ {
int retval = 1; int retval = 1;
UpdateSqlStatement& updateStmt = dynamic_cast<UpdateSqlStatement&>(sqlStatement); UpdateSqlStatement& updateStmt = dynamic_cast<UpdateSqlStatement&>(sqlStatement);
@ -163,7 +164,7 @@ int UpdateDMLPackage::buildFromSqlStatement(SqlStatement& sqlStatement)
int UpdateDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows) int UpdateDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows)
{ {
#ifdef DML_PACKAGE_DEBUG #ifdef DML_PACKAGE_DEBUG
//cout << "The data buffer received: " << buffer << endl; // cout << "The data buffer received: " << buffer << endl;
#endif #endif
int retval = 1; int retval = 1;
@ -178,46 +179,46 @@ int UpdateDMLPackage::buildFromBuffer(std::string& buffer, int columns, int rows
for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) for (tokenizer::iterator tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter)
{ {
dataList.push_back(StripLeadingWhitespace(*tok_iter)); dataList.push_back(StripLeadingWhitespace(*tok_iter));
} }
int n = 0; int n = 0;
for (int i = 0; i < rows; i++) for (int i = 0; i < rows; i++)
{ {
//get a new row // get a new row
Row* aRowPtr = new Row(); Row* aRowPtr = new Row();
std::string colName; std::string colName;
std::string colValue; std::string colValue;
//get row ID from the buffer // get row ID from the buffer
std::string rowid = dataList[n++]; std::string rowid = dataList[n++];
aRowPtr->set_RowID(atoll(rowid.c_str())); aRowPtr->set_RowID(atoll(rowid.c_str()));
#ifdef DML_PACKAGE_DEBUG #ifdef DML_PACKAGE_DEBUG
//cout << "The row ID is " << rowid << endl; // cout << "The row ID is " << rowid << endl;
#endif #endif
for (int j = 0; j < columns; j++) for (int j = 0; j < columns; j++)
{ {
//Build a column list // Build a column list
colName = dataList[n++]; colName = dataList[n++];
colValue = dataList[n++]; colValue = dataList[n++];
#ifdef DML_PACKAGE_DEBUG #ifdef DML_PACKAGE_DEBUG
//cout << "The column data: " << colName << " " << colValue << endl; // cout << "The column data: " << colName << " " << colValue << endl;
#endif #endif
DMLColumn* aColumn = new DMLColumn(colName, colValue); DMLColumn* aColumn = new DMLColumn(colName, colValue);
(aRowPtr->get_ColumnList()).push_back(aColumn); (aRowPtr->get_ColumnList()).push_back(aColumn);
} }
//build a row list for a table // build a row list for a table
fTable->get_RowList().push_back(aRowPtr); fTable->get_RowList().push_back(aRowPtr);
} }
return retval; return retval;
} }
int UpdateDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues ) int UpdateDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap,
int columns, int rows, NullValuesBitset& nullValues)
{ {
int retval = 1; int retval = 1;
@ -228,7 +229,7 @@ int UpdateDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValues
for (int j = 0; j < columns; j++) for (int j = 0; j < columns; j++)
{ {
//Build a column list // Build a column list
colName = colNameList[j]; colName = colNameList[j];
colValList = tableValuesMap[j]; colValList = tableValuesMap[j];
@ -237,14 +238,13 @@ int UpdateDMLPackage::buildFromMysqlBuffer(ColNameList& colNameList, TableValues
(aRowPtr->get_ColumnList()).push_back(aColumn); (aRowPtr->get_ColumnList()).push_back(aColumn);
} }
//build a row list for a table // build a row list for a table
fTable->get_RowList().push_back(aRowPtr); fTable->get_RowList().push_back(aRowPtr);
return retval; return retval;
} }
void UpdateDMLPackage::buildUpdateFromMysqlBuffer(UpdateSqlStatement& updateStmt) void UpdateDMLPackage::buildUpdateFromMysqlBuffer(UpdateSqlStatement& updateStmt)
{ {
if (!updateStmt.fColAssignmentListPtr) if (!updateStmt.fColAssignmentListPtr)
throw runtime_error("updateStmt.fColAssignmentPtr == NULL"); throw runtime_error("updateStmt.fColAssignmentPtr == NULL");
@ -259,8 +259,8 @@ void UpdateDMLPackage::buildUpdateFromMysqlBuffer(UpdateSqlStatement& updateStm
while (iter != updateStmt.fColAssignmentListPtr->end()) while (iter != updateStmt.fColAssignmentListPtr->end())
{ {
ColumnAssignment* colaPtr = *iter; ColumnAssignment* colaPtr = *iter;
DMLColumn* colPtr = new DMLColumn(colaPtr->fColumn, colaPtr->fScalarExpression, colaPtr->fFromCol, colaPtr->fFuncScale, DMLColumn* colPtr = new DMLColumn(colaPtr->fColumn, colaPtr->fScalarExpression, colaPtr->fFromCol,
colaPtr->fIsNull); colaPtr->fFuncScale, colaPtr->fIsNull);
rowPtr->get_ColumnList().push_back(colPtr); rowPtr->get_ColumnList().push_back(colPtr);
++iter; ++iter;

View File

@ -40,8 +40,7 @@ namespace dmlpackage
*/ */
class UpdateDMLPackage : public CalpontDMLPackage class UpdateDMLPackage : public CalpontDMLPackage
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT UpdateDMLPackage(); EXPORT UpdateDMLPackage();
@ -53,8 +52,8 @@ public:
* @param dmlStatement the dml statement * @param dmlStatement the dml statement
* @param sessionID the session ID * @param sessionID the session ID
*/ */
EXPORT UpdateDMLPackage( std::string schemaName, std::string tableName, EXPORT UpdateDMLPackage(std::string schemaName, std::string tableName, std::string dmlStatement,
std::string dmlStatement, int sessionID ); int sessionID);
/** @brief dtor /** @brief dtor
*/ */
@ -91,16 +90,13 @@ public:
* @param colNameList, tableValuesMap * @param colNameList, tableValuesMap
* @param rows the number of rows in the buffer * @param rows the number of rows in the buffer
*/ */
EXPORT int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns, int rows, NullValuesBitset& nullValues); EXPORT int buildFromMysqlBuffer(ColNameList& colNameList, TableValuesMap& tableValuesMap, int columns,
void buildUpdateFromMysqlBuffer(UpdateSqlStatement& updateStmt ); int rows, NullValuesBitset& nullValues);
void buildUpdateFromMysqlBuffer(UpdateSqlStatement& updateStmt);
protected:
private:
protected:
private:
}; };
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -29,31 +29,56 @@ using namespace std;
namespace dmlpackage namespace dmlpackage
{ {
VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int sessionID) VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int sessionID)
: fDMLStatement(dmlstatement), fSessionID(sessionID), fLogging(true), fLogending(true) : fDMLStatement(dmlstatement), fSessionID(sessionID), fLogging(true), fLogending(true)
{} {
}
VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int stmttype, int sessionID) VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int stmttype, int sessionID)
: fDMLStatement(dmlstatement), fDMLStatementType(stmttype), fSessionID(sessionID), fLogging(true), fLogending(true) : fDMLStatement(dmlstatement)
{} , fDMLStatementType(stmttype)
, fSessionID(sessionID)
, fLogging(true)
, fLogending(true)
{
}
VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int stmttype, VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName,
std::string tName, std::string schema, std::string schema, int rows, int columns, std::string buf,
int rows, int columns, std::string buf,
int sessionID) int sessionID)
: fDMLStatement(dmlstatement), fDMLStatementType(stmttype), : fDMLStatement(dmlstatement)
fTableName(tName), fSchema(schema), fRows(rows), fColumns(columns), , fDMLStatementType(stmttype)
fDataBuffer(buf), fSessionID(sessionID), fLogging(true), fLogending(true) , fTableName(tName)
{} , fSchema(schema)
, fRows(rows)
, fColumns(columns)
, fDataBuffer(buf)
, fSessionID(sessionID)
, fLogging(true)
, fLogending(true)
{
}
VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName, std::string schema, int rows, int columns, VendorDMLStatement::VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName,
ColNameList& colNameList, TableValuesMap& tableValuesMap, NullValuesBitset& nullValues, int sessionID) std::string schema, int rows, int columns, ColNameList& colNameList,
: fDMLStatement(dmlstatement), fDMLStatementType(stmttype), TableValuesMap& tableValuesMap, NullValuesBitset& nullValues,
fTableName(tName), fSchema(schema), fRows(rows), fColumns(columns), int sessionID)
fColNameList(colNameList), fTableValuesMap(tableValuesMap), fNullValues(nullValues), fSessionID(sessionID), fLogging(true), fLogending(true) : fDMLStatement(dmlstatement)
{} , fDMLStatementType(stmttype)
, fTableName(tName)
, fSchema(schema)
, fRows(rows)
, fColumns(columns)
, fColNameList(colNameList)
, fTableValuesMap(tableValuesMap)
, fNullValues(nullValues)
, fSessionID(sessionID)
, fLogging(true)
, fLogending(true)
{
}
VendorDMLStatement::~VendorDMLStatement() VendorDMLStatement::~VendorDMLStatement()
{} {
} }
} // namespace dmlpackage

View File

@ -45,8 +45,7 @@ typedef std::bitset<4096> NullValuesBitset;
*/ */
class VendorDMLStatement class VendorDMLStatement
{ {
public:
public:
/** @brief ctor /** @brief ctor
*/ */
EXPORT VendorDMLStatement(std::string dmlstatement, int sessionID); EXPORT VendorDMLStatement(std::string dmlstatement, int sessionID);
@ -57,14 +56,14 @@ public:
/** @brief old ctor! /** @brief old ctor!
*/ */
EXPORT VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName, EXPORT VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName, std::string schema,
std::string schema, int rows, int columns, std::string buf, int rows, int columns, std::string buf, int sessionID);
int sessionID);
/** @brief ctor for mysql /** @brief ctor for mysql
*/ */
EXPORT VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName, std::string schema, int rows, int columns, EXPORT VendorDMLStatement(std::string dmlstatement, int stmttype, std::string tName, std::string schema,
ColNameList& colNameList, TableValuesMap& tableValuesMap, NullValuesBitset& nullValues, int sessionID); int rows, int columns, ColNameList& colNameList, TableValuesMap& tableValuesMap,
NullValuesBitset& nullValues, int sessionID);
/** @brief destructor /** @brief destructor
*/ */
@ -79,7 +78,7 @@ public:
/** @brief Set the table name /** @brief Set the table name
*/ */
inline void set_TableName( std::string value ) inline void set_TableName(std::string value)
{ {
fTableName = value; fTableName = value;
} }
@ -93,7 +92,7 @@ public:
/** @brief Set the schema name /** @brief Set the schema name
*/ */
inline void set_SchemaName( std::string value ) inline void set_SchemaName(std::string value)
{ {
fSchema = value; fSchema = value;
} }
@ -107,7 +106,7 @@ public:
/** @brief Set the DML statement type /** @brief Set the DML statement type
*/ */
inline void set_DMLStatementType( int value ) inline void set_DMLStatementType(int value)
{ {
fDMLStatementType = value; fDMLStatementType = value;
} }
@ -121,7 +120,7 @@ public:
/** @brief Set the DML statVendorDMLStatement classement /** @brief Set the DML statVendorDMLStatement classement
*/ */
inline void set_DMLStatement( std::string dmlStatement ) inline void set_DMLStatement(std::string dmlStatement)
{ {
fDMLStatement = dmlStatement; fDMLStatement = dmlStatement;
} }
@ -135,7 +134,7 @@ public:
/** @brief Set the number of rows /** @brief Set the number of rows
*/ */
inline void set_Rows( int value ) inline void set_Rows(int value)
{ {
fRows = value; fRows = value;
} }
@ -149,7 +148,7 @@ public:
/** @brief Set the number of columns /** @brief Set the number of columns
*/ */
inline void set_Columns( int value ) inline void set_Columns(int value)
{ {
fColumns = value; fColumns = value;
} }
@ -163,7 +162,7 @@ public:
/** @brief Set the data buffer /** @brief Set the data buffer
*/ */
inline void set_DataBuffer( std::string value ) inline void set_DataBuffer(std::string value)
{ {
fDataBuffer = value; fDataBuffer = value;
} }
@ -181,7 +180,7 @@ public:
/** @brief Set the session ID /** @brief Set the session ID
*/ */
inline void set_SessionID( int value ) inline void set_SessionID(int value)
{ {
fSessionID = value; fSessionID = value;
} }
@ -205,7 +204,7 @@ public:
* *
* @param logging the logging flag to set * @param logging the logging flag to set
*/ */
inline void set_Logging( bool logging ) inline void set_Logging(bool logging)
{ {
fLogging = logging; fLogging = logging;
} }
@ -221,14 +220,13 @@ public:
* *
* @param logending the logending flag to set * @param logending the logending flag to set
*/ */
inline void set_Logending( bool logending ) inline void set_Logending(bool logending)
{ {
fLogending = logending; fLogending = logending;
} }
protected: protected:
private:
private:
std::string fDMLStatement; std::string fDMLStatement;
int fDMLStatementType; int fDMLStatementType;
std::string fTableName; std::string fTableName;
@ -242,10 +240,8 @@ private:
int fSessionID; int fSessionID;
bool fLogging; bool fLogging;
bool fLogending; bool fLogending;
}; };
} } // namespace dmlpackage
#undef EXPORT #undef EXPORT

View File

@ -26,11 +26,10 @@
#include <boost/thread/mutex.hpp> #include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp> #include <boost/thread/condition.hpp>
class AutoincrementData class AutoincrementData
{ {
public: public:
typedef std::map <uint32_t, AutoincrementData*> AutoincDataMap; typedef std::map<uint32_t, AutoincrementData*> AutoincDataMap;
typedef std::map<uint32_t, long long> OIDNextValue; typedef std::map<uint32_t, long long> OIDNextValue;
static AutoincrementData* makeAutoincrementData(uint32_t sessionID = 0); static AutoincrementData* makeAutoincrementData(uint32_t sessionID = 0);
static void removeAutoincrementData(uint32_t sessionID = 0); static void removeAutoincrementData(uint32_t sessionID = 0);
@ -38,7 +37,7 @@ public:
long long getNextValue(uint32_t columnOid); long long getNextValue(uint32_t columnOid);
OIDNextValue& getOidNextValueMap(); OIDNextValue& getOidNextValueMap();
private: private:
/** Constuctors */ /** Constuctors */
explicit AutoincrementData(); explicit AutoincrementData();
explicit AutoincrementData(const AutoincrementData& rhs); explicit AutoincrementData(const AutoincrementData& rhs);

Some files were not shown because too many files have changed in this diff Show More