StorageGenerateRandom.cpp 17.1 KB
Newer Older
A
Alexey Milovidov 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <Storages/IStorage.h>
#include <Storages/ColumnsDescription.h>
#include <Storages/StorageGenerateRandom.h>
#include <Storages/StorageFactory.h>
#include <Processors/Sources/SourceFromSingleChunk.h>
#include <Processors/Pipe.h>
#include <Parsers/ASTLiteral.h>

#include <DataTypes/DataTypeTuple.h>
#include <DataTypes/DataTypeEnum.h>
#include <DataTypes/DataTypeNullable.h>
#include <DataTypes/DataTypeDateTime64.h>
#include <DataTypes/DataTypeDecimalBase.h>
#include <DataTypes/DataTypeArray.h>
A
Alexey Milovidov 已提交
15 16
#include <DataTypes/DataTypeString.h>
#include <DataTypes/DataTypeFixedString.h>
17
#include <DataTypes/NestedUtils.h>
A
Alexey Milovidov 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include <Columns/ColumnArray.h>
#include <Columns/ColumnFixedString.h>
#include <Columns/ColumnString.h>
#include <Columns/ColumnVector.h>
#include <Columns/ColumnNullable.h>
#include <Columns/ColumnTuple.h>

#include <Common/SipHash.h>
#include <Common/randomSeed.h>
#include <common/unaligned.h>

#include <Functions/FunctionFactory.h>

#include <pcg_random.hpp>


namespace DB
{

namespace ErrorCodes
{
    extern const int NOT_IMPLEMENTED;
    extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
41 42
    extern const int TOO_LARGE_ARRAY_SIZE;
    extern const int TOO_LARGE_STRING_SIZE;
A
Alexey Milovidov 已提交
43 44 45 46 47 48
}


namespace
{

A
Alexey Milovidov 已提交
49
void fillBufferWithRandomData(char * __restrict data, size_t size, pcg64 & rng)
A
Alexey Milovidov 已提交
50 51 52 53 54 55 56
{
    char * __restrict end = data + size;
    while (data < end)
    {
        /// The loop can be further optimized.
        UInt64 number = rng();
        unalignedStore<UInt64>(data, number);
A
Alexey Milovidov 已提交
57
        data += sizeof(UInt64); /// We assume that data has at least 7-byte padding (see PaddedPODArray)
A
Alexey Milovidov 已提交
58 59 60 61 62
    }
}


ColumnPtr fillColumnWithRandomData(
63 64 65 66 67 68
    const DataTypePtr type,
    UInt64 limit,
    UInt64 max_array_length,
    UInt64 max_string_length,
    pcg64 & rng,
    const Context & context)
A
Alexey Milovidov 已提交
69 70 71 72 73 74 75
{
    TypeIndex idx = type->getTypeId();

    switch (idx)
    {
        case TypeIndex::String:
        {
A
Alexey Milovidov 已提交
76
            /// Mostly the same as the implementation of randomPrintableASCII function.
A
Alexey Milovidov 已提交
77

A
Alexey Milovidov 已提交
78 79 80 81
            auto column = ColumnString::create();
            ColumnString::Chars & data_to = column->getChars();
            ColumnString::Offsets & offsets_to = column->getOffsets();
            offsets_to.resize(limit);
A
Alexey Milovidov 已提交
82

A
Alexey Milovidov 已提交
83 84
            IColumn::Offset offset = 0;
            for (size_t row_num = 0; row_num < limit; ++row_num)
A
Alexey Milovidov 已提交
85
            {
A
Alexey Milovidov 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
                size_t length = rng() % (max_string_length + 1);    /// Slow

                IColumn::Offset next_offset = offset + length + 1;
                data_to.resize(next_offset);
                offsets_to[row_num] = next_offset;

                auto * data_to_ptr = data_to.data();    /// avoid assert on array indexing after end
                for (size_t pos = offset, end = offset + length; pos < end; pos += 4)    /// We have padding in column buffers that we can overwrite.
                {
                    UInt64 rand = rng();

                    UInt16 rand1 = rand;
                    UInt16 rand2 = rand >> 16;
                    UInt16 rand3 = rand >> 32;
                    UInt16 rand4 = rand >> 48;

                    /// Printable characters are from range [32; 126].
                    /// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
A
Alexey Milovidov 已提交
104

A
Alexey Milovidov 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
                    data_to_ptr[pos + 0] = 32 + ((rand1 * 95) >> 16);
                    data_to_ptr[pos + 1] = 32 + ((rand2 * 95) >> 16);
                    data_to_ptr[pos + 2] = 32 + ((rand3 * 95) >> 16);
                    data_to_ptr[pos + 3] = 32 + ((rand4 * 95) >> 16);

                    /// NOTE gcc failed to vectorize this code (aliasing of char?)
                    /// TODO Implement SIMD optimizations from Danila Kutenin.
                }

                data_to[offset + length] = 0;

                offset = next_offset;
            }

            return column;
A
Alexey Milovidov 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        }

        case TypeIndex::Enum8:
        {
            auto column = ColumnVector<Int8>::create();
            auto values = typeid_cast<const DataTypeEnum<Int8> *>(type.get())->getValues();
            auto & data = column->getData();
            data.resize(limit);

            UInt8 size = values.size();
            UInt8 off;
            for (UInt64 i = 0; i < limit; ++i)
            {
                off = static_cast<UInt8>(rng()) % size;
                data[i] = values[off].second;
            }

            return column;
        }

        case TypeIndex::Enum16:
        {
            auto column = ColumnVector<Int16>::create();
            auto values = typeid_cast<const DataTypeEnum<Int16> *>(type.get())->getValues();
            auto & data = column->getData();
            data.resize(limit);

            UInt16 size = values.size();
            UInt8 off;
            for (UInt64 i = 0; i < limit; ++i)
            {
                off = static_cast<UInt16>(rng()) % size;
                data[i] = values[off].second;
            }

            return column;
        }

        case TypeIndex::Array:
        {
            auto nested_type = typeid_cast<const DataTypeArray *>(type.get())->getNestedType();

            auto offsets_column = ColumnVector<ColumnArray::Offset>::create();
            auto & offsets = offsets_column->getData();

            UInt64 offset = 0;
            offsets.resize(limit);
            for (UInt64 i = 0; i < limit; ++i)
            {
A
Alexey Milovidov 已提交
169
                offset += static_cast<UInt64>(rng()) % (max_array_length + 1);
A
Alexey Milovidov 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
                offsets[i] = offset;
            }

            auto data_column = fillColumnWithRandomData(nested_type, offset, max_array_length, max_string_length, rng, context);

            return ColumnArray::create(std::move(data_column), std::move(offsets_column));
        }

        case TypeIndex::Tuple:
        {
            auto elements = typeid_cast<const DataTypeTuple *>(type.get())->getElements();
            const size_t tuple_size = elements.size();
            Columns tuple_columns(tuple_size);

            for (size_t i = 0; i < tuple_size; ++i)
                tuple_columns[i] = fillColumnWithRandomData(elements[i], limit, max_array_length, max_string_length, rng, context);

            return ColumnTuple::create(std::move(tuple_columns));
        }

        case TypeIndex::Nullable:
        {
            auto nested_type = typeid_cast<const DataTypeNullable *>(type.get())->getNestedType();
            auto nested_column = fillColumnWithRandomData(nested_type, limit, max_array_length, max_string_length, rng, context);

            auto null_map_column = ColumnUInt8::create();
            auto & null_map = null_map_column->getData();
            null_map.resize(limit);
            for (UInt64 i = 0; i < limit; ++i)
                null_map[i] = rng() % 16 == 0; /// No real motivation for this.

            return ColumnNullable::create(std::move(nested_column), std::move(null_map_column));
        }

        case TypeIndex::UInt8:
        {
            auto column = ColumnUInt8::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(UInt8), rng);
            return column;
        }
        case TypeIndex::UInt16: [[fallthrough]];
        case TypeIndex::Date:
        {
            auto column = ColumnUInt16::create();
            column->getData().resize(limit);
216 217 218 219

            for (size_t i = 0; i < limit; ++i)
                column->getData()[i] = rng() % (DATE_LUT_MAX_DAY_NUM + 1);   /// Slow

A
Alexey Milovidov 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
            return column;
        }
        case TypeIndex::UInt32: [[fallthrough]];
        case TypeIndex::DateTime:
        {
            auto column = ColumnUInt32::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(UInt32), rng);
            return column;
        }
        case TypeIndex::UInt64:
        {
            auto column = ColumnUInt64::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(UInt64), rng);
            return column;
        }
        case TypeIndex::UInt128: [[fallthrough]];
        case TypeIndex::UUID:
        {
            auto column = ColumnUInt128::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(UInt128), rng);
            return column;
        }
        case TypeIndex::Int8:
        {
            auto column = ColumnInt8::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(Int8), rng);
            return column;
        }
        case TypeIndex::Int16:
        {
            auto column = ColumnInt16::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(Int16), rng);
            return column;
        }
        case TypeIndex::Int32:
        {
            auto column = ColumnInt32::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(Int32), rng);
            return column;
        }
        case TypeIndex::Int64:
        {
            auto column = ColumnInt64::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(Int64), rng);
            return column;
        }
        case TypeIndex::Float32:
        {
            auto column = ColumnFloat32::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(Float32), rng);
            return column;
        }
        case TypeIndex::Float64:
        {
            auto column = ColumnFloat64::create();
            column->getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getData().data()), limit * sizeof(Float64), rng);
            return column;
        }
        case TypeIndex::Decimal32:
        {
            auto column = type->createColumn();
            auto & column_concrete = typeid_cast<ColumnDecimal<Decimal32> &>(*column);
            column_concrete.getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column_concrete.getData().data()), limit * sizeof(Decimal32), rng);
            return column;
        }
A
Alexey Milovidov 已提交
295
        case TypeIndex::Decimal64:  /// TODO Decimal may be generated out of range.
A
Alexey Milovidov 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        {
            auto column = type->createColumn();
            auto & column_concrete = typeid_cast<ColumnDecimal<Decimal64> &>(*column);
            column_concrete.getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column_concrete.getData().data()), limit * sizeof(Decimal64), rng);
            return column;
        }
        case TypeIndex::Decimal128:
        {
            auto column = type->createColumn();
            auto & column_concrete = typeid_cast<ColumnDecimal<Decimal128> &>(*column);
            column_concrete.getData().resize(limit);
            fillBufferWithRandomData(reinterpret_cast<char *>(column_concrete.getData().data()), limit * sizeof(Decimal128), rng);
            return column;
        }
A
Alexey Milovidov 已提交
311 312 313 314 315 316 317 318
        case TypeIndex::FixedString:
        {
            size_t n = typeid_cast<const DataTypeFixedString &>(*type).getN();
            auto column = ColumnFixedString::create(n);
            column->getChars().resize(limit * n);
            fillBufferWithRandomData(reinterpret_cast<char *>(column->getChars().data()), limit * n, rng);
            return column;
        }
A
Alexey Milovidov 已提交
319 320 321
        case TypeIndex::DateTime64:
        {
            auto column = type->createColumn();
322
            auto & column_concrete = typeid_cast<ColumnDecimal<DateTime64> &>(*column);
A
Alexey Milovidov 已提交
323 324 325 326 327 328 329 330 331
            column_concrete.getData().resize(limit);

            UInt64 range = (1ULL << 32) * intExp10(typeid_cast<const DataTypeDateTime64 &>(*type).getScale());

            for (size_t i = 0; i < limit; ++i)
                column_concrete.getData()[i] = rng() % range;   /// Slow

            return column;
        }
A
Alexey Milovidov 已提交
332 333 334 335 336 337 338 339 340 341 342

        default:
            throw Exception("The 'GenerateRandom' is not implemented for type " + type->getName(), ErrorCodes::NOT_IMPLEMENTED);
    }
}


class GenerateSource : public SourceWithProgress
{
public:
    GenerateSource(UInt64 block_size_, UInt64 max_array_length_, UInt64 max_string_length_, UInt64 random_seed_, Block block_header_, const Context & context_)
343 344 345
        : SourceWithProgress(Nested::flatten(prepareBlockToFill(block_header_)))
        , block_size(block_size_), max_array_length(max_array_length_), max_string_length(max_string_length_)
        , block_to_fill(std::move(block_header_)), rng(random_seed_), context(context_) {}
A
Alexey Milovidov 已提交
346 347 348 349 350 351 352

    String getName() const override { return "GenerateRandom"; }

protected:
    Chunk generate() override
    {
        Columns columns;
353
        columns.reserve(block_to_fill.columns());
A
Alexey Milovidov 已提交
354

355 356
        for (const auto & elem : block_to_fill)
            columns.emplace_back(fillColumnWithRandomData(elem.type, block_size, max_array_length, max_string_length, rng, context));
A
Alexey Milovidov 已提交
357

358 359
        columns = Nested::flatten(block_to_fill.cloneWithColumns(std::move(columns))).getColumns();
        return {std::move(columns), block_size};
A
Alexey Milovidov 已提交
360 361 362 363 364 365
    }

private:
    UInt64 block_size;
    UInt64 max_array_length;
    UInt64 max_string_length;
366
    Block block_to_fill;
A
Alexey Milovidov 已提交
367

A
Alexey Milovidov 已提交
368
    pcg64 rng;
A
Alexey Milovidov 已提交
369 370

    const Context & context;
371 372 373 374 375 376 377 378 379 380 381 382

    static Block & prepareBlockToFill(Block & block)
    {
        /// To support Nested types, we will collect them to single Array of Tuple.
        auto names_and_types = Nested::collect(block.getNamesAndTypesList());
        block.clear();

        for (auto & column : names_and_types)
            block.insert(ColumnWithTypeAndName(column.type, column.name));

        return block;
    }
A
Alexey Milovidov 已提交
383 384 385 386 387 388
};

}


StorageGenerateRandom::StorageGenerateRandom(const StorageID & table_id_, const ColumnsDescription & columns_,
389
    UInt64 max_array_length_, UInt64 max_string_length_, std::optional<UInt64> random_seed_)
A
Alexey Milovidov 已提交
390 391
    : IStorage(table_id_), max_array_length(max_array_length_), max_string_length(max_string_length_)
{
392 393 394 395 396 397 398 399 400 401
    static constexpr size_t MAX_ARRAY_SIZE = 1 << 30;
    static constexpr size_t MAX_STRING_SIZE = 1 << 30;

    if (max_array_length > MAX_ARRAY_SIZE)
        throw Exception(ErrorCodes::TOO_LARGE_ARRAY_SIZE, "Too large array size in GenerateRandom: {}, maximum: {}",
                        max_array_length, MAX_ARRAY_SIZE);
    if (max_string_length > MAX_STRING_SIZE)
        throw Exception(ErrorCodes::TOO_LARGE_STRING_SIZE, "Too large string size in GenerateRandom: {}, maximum: {}",
                        max_string_length, MAX_STRING_SIZE);

A
Alexey Milovidov 已提交
402
    random_seed = random_seed_ ? sipHash64(*random_seed_) : randomSeed();
A
alesapin 已提交
403 404 405
    StorageInMemoryMetadata storage_metadata;
    storage_metadata.setColumns(columns_);
    setInMemoryMetadata(storage_metadata);
A
Alexey Milovidov 已提交
406 407 408 409 410 411 412 413 414 415
}


void registerStorageGenerateRandom(StorageFactory & factory)
{
    factory.registerStorage("GenerateRandom", [](const StorageFactory::Arguments & args)
    {
        ASTs & engine_args = args.engine_args;

        if (engine_args.size() > 3)
416 417 418
            throw Exception("Storage GenerateRandom requires at most three arguments: "
                "random_seed, max_string_length, max_array_length.",
                ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);
A
Alexey Milovidov 已提交
419

420 421 422
        std::optional<UInt64> random_seed;
        UInt64 max_string_length = 10;
        UInt64 max_array_length = 10;
A
Alexey Milovidov 已提交
423

A
Alexey Milovidov 已提交
424
        if (!engine_args.empty())
425 426 427 428 429
        {
            const Field & value = engine_args[0]->as<const ASTLiteral &>().value;
            if (!value.isNull())
                random_seed = value.safeGet<UInt64>();
        }
A
Alexey Milovidov 已提交
430 431

        if (engine_args.size() >= 2)
432
            max_string_length = engine_args[1]->as<const ASTLiteral &>().value.safeGet<UInt64>();
A
Alexey Milovidov 已提交
433 434

        if (engine_args.size() == 3)
435
            max_array_length = engine_args[2]->as<const ASTLiteral &>().value.safeGet<UInt64>();
A
Alexey Milovidov 已提交
436

437
        return StorageGenerateRandom::create(args.table_id, args.columns, max_array_length, max_string_length, random_seed);
A
Alexey Milovidov 已提交
438 439 440
    });
}

N
Nikolai Kochetov 已提交
441
Pipe StorageGenerateRandom::read(
A
Alexey Milovidov 已提交
442
    const Names & column_names,
A
alesapin 已提交
443
    const StorageMetadataPtr & metadata_snapshot,
444
    SelectQueryInfo & /*query_info*/,
A
Alexey Milovidov 已提交
445 446 447 448 449
    const Context & context,
    QueryProcessingStage::Enum /*processed_stage*/,
    size_t max_block_size,
    unsigned num_streams)
{
A
alesapin 已提交
450
    metadata_snapshot->check(column_names, getVirtuals(), getStorageID());
A
Alexey Milovidov 已提交
451 452 453 454

    Pipes pipes;
    pipes.reserve(num_streams);

455
    const ColumnsDescription & our_columns = metadata_snapshot->getColumns();
A
Alexey Milovidov 已提交
456 457 458
    Block block_header;
    for (const auto & name : column_names)
    {
A
alexey-milovidov 已提交
459
        const auto & name_type = our_columns.get(name);
A
Alexey Milovidov 已提交
460 461 462 463 464
        MutableColumnPtr column = name_type.type->createColumn();
        block_header.insert({std::move(column), name_type.type, name_type.name});
    }

    /// Will create more seed values for each source from initial seed.
A
Alexey Milovidov 已提交
465
    pcg64 generate(random_seed);
A
Alexey Milovidov 已提交
466 467 468 469

    for (UInt64 i = 0; i < num_streams; ++i)
        pipes.emplace_back(std::make_shared<GenerateSource>(max_block_size, max_array_length, max_string_length, generate(), block_header, context));

N
Nikolai Kochetov 已提交
470
    return Pipe::unitePipes(std::move(pipes));
A
Alexey Milovidov 已提交
471 472 473
}

}