CreateTable.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. RefPtr<SQLResult> CreateTable::execute(ExecutionContext& context) const
  10. {
  11. auto schema_name = (!m_schema_name.is_null() && !m_schema_name.is_empty()) ? m_schema_name : "default";
  12. auto schema_def_or_error = context.database->get_schema(schema_name);
  13. if (schema_def_or_error.is_error())
  14. return SQLResult::construct(SQLCommand::Create, SQLErrorCode::InternalError, schema_def_or_error.error());
  15. auto schema_def = schema_def_or_error.release_value();
  16. if (!schema_def)
  17. return SQLResult::construct(SQLCommand::Create, SQLErrorCode::SchemaDoesNotExist, m_schema_name);
  18. auto table_def_or_error = context.database->get_table(schema_name, m_table_name);
  19. if (table_def_or_error.is_error())
  20. return SQLResult::construct(SQLCommand::Create, SQLErrorCode::InternalError, table_def_or_error.error());
  21. auto table_def = table_def_or_error.release_value();
  22. if (table_def) {
  23. if (m_is_error_if_table_exists) {
  24. return SQLResult::construct(SQLCommand::Create, SQLErrorCode::TableExists, m_table_name);
  25. } else {
  26. return SQLResult::construct(SQLCommand::Create);
  27. }
  28. }
  29. table_def = TableDef::construct(schema_def, m_table_name);
  30. for (auto& column : m_columns) {
  31. SQLType type;
  32. if (column.type_name()->name() == "VARCHAR" || column.type_name()->name() == "TEXT") {
  33. type = SQLType::Text;
  34. } else if (column.type_name()->name() == "INT" || column.type_name()->name() == "INTEGER") {
  35. type = SQLType::Integer;
  36. } else if (column.type_name()->name() == "FLOAT" || column.type_name()->name() == "NUMBER") {
  37. type = SQLType::Float;
  38. } else {
  39. return SQLResult::construct(SQLCommand::Create, SQLErrorCode::InvalidType, column.type_name()->name());
  40. }
  41. table_def->append_column(column.name(), type);
  42. }
  43. if (auto maybe_error = context.database->add_table(*table_def); maybe_error.is_error())
  44. return SQLResult::construct(SQLCommand::Create, SQLErrorCode::InternalError, maybe_error.release_error());
  45. return SQLResult::construct(SQLCommand::Create, 0, 1);
  46. }
  47. }