You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.7 KiB

  1. #pragma once
  2. #include "Table.h"
  3. #include <string>
  4. namespace db {
  5. namespace migrations {
  6. namespace builder {
  7. class CreateTableBuilder;
  8. class AlterTableBuilder;
  9. class DropTableBuilder;
  10. class AbstractTableBuilder {
  11. protected:
  12. Table &m_table;
  13. explicit AbstractTableBuilder(Table &table) : m_table(table) {}
  14. public:
  15. operator Table() const {
  16. return std::move(m_table);
  17. }
  18. };
  19. class TableBuilder : public AbstractTableBuilder {
  20. public:
  21. Table m_table;
  22. TableBuilder() : AbstractTableBuilder{m_table} {
  23. }
  24. };
  25. class CreateTableBuilder : public TableBuilder {
  26. public:
  27. bool is_primary_set = false;
  28. explicit CreateTableBuilder(const std::string &table_name) : TableBuilder() {
  29. m_table.header += "CREATE TABLE IF NOT EXISTS " + table_name + " (";
  30. }
  31. CreateTableBuilder &null(const std::string &i, const std::string &opts = "") {
  32. m_table.body += "\t" + i + " NULL " + opts + ",\n";
  33. return *this;
  34. }
  35. CreateTableBuilder &integer(const std::string &i, const std::string &opts = "") {
  36. m_table.body += "\t" + i + " INTEGER " + opts + ",\n";
  37. return *this;
  38. }
  39. CreateTableBuilder &real(const std::string &i, const std::string &opts = "") {
  40. m_table.body += "\t" + i + " REAL " + opts + ",\n";
  41. return *this;
  42. }
  43. CreateTableBuilder &text(const std::string &i, const std::string &opts = "") {
  44. m_table.body += "\t" + i + " TEXT " + opts + ",\n";
  45. return *this;
  46. }
  47. CreateTableBuilder &blob(const std::string &i, const std::string &opts = "") {
  48. m_table.body += "\t" + i + " BLOB " + opts + ",\n";
  49. return *this;
  50. }
  51. CreateTableBuilder &close() {
  52. m_table.body.pop_back();
  53. m_table.body.pop_back();
  54. m_table.body += ");\n";
  55. return *this;
  56. }
  57. };
  58. class AlterTableBuilder : public TableBuilder {
  59. public:
  60. explicit AlterTableBuilder(std::string table_name) : TableBuilder() {
  61. m_table.header = "ALTER TABLE " + table_name;
  62. }
  63. AlterTableBuilder &rename_column(const std::string &column_old, const std::string &column_new) {
  64. m_table.body += "RENAME COLUMN " + column_old + " TO " + column_new + ";\n";
  65. return *this;
  66. }
  67. };
  68. class DropTableBuilder : public TableBuilder {
  69. public:
  70. explicit DropTableBuilder(std::string table_name) : TableBuilder() {
  71. m_table.header = "DROP TABLE IF EXISTS " + table_name + ";\n";
  72. }
  73. };
  74. }
  75. }
  76. }