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