CreateTable.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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_def = TRY(context.database->get_schema(m_schema_name));
  12. auto table_def = TableDef::construct(schema_def, m_table_name);
  13. for (auto const& column : m_columns) {
  14. SQLType type;
  15. if (column.type_name()->name().is_one_of("VARCHAR"sv, "TEXT"sv))
  16. type = SQLType::Text;
  17. else if (column.type_name()->name().is_one_of("INT"sv, "INTEGER"sv))
  18. type = SQLType::Integer;
  19. else if (column.type_name()->name().is_one_of("FLOAT"sv, "NUMBER"sv))
  20. type = SQLType::Float;
  21. else if (column.type_name()->name().is_one_of("BOOL"sv, "BOOLEAN"sv))
  22. type = SQLType::Boolean;
  23. else
  24. return Result { SQLCommand::Create, SQLErrorCode::InvalidType, column.type_name()->name() };
  25. table_def->append_column(column.name(), type);
  26. }
  27. if (auto result = context.database->add_table(*table_def); result.is_error()) {
  28. if (result.error().error() != SQLErrorCode::TableExists || m_is_error_if_table_exists)
  29. return result.release_error();
  30. }
  31. return ResultSet { SQLCommand::Create };
  32. }
  33. }