Insert.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. * Copyright (c) 2021, Mahmoud Mandour <ma.mandourr@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibSQL/AST/AST.h>
  8. #include <LibSQL/Database.h>
  9. #include <LibSQL/Meta.h>
  10. #include <LibSQL/Row.h>
  11. namespace SQL::AST {
  12. static bool does_value_data_type_match(SQLType expected, SQLType actual)
  13. {
  14. if (actual == SQLType::Null)
  15. return false;
  16. if (expected == SQLType::Integer)
  17. return actual == SQLType::Integer || actual == SQLType::Float;
  18. return expected == actual;
  19. }
  20. ResultOr<ResultSet> Insert::execute(ExecutionContext& context) const
  21. {
  22. auto table_def = TRY(context.database->get_table(m_schema_name, m_table_name));
  23. if (!table_def) {
  24. auto schema_name = m_schema_name.is_empty() ? String("default"sv) : m_schema_name;
  25. return Result { SQLCommand::Insert, SQLErrorCode::TableDoesNotExist, String::formatted("{}.{}", schema_name, m_table_name) };
  26. }
  27. Row row(table_def);
  28. for (auto& column : m_column_names) {
  29. if (!row.has(column))
  30. return Result { SQLCommand::Insert, SQLErrorCode::ColumnDoesNotExist, column };
  31. }
  32. ResultSet result { SQLCommand::Insert };
  33. TRY(result.try_ensure_capacity(m_chained_expressions.size()));
  34. for (auto& row_expr : m_chained_expressions) {
  35. for (auto& column_def : table_def->columns()) {
  36. if (!m_column_names.contains_slow(column_def.name()))
  37. row[column_def.name()] = column_def.default_value();
  38. }
  39. auto row_value = TRY(row_expr.evaluate(context));
  40. VERIFY(row_value.type() == SQLType::Tuple);
  41. auto values = row_value.to_vector().value();
  42. if (m_column_names.is_empty() && values.size() != row.size())
  43. return Result { SQLCommand::Insert, SQLErrorCode::InvalidNumberOfValues, String::empty() };
  44. for (auto ix = 0u; ix < values.size(); ix++) {
  45. auto input_value_type = values[ix].type();
  46. auto& tuple_descriptor = *row.descriptor();
  47. // In case of having column names, this must succeed since we checked for every column name for existence in the table.
  48. auto element_index = m_column_names.is_empty() ? ix : tuple_descriptor.find_if([&](auto element) { return element.name == m_column_names[ix]; }).index();
  49. auto element_type = tuple_descriptor[element_index].type;
  50. if (!does_value_data_type_match(element_type, input_value_type))
  51. return Result { SQLCommand::Insert, SQLErrorCode::InvalidValueType, table_def->columns()[element_index].name() };
  52. row[element_index] = values[ix];
  53. }
  54. TRY(context.database->insert(row));
  55. result.insert_row(row, {});
  56. }
  57. return result;
  58. }
  59. }