~aleteoryx/muditaos

ref: 496e53b848aa4d08fed29a2d9646cc529feef7c2 muditaos/module-db/Database/DatabaseInitializer.hpp -rw-r--r-- 1.8 KiB
496e53b8 — Dawid Wojtas [MOS-692] Update slider after tethering is off 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once

#include "Database.hpp"
#include <fstream>
#include <filesystem>

namespace
{
    template <typename T>
    inline bool starts_with(const T &str, const T &start)
    {
        if (start.size() > str.size())
            return false;
        return str.compare(0, start.size(), start) == 0;
    }
    template <typename T>
    inline bool ends_with(const T &str, const T &end)
    {
        if (end.size() > str.size())
            return false;
        return std::equal(end.rbegin(), end.rend(), str.rbegin());
    }
} // namespace

class DatabaseInitializer
{
    class ScopedFile
    {
      public:
        ScopedFile(std::string path, std::string mode)
        {
            file = std::fopen(path.c_str(), mode.c_str());
        }

        ~ScopedFile()
        {
            std::fclose(file);
        }

        [[nodiscard]] std::FILE *get() const
        {
            return file;
        }

      private:
        std::FILE *file = nullptr;
    };

  public:
    DatabaseInitializer(Database *db);
    ~DatabaseInitializer() = default;

    auto run(std::filesystem::path path, std::string ext = "sql") -> bool;

    auto readCommands(std::filesystem::path filePath) -> std::vector<std::string>;

    auto listFiles(std::filesystem::path path, std::string prefix, std::string ext)
        -> std::vector<std::filesystem::path>;

    auto executeOnDb(const std::vector<std::string> statements) -> bool;

  private:
    /*
     * Splits filename in format <prefix>_<num>.ext into array
     *  [0] - filename
     *  [1] - prefix
     *  [2] - num
     */
    auto splitFilename(std::string filename) -> std::array<std::string, 3>;
    std::string readContent(const char *filename) const noexcept;

    Database *db = nullptr;
};