CreateTable.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibSQL/AST/AST.h>
  7. #include <LibSQL/Database.h>
  8. namespace SQL::AST {
  9. ResultOr<ResultSet> CreateTable::execute(ExecutionContext& context) const
  10. {
  11. auto schema_name = m_schema_name.is_empty() ? String { "default"sv } : m_schema_name;
  12. auto schema_def = TRY(context.database->get_schema(schema_name));
  13. if (!schema_def)
  14. return Result { SQLCommand::Create, SQLErrorCode::SchemaDoesNotExist, schema_name };
  15. auto table_def = TRY(context.database->get_table(schema_name, m_table_name));
  16. if (table_def) {
  17. if (m_is_error_if_table_exists)
  18. return Result { SQLCommand::Create, SQLErrorCode::TableExists, m_table_name };
  19. return ResultSet { SQLCommand::Create };
  20. }
  21. table_def = TableDef::construct(schema_def, m_table_name);
  22. for (auto& column : m_columns) {
  23. SQLType type;
  24. if (column.type_name()->name().is_one_of("VARCHAR"sv, "TEXT"sv))
  25. type = SQLType::Text;
  26. else if (column.type_name()->name().is_one_of("INT"sv, "INTEGER"sv))
  27. type = SQLType::Integer;
  28. else if (column.type_name()->name().is_one_of("FLOAT"sv, "NUMBER"sv))
  29. type = SQLType::Float;
  30. else
  31. return Result { SQLCommand::Create, SQLErrorCode::InvalidType, column.type_name()->name() };
  32. table_def->append_column(column.name(), type);
  33. }
  34. TRY(context.database->add_table(*table_def));
  35. return ResultSet { SQLCommand::Create };
  36. }
  37. }