/**
* Relational pipes
* Copyright © 2021 František Kučera (Frantovo.cz, GlobalCode.info)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <regex>
#include <locale>
#include <relpipe/common/type/typedefs.h>
#include "Mode.h"
namespace relpipe {
namespace tr {
namespace infertypes {
class DataMode : public Mode {
private:
static const std::wregex BOOLEAN_PATTERN;
static const std::wregex INTEGER_PATTERN;
relpipe::common::type::StringX name;
std::vector<relpipe::reader::handlers::AttributeMetadata> attributes;
std::vector<relpipe::common::type::StringX> values;
bool matches(int attributeIndex, const std::wregex& pattern) {
for (int record = 0, attributeCount = attributes.size(), limit = values.size() / attributeCount; record < limit; record++) if (!std::regex_match(values[record * attributeCount + attributeIndex], pattern)) return false;
return true;
}
public:
DataMode(shared_ptr<writer::RelationalWriter> relationalWriter) : Mode(relationalWriter) {
}
void startRelation(relpipe::common::type::StringX name, std::vector<relpipe::reader::handlers::AttributeMetadata> attributes) override {
this->name = name;
this->attributes = attributes;
}
void attribute(const relpipe::common::type::StringX& value) override {
values.push_back(value);
}
virtual ~DataMode() {
std::vector<bool> booleans(attributes.size(), true);
std::vector<bool> integers(attributes.size(), true);
for (int i = 0, limit = attributes.size(); i < limit; i++) {
booleans[i] = matches(i, BOOLEAN_PATTERN);
integers[i] = matches(i, INTEGER_PATTERN);
}
vector<writer::AttributeMetadata> writerMetadata;
for (int i = 0, limit = attributes.size(); i < limit; i++) {
relpipe::reader::handlers::AttributeMetadata& am = attributes[i];
relpipe::writer::TypeId type;
if (booleans[i]) type = relpipe::writer::TypeId::BOOLEAN;
else if (integers[i]) type = relpipe::writer::TypeId::INTEGER;
else type = relpipe::writer::TypeId::STRING;
writerMetadata.push_back({am.getAttributeName(), type});
}
relationalWriter->startRelation(name, writerMetadata, true);
for (relpipe::common::type::StringX& value : values) relationalWriter->writeAttribute(value);
}
};
const std::wregex DataMode::BOOLEAN_PATTERN = std::wregex(L"true|false");
const std::wregex DataMode::INTEGER_PATTERN = std::wregex(L"-?[0-9]+");
}
}
}