diff --git a/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/masd_schema_ore_diff.sh b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/masd_schema_ore_diff.sh new file mode 100644 index 00000000..b5914562 --- /dev/null +++ b/doc/agile/versions/v0/sprint_01/own_the_masd_meta_model/evidence/masd_schema_ore_diff.sh @@ -0,0 +1,77 @@ +#!/bin/bash +# +# Copyright (C) 2026 Marco Craveiro +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation; either version 3 of the License, or (at your option) any later +# version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin +# Street, Fifth Floor, Boston, MA 02110-1301, USA. +# +set -euo pipefail + +usage() { + cat <<'EOF' +usage: masd_schema_ore_diff.sh + +Runs compass diff over a scratch copy of ORE Studio's main four times: + + old the old binary, as ORE Studio configures it; + new the new binary, as ORE Studio configures it; + old_layered the old binary, its library @compass,projects/ores.codegen/library; + new_layered the new binary, the same, so the masd.* nodes of the MASD + library are in the graph beside ORE Studio's. + +new must equal old, and new_layered old_layered, byte for byte. Each binary +must sit in a bin directory with share/compass/masd beside it. +EOF +} + +[ $# -eq 4 ] || { usage >&2; exit 2; } +old="$1"; new="$2"; git_dir="$3"; scratch="$4" + +ore="$scratch/ore" +# A copy already committed in the scratch directory is reused, so the four +# runs can be repeated without unpacking ORE Studio again. +if [ ! -d "$ore/.git" ]; then + rm -rf "${ore:?}" + mkdir -p "$ore" + git --git-dir="$git_dir" archive main | tar -x -C "$ore" + git -C "$ore" init -q + git -C "$ore" add -A + git -C "$ore" -c user.name=scratch -c user.email=scratch@example.invalid \ + commit -qm "ORE Studio main" +fi + +layered=(--set codegen.library=@compass,projects/ores.codegen/library) + +run() { + local name="$1"; shift + "$@" -C "$ore" diff --files >"$scratch/$name.diff" 2>"$scratch/$name.err" || + true +} + +same() { + if cmp -s "$scratch/$1.diff" "$scratch/$2.diff" && + cmp -s <(tail -n +2 "$scratch/$1.err") <(tail -n +2 "$scratch/$2.err"); then + echo "$2: same as $1, $(grep -c '^+++ ' "$scratch/$2.diff") files" + else + echo "$2: different from $1; see $scratch/$2.diff and $scratch/$2.err" + return 1 + fi +} + +run old "$old" +head -n 1 "$scratch/old.err" +run new "$new" +same old new +run old_layered "$old" "${layered[@]}" +run new_layered "$new" "${layered[@]}" +same old_layered new_layered diff --git a/projects/compass.codegen/include/compass.codegen/ops/masd_context.hpp b/projects/compass.codegen/include/compass.codegen/ops/masd_context.hpp new file mode 100644 index 00000000..d37352cd --- /dev/null +++ b/projects/compass.codegen/include/compass.codegen/ops/masd_context.hpp @@ -0,0 +1,60 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef COMPASS_CODEGEN_OPS_MASD_CONTEXT_HPP +#define COMPASS_CODEGEN_OPS_MASD_CONTEXT_HPP + +#include +#include "compass.model/ops/builder.hpp" +#include "compass.model/ops/typescript.hpp" +#include "compass.model/types/masd_entity.hpp" + +namespace compass::codegen::ops { + +/** + * @brief The context the masd.cpp templates render a table's row type and + * COPY writer from: the library values and, under masd_entity, the names, + * includes, enumerations, members and COPY fields @p e implies. @p custom + * gives the header of each C++ type the standard library does not have. + * @throws std::runtime_error when a column of the row has a SQL type with + * no C++ type and the model states none. + */ +[[nodiscard]] compass::model::types::value_id masd_entity_context( + compass::model::ops::builder& b, compass::model::types::value_id library, + const compass::model::types::masd_entity& e, + const compass::model::ops::custom_types& custom); + +/** + * @brief The context the masd.sql template renders a component's whole + * schema from: the library values and, under masd_schema, each schema of + * @p s with the tables of @p tables in it, in an order where every table + * follows the tables it references, ties broken by name, then the + * functions. A table of a schema @p s does not list is left out, as the + * bookkeeping schema the migration runner creates is. + * @throws std::runtime_error when a foreign key references a table + * schema.sql does not create, or the references form a cycle. + */ +[[nodiscard]] compass::model::types::value_id masd_schema_context( + compass::model::ops::builder& b, compass::model::types::value_id library, + const compass::model::types::masd_schema& s, + std::span tables); + +} + +#endif diff --git a/projects/compass.codegen/include/compass.codegen/ops/physical_space.hpp b/projects/compass.codegen/include/compass.codegen/ops/physical_space.hpp index e8c27d95..e168fdc2 100644 --- a/projects/compass.codegen/include/compass.codegen/ops/physical_space.hpp +++ b/projects/compass.codegen/include/compass.codegen/ops/physical_space.hpp @@ -29,6 +29,12 @@ namespace compass::codegen::ops { +/** + * @brief The root of the MASD library's technical spaces, which the graph + * holds beside the product's own. + */ +inline constexpr std::string_view masd_root = "masd"; + /** * @brief One .*.org node document of the template library: its file * name and its text. diff --git a/projects/compass.codegen/library/component_catalogue.org b/projects/compass.codegen/library/component_catalogue.org new file mode 100644 index 00000000..07ebfb45 --- /dev/null +++ b/projects/compass.codegen/library/component_catalogue.org @@ -0,0 +1,17 @@ +:PROPERTIES: +:ID: 365DC1D2-2504-4F0F-B054-E021648143A0 +:END: +#+title: Component catalogue +#+description: The components of compass whose models compass's codegen codec generates, each with the modeling directory its models are found in. +#+type: ores.codegen.component_catalogue + +Read by compass's =codegen= codec from the project's library, which this +directory is; the MASD library, =@compass=, comes before it. A component is +generated when it has a row here, and only the models directly in its +=modeling_dir= whose =#+type:= is a codegen type are read. + +* Components + +| name | modeling_dir | exclude_org_types | +|------+------------------------------+-------------------| +| db | projects/compass.db/modeling | | diff --git a/projects/compass.codegen/library/data/licence-GPL-v3.txt b/projects/compass.codegen/library/data/licence-GPL-v3.txt new file mode 100644 index 00000000..58267160 --- /dev/null +++ b/projects/compass.codegen/library/data/licence-GPL-v3.txt @@ -0,0 +1,13 @@ +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License as published by the Free Software +Foundation; either version 3 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +details. + +You should have received a copy of the GNU General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 51 +Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. diff --git a/projects/compass.codegen/library/data/modeline.org b/projects/compass.codegen/library/data/modeline.org new file mode 100644 index 00000000..42bd4b83 --- /dev/null +++ b/projects/compass.codegen/library/data/modeline.org @@ -0,0 +1,60 @@ +:PROPERTIES: +:ID: 11D23674-0181-481F-A6A7-74D2D58C00B1 +:END: +#+title: Modelines +#+description: The four editor modelines compass writes at the top of the files it generates for itself: sql, c++, cmake and typescript. Each is a leaf under masd.modelines.emacs with one content attribute holding the Emacs mode line. +#+type: ores.codegen.modeline_catalogue + +Read by compass's =codegen= codec from the project's library, which this +directory is: each modeline opens the licence block of a generated file of +its language. + +* masd.modelines :module: +:PROPERTIES: +:custom_id: 00822DC2-371B-4CF1-9360-DBAC762A99A3 +:END: + +** masd.modelines.emacs :modeline_group: +:PROPERTIES: +:custom_id: ACBF8DA8-BF94-451F-AC0F-EEBA0AE5A0AC +:END: + +*** masd.modelines.emacs.sql :modeline: +:PROPERTIES: +:custom_id: 26B06D2C-DCD8-442A-A4EA-CA87DD0ED0A4 +:END: + +**** content :attribute: +:PROPERTIES: +:masd.codec.value: sql-product: postgres; tab-width: 4; indent-tabs-mode: nil +:END: + +*** masd.modelines.emacs.c++ :modeline: +:PROPERTIES: +:custom_id: 57E442E1-A62A-4670-A6B9-1A1FA6844A44 +:END: + +**** content :attribute: +:PROPERTIES: +:masd.codec.value: mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 +:END: + +*** masd.modelines.emacs.cmake :modeline: +:PROPERTIES: +:custom_id: C165CF64-1B05-4ECF-BB73-5FDC062D089C +:END: + +**** content :attribute: +:PROPERTIES: +:masd.codec.value: mode: cmake; cmake-tab-width: 4; indent-tabs-mode: nil +:END: + +*** masd.modelines.emacs.typescript :modeline: +:PROPERTIES: +:custom_id: A6E890F0-5860-44AC-80E8-AAAA9EE3B960 +:END: + +**** content :attribute: +:PROPERTIES: +:masd.codec.value: mode: typescript-ts-mode; tab-width: 4; indent-tabs-mode: nil +:END: diff --git a/projects/compass.codegen/src/CMakeLists.txt b/projects/compass.codegen/src/CMakeLists.txt index 0aeea41a..ea392335 100644 --- a/projects/compass.codegen/src/CMakeLists.txt +++ b/projects/compass.codegen/src/CMakeLists.txt @@ -59,6 +59,7 @@ add_library(${lib_target_name} ops/junction_context.cpp ops/library.cpp ops/manifest.cpp + ops/masd_context.cpp ops/model_steps.cpp ops/operation_context.cpp ops/output.cpp diff --git a/projects/compass.codegen/src/ops/generate.cpp b/projects/compass.codegen/src/ops/generate.cpp index 1fd60f36..4b0d3bca 100644 --- a/projects/compass.codegen/src/ops/generate.cpp +++ b/projects/compass.codegen/src/ops/generate.cpp @@ -35,6 +35,7 @@ #include "compass.codegen/ops/entity_registry.hpp" #include "compass.codegen/ops/facts.hpp" #include "compass.codegen/ops/manifest.hpp" +#include "compass.codegen/ops/masd_context.hpp" #include "compass.codegen/ops/model_contexts.hpp" #include "compass.codegen/ops/output.hpp" #include "compass.codegen/ops/physical_space.hpp" @@ -42,6 +43,7 @@ #include "compass.codegen/ops/values.hpp" #include "compass.model/ops/builder.hpp" #include "compass.model/ops/entity_claim.hpp" +#include "compass.model/ops/masd_entity.hpp" #include "compass.model/ops/outline.hpp" namespace compass::codegen::ops { @@ -122,10 +124,11 @@ bool is_model_candidate(std::string_view path) { } /** - * @brief The physical-space graph of the .*.org nodes of the - * templates/ directories of @p libraries, read in file-name order as - * load_graph reads them, with the name and the bytes of each node - * appended to @p read. + * @brief The physical-space graph of the .*.org and masd.*.org nodes + * of the templates/ directories of @p libraries, read in file-name order + * as load_graph reads them, with the name and the bytes of each node + * appended to @p read. The masd nodes are the MASD library's technical + * spaces, which serve the masd.codegen model types of any product. * @throws std::runtime_error when two libraries hold a node of the same * name: a node lives in one library, so a page moved between them cannot * be left in both. @@ -133,11 +136,17 @@ bool is_model_candidate(std::string_view path) { types::physical_space load_graph(const checkout_reader& reader, const std::vector& libraries, std::string_view root, std::string& read) { + std::vector roots{std::string(root)}; + if (root != masd_root) + roots.emplace_back(masd_root); std::map> found; for (const auto& library : libraries) { const auto templates = library + "/templates"; - for (const auto path : reader.list(templates + "/" + - std::string(root) + ".", ".org")) { + std::vector paths; + for (const auto& r : roots) + std::ranges::copy(reader.list(templates + "/" + r + ".", ".org"), + std::back_inserter(paths)); + for (const auto path : paths) { if (path.find('/', templates.size() + 1) != std::string_view::npos) continue; const std::string name(file_name(path)); @@ -386,7 +395,9 @@ constexpr context_type context_types[] = { {model_type::asset_class_catalogue, "asset_class_catalogue"}, {model_type::outcome_catalogue, "outcome_catalogue"}, {model_type::trade_type_catalogue, "trade_type_catalogue"}, - {model_type::service_registry, "service_registry"}}; + {model_type::service_registry, "service_registry"}, + {model_type::masd_entity, "masd_entity"}, + {model_type::masd_schema, "masd_schema"}}; /** * @brief A model's shared context and what its template variants are @@ -538,6 +549,55 @@ struct model_plan { */ using template_filter = std::function; +/** + * @brief Adds to @p out a row for each of @p units, rendered from + * @p context unless @p wanted refuses its template; a later unit naming + * an output replaces the earlier one. + */ +void add_rows(model_plan& out, const std::vector& units, + value_id context, std::string_view type_name, + const template_filter& wanted) { + std::unordered_map rows; + for (const auto& u : units) { + const bool kept = wanted && !wanted(u.template_name); + model_row row{{u.output, u.template_name, + kept ? value_id::none() : context, type_name}, kept}; + const auto [at, added] = rows.try_emplace(u.output, out.rows.size()); + if (added) + out.rows.push_back(std::move(row)); + else + out.rows[at->second] = std::move(row); + } +} + +/** + * @brief The context of a model of the MASD library: a table's, or a + * component's schema with every table modelled beside it. + * @throws compass::model::ops::model_error when a table beside the schema + * does not load. + */ +value_id masd_context(mops::builder& b, value_id library, + const mops::document& doc, model_type type, documents& docs, + const types::entity_registry& entities) { + const auto& find = docs.finder(); + if (type == model_type::masd_entity) + return masd_entity_context(b, library, + mops::read_masd_entity(doc, find), entities.custom_types); + const auto dir = doc.path.substr(0, doc.path.rfind('/') + 1); + std::vector tables; + for (const auto p : docs.org()) { + if (!p.starts_with(dir) || + p.find('/', dir.size()) != std::string_view::npos) + continue; + const auto d = docs.get(p); + if (d && mops::model_type_of(mops::declared_type(*d)) == + model_type::masd_entity) + tables.push_back(mops::read_masd_entity(*d, find)); + } + return masd_schema_context(b, library, mops::read_masd_schema(doc), + tables); +} + /** * @brief Plans the outputs of the model at @p path with the values of * @p b, reading @p registry and @p entities, which record what is read @@ -590,6 +650,18 @@ model_plan plan_model(mops::builder& b, value_id library, true), protocol_owned(registry, b.tables(), values::member(b.tables(), root, type_name), path)}; + if (*type == model_type::masd_entity || + *type == model_type::masd_schema) { + try { + const auto context = masd_context(b, library, *doc, *type, docs, + entities); + out.context = true; + add_rows(out, units, context, type_name, wanted); + } catch (const mops::model_error& e) { + out.error = std::string(path) + ": " + e.what(); + } + return out; + } const auto members = *type == model_type::family ? family_members_of(path, docs, b, cache) : family_members{}; const auto groups = *type == model_type::trade_type_catalogue diff --git a/projects/compass.codegen/src/ops/manifest.cpp b/projects/compass.codegen/src/ops/manifest.cpp index 2fba40a1..a402c6f6 100644 --- a/projects/compass.codegen/src/ops/manifest.cpp +++ b/projects/compass.codegen/src/ops/manifest.cpp @@ -32,7 +32,8 @@ constexpr std::string_view codegen_types[] = { "ores.codegen.operation", "ores.codegen.family", "ores.codegen.service_registry", "ores.codegen.component", "ores.codegen.asset_class_catalogue", "ores.codegen.trade_type_catalogue", - "ores.codegen.outcome_catalogue"}; + "ores.codegen.outcome_catalogue", "masd.codegen.entity", + "masd.codegen.schema"}; std::string_view strip(std::string_view s) { while (!s.empty() && std::isspace(static_cast(s.front()))) diff --git a/projects/compass.codegen/src/ops/masd_context.cpp b/projects/compass.codegen/src/ops/masd_context.cpp new file mode 100644 index 00000000..460681ae --- /dev/null +++ b/projects/compass.codegen/src/ops/masd_context.cpp @@ -0,0 +1,444 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.codegen/ops/masd_context.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace compass::codegen::ops { + +namespace { + +namespace mtypes = compass::model::types; +using compass::model::ops::builder; +using mtypes::key_kind; +using mtypes::masd_column; +using mtypes::masd_entity; +using mtypes::value_id; +using mtypes::written_by; + +/** + * @brief The C++ type of each SQL type a row may hold, when the model + * states none. + */ +constexpr std::pair sql_to_cpp[] = { + {"text", "std::string"}, + {"integer", "std::int32_t"}, + {"bigint", "std::int64_t"}, + {"boolean", "bool"}, + {"bytea", "std::string"}, + {"jsonb", "std::string"}, + {"text[]", "std::vector"}, + {"timestamptz", "std::chrono::sys_time"}}; + +/** + * @brief The standard header each standard name needs, the first of a + * name's spellings that a type mentions winning. + */ +constexpr std::pair std_headers[] = { + {"std::string_view", ""}, + {"std::string", ""}, + {"std::optional", ""}, + {"std::vector", ""}, + {"std::chrono", ""}, + {"std::int", ""}, + {"std::uint", ""}, + {"std::size_t", ""}}; + +bool is_word(char c) { + return std::isalnum(static_cast(c)) != 0 || c == '_'; +} + +/** + * @brief Whether @p type mentions @p name as a whole name, so + * std::string does not match std::string_view. + */ +bool mentions(std::string_view type, std::string_view name) { + for (auto at = type.find(name); at != std::string_view::npos; + at = type.find(name, at + 1)) { + const auto end = at + name.size(); + const bool prefix = name.ends_with("int"); + if (prefix || end == type.size() || !is_word(type[end])) + return true; + } + return false; +} + +std::string upper(std::string_view s) { + std::string out; + for (const char c : s) + out += is_word(c) ? static_cast(std::toupper( + static_cast(c))) : '_'; + return out; +} + +bool in_row(const masd_column& c) { + return c.writer == written_by::row && (c.key == key_kind::none || + c.key == key_kind::natural); +} + +bool in_copy(const masd_column& c) { + return c.writer == written_by::row && c.key != key_kind::identity; +} + +bool is_parameter(const masd_column& c) { + return c.writer == written_by::row && !in_row(c) && + c.key != key_kind::identity; +} + +std::string base_type(const masd_column& c) { + if (!c.cpp_type.empty()) + return c.cpp_type; + if (!c.enum_name.empty()) + return c.enum_name; + for (const auto& [sql, cpp] : sql_to_cpp) + if (sql == c.sql_type) + return std::string(cpp); + throw std::runtime_error("codegen: the column '" + c.name + "' is of " + "SQL type " + c.sql_type + ", which has no C++ type; state one with " + ":cpp_type:"); +} + +std::string member_type(const masd_column& c) { + const auto t = base_type(c); + return c.nullable ? "std::optional<" + t + ">" : t; +} + +bool is_arithmetic(std::string_view t) { + return t == "bool" || t == "std::size_t" || t.starts_with("std::int") || + t.starts_with("std::uint"); +} + +/** + * @brief The value a member starts with: zero, false, or the value of its + * enumeration the column defaults to, else the first. + */ +std::string initializer(const masd_column& c) { + if (c.nullable) + return {}; + const auto t = base_type(c); + if (!c.enum_name.empty() && c.cpp_type.empty()) { + auto value = c.values.front(); + const auto& d = c.default_value; + if (d.size() > 2 && d.front() == '\'' && d.back() == '\'') + value = d.substr(1, d.size() - 2); + return " = " + c.enum_name + "::" + value; + } + if (t == "bool") + return " = false"; + if (is_arithmetic(t)) + return " = 0"; + return {}; +} + +/** + * @brief The includes a header holding @p types needs, standard headers + * first, then @p project and the header of each custom type, each sorted. + */ +void add_includes(builder& b, value_id parent, + const std::vector& types, + const compass::model::ops::custom_types& custom, + std::set project) { + std::set system; + for (const auto& t : types) { + for (const auto& [name, header] : std_headers) + if (mentions(t, name)) + system.emplace(header); + for (const auto& [name, header] : custom) + if (mentions(t, name)) + project.insert(header); + } + const auto list = b.list(parent, "includes"); + for (const auto* set : {&system, &project}) + for (const auto& h : *set) + b.set(b.append_object(list), "include", h); +} + +void add_last(builder& b, value_id item, bool last) { + b.set(item, "last", last); +} + +/** + * @brief @p words joined by ", " into lines of string literals no longer + * than @p width, each but the last ending in the separator. + */ +std::vector wrapped(const std::vector& words, + std::size_t width) { + std::vector lines(1); + for (std::size_t i = 0; i < words.size(); ++i) { + const auto piece = words[i] + (i + 1 < words.size() ? ", " : ""); + if (!lines.back().empty() && lines.back().size() + piece.size() > + width) + lines.emplace_back(); + lines.back() += piece; + } + return lines; +} + +value_id with_library(builder& b, value_id library) { + const auto context = b.detached_object(); + const auto& t = b.tables(); + for (auto c = t.values.firsts[library]; !c.is_none(); + c = t.values.nexts[c]) + b.set_copy(context, mtypes::text_of(t.texts, t.values.keys[c]), c); + return context; +} + +void add_enums(builder& b, value_id m, const masd_entity& e) { + const auto list = b.list(m, "enums"); + for (const auto& c : e.columns) { + if (c.values.empty() || !c.cpp_type.empty()) + continue; + const auto en = b.append_object(list); + b.set(en, "name", c.enum_name); + b.set(en, "column", c.name); + b.set(en, "first", c.values.front()); + const auto values = b.list(en, "values"); + for (std::size_t i = 0; i < c.values.size(); ++i) { + const auto v = b.append_object(values); + b.set(v, "value", c.values[i]); + add_last(b, v, i + 1 == c.values.size()); + } + } +} + +std::string parameter_of(const masd_column& c) { + const auto t = c.key == key_kind::ord ? std::string("std::size_t") + : base_type(c); + return (is_arithmetic(t) ? t + " " : "const " + t + "& ") + c.member; +} + +void add_copy(builder& b, value_id m, const masd_entity& e) { + std::vector columns; + const auto parameters = b.list(m, "copy_parameters"); + const auto fields = b.list(m, "copy_fields"); + for (const auto& c : e.columns) { + if (!in_copy(c)) + continue; + columns.push_back(c.name); + if (is_parameter(c)) + b.set(b.append_object(parameters), "declaration", parameter_of(c)); + b.set(b.append_object(fields), "expression", + is_parameter(c) ? c.member : "r." + c.member); + } + const auto lines = wrapped(columns, 68); + const auto list = b.list(m, "copy_column_lines"); + for (std::size_t i = 0; i < lines.size(); ++i) { + const auto l = b.append_object(list); + b.set(l, "text", lines[i]); + add_last(b, l, i + 1 == lines.size()); + } +} + +std::string column_definition(const masd_column& c, + const masd_entity& e, bool single_key) { + auto out = c.name + " " + c.sql_type; + if (c.key == key_kind::identity) + out += " GENERATED ALWAYS AS IDENTITY"; + if (!c.generated.empty()) + out += " GENERATED ALWAYS AS (" + c.generated + ") STORED"; + if (c.primary_key && single_key) + out += " PRIMARY KEY"; + else if (!c.nullable) + out += " NOT NULL"; + if (c.unique) + out += " UNIQUE"; + if (!c.default_value.empty()) + out += " DEFAULT " + c.default_value; + for (const auto& f : e.foreign_keys) { + if (f.column != c.name) + continue; + out += " REFERENCES " + f.references; + if (f.cascade) + out += " ON DELETE CASCADE"; + } + if (!c.values.empty()) { + out += " CHECK (" + c.name + " IN ("; + for (std::size_t i = 0; i < c.values.size(); ++i) + out += (i ? ", '" : "'") + c.values[i] + "'"; + out += "))"; + } + return out; +} + +std::string joined(const std::vector& names) { + std::string out; + for (const auto& n : names) + out += (out.empty() ? "" : ", ") + n; + return out; +} + +std::string qualified(const masd_entity& e) { + return e.schema + "." + e.entity; +} + +void add_table(builder& b, value_id list, const masd_entity& e) { + const auto t = b.append_object(list); + b.set(t, "table", qualified(e)); + b.set(t, "retained", e.retained); + std::vector definitions; + std::vector keys; + for (const auto& c : e.columns) + if (c.primary_key) + keys.push_back(c.name); + for (const auto& c : e.columns) + definitions.push_back(column_definition(c, e, keys.size() == 1)); + if (keys.size() > 1) + definitions.push_back("PRIMARY KEY (" + joined(keys) + ")"); + for (const auto& u : e.uniques) + definitions.push_back("UNIQUE (" + joined(u) + ")"); + for (const auto& check : e.checks) + definitions.push_back("CHECK (" + check + ")"); + const auto defs = b.list(t, "definitions"); + for (std::size_t i = 0; i < definitions.size(); ++i) { + const auto d = b.append_object(defs); + b.set(d, "definition", definitions[i]); + add_last(b, d, i + 1 == definitions.size()); + } + const auto indexes = b.list(t, "indexes"); + for (const auto& i : e.indexes) { + std::vector columns; + for (const auto& c : i.columns) + columns.push_back(i.opclass.empty() ? c : c + " " + i.opclass); + auto s = std::string(i.unique ? "CREATE UNIQUE INDEX " : + "CREATE INDEX ") + e.entity + "_" + i.name + " ON " + + qualified(e); + if (!i.method.empty()) + s += " USING " + i.method; + s += " (" + joined(columns) + ")"; + if (!i.where.empty()) + s += " WHERE " + i.where; + b.set(b.append_object(indexes), "statement", s + ";"); + } +} + +/** + * @brief The tables of @p schema among @p tables, each after the tables it + * references, ties broken by name. + */ +std::vector ordered(std::string_view schema, + std::span tables, std::set& created) { + std::map pending; + for (const auto& e : tables) + if (e.schema == schema) + pending.emplace(qualified(e), &e); + std::vector out; + while (!pending.empty()) { + const auto ready = std::ranges::find_if(pending, [&](const auto& p) { + return std::ranges::all_of(p.second->foreign_keys, + [&](const auto& f) { + return f.references == p.first || + created.contains(f.references); + }); + }); + if (ready == pending.end()) + throw std::runtime_error("codegen: the tables of the schema " + + std::string(schema) + " reference a table no listed schema " + "creates before them, or each other in a cycle: " + + pending.begin()->first); + created.insert(ready->first); + out.push_back(ready->second); + pending.erase(ready); + } + return out; +} + +} + +value_id masd_entity_context(builder& b, value_id library, + const masd_entity& e, const compass::model::ops::custom_types& custom) { + const auto context = with_library(b, library); + const auto m = b.object(context, "masd_entity"); + const auto component = e.product + "." + e.component; + const auto ns = e.product + "::" + e.component; + b.set(m, "table", qualified(e)); + b.set(m, "entity", e.entity); + b.set(m, "row_type", e.row_type); + b.set(m, "types_namespace", ns + "::types"); + b.set(m, "io_namespace", ns + "::io"); + b.set(m, "row_guard", upper(component + "/types/" + e.entity + + "_row.hpp")); + b.set(m, "copy_guard", upper(component + "/io/" + e.entity + + "_copy.hpp")); + b.set(m, "row_include", component + "/types/" + e.entity + "_row.hpp"); + b.set(m, "copy_include", component + "/io/" + e.entity + "_copy.hpp"); + b.set(m, "brief", e.brief); + std::vector row_types; + for (const auto& c : e.columns) { + if (in_row(c)) + row_types.push_back(member_type(c)); + if (!c.values.empty()) + row_types.insert(row_types.end(), + {"std::optional", "std::string_view"}); + } + add_includes(b, m, row_types, custom, {}); + add_enums(b, m, e); + const auto members = b.list(m, "members"); + for (const auto& c : e.columns) { + if (!in_row(c)) + continue; + const auto member = b.append_object(members); + b.set(member, "member", c.member); + b.set(member, "cpp_type", member_type(c)); + b.set(member, "initializer", initializer(c)); + } + std::vector parameter_types{"std::string_view"}; + for (const auto& c : e.columns) + if (is_parameter(c)) + parameter_types.push_back(c.key == key_kind::ord + ? "std::size_t" : base_type(c)); + const auto copy = b.object(m, "copy"); + add_includes(b, copy, parameter_types, custom, + {"\"" + component + "/ops/copy_text.hpp\"", + "\"" + component + "/types/" + e.entity + "_row.hpp\""}); + add_copy(b, m, e); + return context; +} + +value_id masd_schema_context(builder& b, value_id library, + const mtypes::masd_schema& s, std::span tables) { + const auto context = with_library(b, library); + const auto m = b.object(context, "masd_schema"); + const auto schemas = b.list(m, "schemas"); + std::set created; + for (const auto& name : s.schemas) { + const auto schema = b.append_object(schemas); + b.set(schema, "name", name); + const auto list = b.list(schema, "tables"); + for (const auto* e : ordered(name, tables, created)) + add_table(b, list, *e); + } + const auto functions = b.list(m, "functions"); + for (const auto& f : s.functions) { + auto sql = f; + while (!sql.empty() && std::isspace( + static_cast(sql.back()))) + sql.pop_back(); + b.set(b.append_object(functions), "sql", sql); + } + return context; +} + +} diff --git a/projects/compass.codegen/src/ops/physical_space.cpp b/projects/compass.codegen/src/ops/physical_space.cpp index b061db49..1e44c36d 100644 --- a/projects/compass.codegen/src/ops/physical_space.cpp +++ b/projects/compass.codegen/src/ops/physical_space.cpp @@ -634,6 +634,24 @@ std::vector field_group_placeholders(const model_tables& t, {"{EntityPascal}", snake_to_pascal(singular)}}; } +/** + * @brief The placeholders of a model of the MASD library: its component's + * directory and, for a table, its entity. + */ +std::vector masd_placeholders(const model_tables& t, + value_id model) { + return {{"{component_dir}", get_or(t, model, "product", "") + "." + + get_or(t, model, "component", "")}, + {"{entity}", get_or(t, model, "entity_singular", "")}}; +} + +/** + * @brief The root of @p address: its first part. + */ +std::string_view root_of(std::string_view address) { + return address.substr(0, address.find('.')); +} + /** * @brief resolve_targets' gates for the domain entity @p entity of the * model at @p model_path: drops from @p facets what the entity cannot @@ -838,7 +856,9 @@ std::vector model_units(const types::physical_space& g, const types::checkout_registry& registry, std::string_view type, const model_tables& models, value_id model, std::string_view model_path, std::span properties) { - const auto o = enabled_overrides(properties, g.root); + auto o = enabled_overrides(properties, g.root); + if (g.root != masd_root) + o.merge(enabled_overrides(properties, masd_root)); const auto& f = g.facets; const auto& a = g.archetypes; @@ -854,7 +874,8 @@ std::vector model_units(const types::physical_space& g, named = named || (it != o.end() && it->second); } if (named || is_enabled(f.addresses[i], f.addresses[i], - f.technical_spaces[i], g.root, o, f.defaults[i] != 0)) + f.technical_spaces[i], root_of(f.addresses[i]), o, + f.defaults[i] != 0)) facets.insert(f.addresses[i]); } @@ -885,6 +906,8 @@ std::vector model_units(const types::physical_space& g, : type == "field_group" ? field_group_placeholders(models, owned, g.root) : type == "family" ? family_placeholders(models, owned, g.root) + : type == "masd_entity" || type == "masd_schema" + ? masd_placeholders(models, owned) : std::vector{}; std::vector deferred; @@ -903,7 +926,7 @@ std::vector model_units(const types::physical_space& g, return a.addresses[j] == under(g.root, w); })) continue; - if (!is_enabled(a.addresses[j], facet, ts, g.root, o, + if (!is_enabled(a.addresses[j], facet, ts, root_of(facet), o, a.defaults[j] != 0)) continue; if (a.template_names[j].empty() || a.outputs[j].empty()) diff --git a/projects/compass.codegen/tests/CMakeLists.txt b/projects/compass.codegen/tests/CMakeLists.txt index 12eeee3b..e49c3f5f 100644 --- a/projects/compass.codegen/tests/CMakeLists.txt +++ b/projects/compass.codegen/tests/CMakeLists.txt @@ -52,6 +52,7 @@ add_executable(${tests_target_name} ops_entity_surfaces_tests.cpp ops_entity_typescript_tests.cpp ops_library_tests.cpp + ops_masd_context_tests.cpp ops_model_contexts_tests.cpp ops_output_tests.cpp ops_physical_space_tests.cpp @@ -61,7 +62,8 @@ add_executable(${tests_target_name} target_compile_definitions(${tests_target_name} PRIVATE COMPASS_CODEGEN_SPEC_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data/mustache_spec" - COMPASS_CODEGEN_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data") + COMPASS_CODEGEN_TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/data" + COMPASS_MASD_TEMPLATES_DIR="${CMAKE_SOURCE_DIR}/share/masd/templates") target_link_libraries(${tests_target_name} PRIVATE diff --git a/projects/compass.codegen/tests/ops_masd_context_tests.cpp b/projects/compass.codegen/tests/ops_masd_context_tests.cpp new file mode 100644 index 00000000..96990989 --- /dev/null +++ b/projects/compass.codegen/tests/ops_masd_context_tests.cpp @@ -0,0 +1,262 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.codegen/ops/masd_context.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include "compass.codegen/ops/compile.hpp" +#include "compass.codegen/ops/context.hpp" +#include "compass.codegen/ops/output.hpp" + +namespace { + +namespace mtypes = compass::model::types; +using namespace compass::codegen; +using Catch::Matchers::ContainsSubstring; + +mtypes::masd_column column(std::string name, std::string type) { + mtypes::masd_column c; + c.name = name; + c.member = std::move(name); + c.sql_type = std::move(type); + return c; +} + +mtypes::masd_entity table(std::string schema, std::string entity) { + mtypes::masd_entity e; + e.product = "compass"; + e.component = "db"; + e.schema = std::move(schema); + e.row_type = entity + "_row"; + e.entity = std::move(entity); + return e; +} + +/** + * @brief The template of the MASD library that compass ships, as its + * archetype page tangles it. + */ +std::string library_template(const std::string& name) { + std::ifstream is(std::string(COMPASS_MASD_TEMPLATES_DIR) + "/" + name, + std::ios::binary); + REQUIRE(is); + return {std::istreambuf_iterator(is), {}}; +} + +/** + * @brief @p name rendered from the context @p make builds. + */ +template +std::string rendered(const std::string& name, Make make) { + mtypes::model_tables tables; + compass::model::ops::builder b(tables); + const auto library = ops::library_values(b, "Licence.", "", 2026); + const auto context = make(b, library); + std::string out; + ops::render_output(out, name, ops::compile(library_template(name)), + tables, context); + return out; +} + +/** + * @brief A run of a campaign: an identity key, a now() default the + * database writes, a nullable value list and a foreign key. + */ +mtypes::masd_entity run() { + auto e = table("activity", "run"); + e.retained = true; + auto id = column("id", "bigint"); + id.primary_key = true; + id.key = mtypes::key_kind::identity; + auto campaign = column("campaign", "bigint"); + auto started = column("started_at", "timestamptz"); + started.default_value = "now()"; + started.writer = mtypes::written_by::database; + auto outcome = column("outcome", "text"); + outcome.nullable = true; + outcome.values = {"passed", "failed"}; + outcome.enum_name = "run_outcome"; + e.columns = {id, campaign, started, outcome}; + e.foreign_keys = {{"campaign", "activity.campaign", false}}; + e.indexes = {{"campaign", {"campaign"}, false, "", "", ""}}; + return e; +} + +mtypes::masd_entity campaign() { + auto e = table("activity", "campaign"); + auto id = column("id", "bigint"); + id.primary_key = true; + id.key = mtypes::key_kind::identity; + e.columns = {id, column("story_id", "text"), column("environment", "text")}; + e.uniques = {{"environment", "story_id"}}; + return e; +} + +/** + * @brief A heading of a document: an owner's hash and an ord as its key, + * a member named apart from its column, and a value list with a default. + */ +mtypes::masd_entity heading() { + auto e = table("corpus", "heading"); + auto hash = column("hash", "bytea"); + hash.cpp_type = "store::types::blob_id"; + hash.primary_key = true; + hash.key = mtypes::key_kind::content_hash; + auto ord = column("ord", "integer"); + ord.primary_key = true; + ord.key = mtypes::key_kind::ord; + auto parent = column("parent_ord", "integer"); + parent.member = "parent"; + parent.nullable = true; + auto state = column("state", "text"); + state.values = {"open", "closed"}; + state.default_value = "'closed'"; + state.enum_name = "heading_state"; + auto tags = column("tags", "text[]"); + e.columns = {hash, ord, parent, state, tags}; + e.indexes = {{"tags", {"tags"}, false, "gin", "", "parent_ord > 0"}}; + return e; +} + +} + +TEST_CASE("schema.sql creates each table after the tables it references", + "[codegen][masd]") { + mtypes::masd_schema s; + s.schemas = {"activity"}; + s.functions = {"CREATE FUNCTION activity.f() RETURNS int " + "LANGUAGE sql AS $$ SELECT 1 $$;\n"}; + auto attached = table("activity", "attached"); + attached.columns = {column("run", "bigint")}; + attached.foreign_keys = {{"run", "activity.run", true}}; + const std::vector tables{attached, run(), campaign(), + table("other", "ignored")}; + const auto sql = rendered("masd_sql_schema.sql.mustache", + [&](auto& b, auto library) { + return ops::masd_schema_context(b, library, s, tables); + }); + const auto at = [&](std::string_view text) { return sql.find(text); }; + CHECK(at("CREATE SCHEMA activity;") < at("CREATE TABLE activity.campaign")); + CHECK(at("CREATE TABLE activity.campaign") < at("CREATE TABLE activity.run")); + CHECK(at("CREATE TABLE activity.run") < + at("CREATE TABLE activity.attached")); + CHECK_THAT(sql, ContainsSubstring( + " run bigint NOT NULL REFERENCES activity.run ON DELETE CASCADE\n")); + CHECK(at("CREATE FUNCTION") > at("CREATE TABLE activity.run")); + CHECK(at("other.ignored") == std::string::npos); + CHECK_THAT(sql, ContainsSubstring( + " id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,\n" + " story_id text NOT NULL,\n" + " environment text NOT NULL,\n" + " UNIQUE (environment, story_id)\n);")); + CHECK_THAT(sql, ContainsSubstring( + "-- activity.run is retained: its rows exist nowhere else")); + CHECK_THAT(sql, ContainsSubstring( + " campaign bigint NOT NULL REFERENCES activity.campaign,\n" + " started_at timestamptz NOT NULL DEFAULT now(),\n" + " outcome text CHECK (outcome IN ('passed', 'failed'))\n);")); + CHECK_THAT(sql, ContainsSubstring( + "CREATE INDEX run_campaign ON activity.run (campaign);")); +} + +TEST_CASE("schema.sql refuses tables that reference each other", + "[codegen][masd]") { + mtypes::masd_schema s; + s.schemas = {"activity"}; + auto a = campaign(); + a.foreign_keys = {{"story_id", "activity.run", false}}; + const std::vector tables{run(), a}; + mtypes::model_tables t; + compass::model::ops::builder b(t); + CHECK_THROWS_AS(ops::masd_schema_context(b, b.detached_object(), s, + tables), std::runtime_error); +} + +TEST_CASE("a composite key, a partial index and a value list render as " + "PostgreSQL states them", "[codegen][masd]") { + mtypes::masd_schema s; + s.schemas = {"corpus"}; + const std::vector tables{heading()}; + const auto sql = rendered("masd_sql_schema.sql.mustache", + [&](auto& b, auto library) { + return ops::masd_schema_context(b, library, s, tables); + }); + CHECK_THAT(sql, ContainsSubstring( + " state text NOT NULL DEFAULT 'closed' CHECK (state IN ('open', " + "'closed')),\n")); + CHECK_THAT(sql, ContainsSubstring(" PRIMARY KEY (hash, ord)\n);")); + CHECK_THAT(sql, ContainsSubstring("CREATE INDEX heading_tags ON " + "corpus.heading USING gin (tags) WHERE parent_ord > 0;")); +} + +TEST_CASE("a row holds what the row writes, and its key columns are the " + "COPY writer's arguments", "[codegen][masd]") { + const compass::model::ops::custom_types custom{ + {"store::types::blob_id", "\"compass.store/types/blob_id.hpp\""}}; + const auto make = [&](auto& b, auto library) { + return ops::masd_entity_context(b, library, heading(), custom); + }; + const auto row = rendered("masd_cpp_row.hpp.mustache", make); + CHECK_THAT(row, ContainsSubstring( + "struct heading_row {\n" + " std::optional parent;\n" + " heading_state state = heading_state::closed;\n" + " std::vector tags;\n" + "};")); + CHECK_THAT(row, ContainsSubstring( + "constexpr std::optional heading_state_of(")); + CHECK_THAT(row, ContainsSubstring("#include \n#include " + "\n#include \n#include \n#include " + "\n\nnamespace compass::db::types {")); + + const auto header = rendered("masd_cpp_copy.hpp.mustache", make); + CHECK_THAT(header, ContainsSubstring( + "inline constexpr std::string_view heading_copy_columns =\n" + " \"hash, ord, parent_ord, state, tags\";")); + CHECK_THAT(header, ContainsSubstring( + "void write_copy(ops::copy_writer& w,\n" + " const store::types::blob_id& hash,\n" + " std::size_t ord,\n" + " const types::heading_row& r);")); + CHECK_THAT(header, ContainsSubstring( + "#include \"compass.store/types/blob_id.hpp\"")); + + const auto impl = rendered("masd_cpp_copy.cpp.mustache", make); + CHECK_THAT(impl, ContainsSubstring( + " w.field(hash);\n w.field(ord);\n w.field(r.parent);\n" + " w.field(r.state);\n w.field(r.tags);\n w.end();")); +} + +TEST_CASE("a SQL type with no C++ type is refused unless the model states " + "one", "[codegen][masd]") { + auto e = table("corpus", "section"); + e.columns = {column("tsv", "tsvector")}; + mtypes::model_tables t; + compass::model::ops::builder b(t); + CHECK_THROWS_AS(ops::masd_entity_context(b, b.detached_object(), e, {}), + std::runtime_error); + e.columns[0].writer = mtypes::written_by::writer; + CHECK_NOTHROW(ops::masd_entity_context(b, b.detached_object(), e, {})); +} diff --git a/projects/compass.model/include/compass.model/ops/masd_entity.hpp b/projects/compass.model/include/compass.model/ops/masd_entity.hpp new file mode 100644 index 00000000..7aee6889 --- /dev/null +++ b/projects/compass.model/include/compass.model/ops/masd_entity.hpp @@ -0,0 +1,47 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef COMPASS_MODEL_OPS_MASD_ENTITY_HPP +#define COMPASS_MODEL_OPS_MASD_ENTITY_HPP + +#include "compass.model/ops/load.hpp" +#include "compass.model/types/masd_entity.hpp" + +namespace compass::model::ops { + +/** + * @brief Reads @p d, a model of #+type: masd.codegen.entity, and the + * profile page its * Flags drawer binds, which @p find gives. + * @throws model_error naming what the model says that the format does not + * have: an unknown property, profile, profile feature, section or table + * header, a value outside a property's list, or a column that a foreign + * key, index or unique constraint names and the model lacks. + */ +[[nodiscard]] types::masd_entity read_masd_entity(const document& d, + const document_finder& find); + +/** + * @brief Reads @p d, a model of #+type: masd.codegen.schema. + * @throws model_error as read_masd_entity does. + */ +[[nodiscard]] types::masd_schema read_masd_schema(const document& d); + +} + +#endif diff --git a/projects/compass.model/include/compass.model/types/masd_entity.hpp b/projects/compass.model/include/compass.model/types/masd_entity.hpp new file mode 100644 index 00000000..7c2f7918 --- /dev/null +++ b/projects/compass.model/include/compass.model/types/masd_entity.hpp @@ -0,0 +1,137 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#ifndef COMPASS_MODEL_TYPES_MASD_ENTITY_HPP +#define COMPASS_MODEL_TYPES_MASD_ENTITY_HPP + +#include +#include +#include + +namespace compass::model::types { + +/** + * @brief What a key column is to its row. A natural key is a column of the + * row like any other. The others stay out of the row type: a content hash + * is the identity of the aggregate the row belongs to, an owner is the key + * of the row that owns it, an ord is the row's place in its owner's vector, + * and an identity is generated by the database. + */ +enum class key_kind : std::uint8_t { + none, + natural, + content_hash, + owner, + ord, + identity +}; + +/** + * @brief Who writes a column. The row type and the COPY column list carry + * only what the row writes; the database writes a defaulted or generated + * column, and the writer's own SQL sets or computes the rest. + */ +enum class written_by : std::uint8_t { row, database, writer }; + +/** + * @brief One column of a masd.codegen.entity model, in table order. + * + * member is the name of the row's member, the column's name unless the + * model says otherwise. cpp_type is the type the model states, empty when + * the context derives it from sql_type. values is the closed list of a + * text column, which becomes a check and an enumeration named enum_name. + * generated is the expression of a stored generated column. + */ +struct masd_column { + std::string name; + std::string member; + std::string sql_type; + std::string cpp_type; + std::string default_value; + std::string generated; + std::string enum_name; + std::vector values; + bool nullable = false; + bool primary_key = false; + bool unique = false; + key_kind key = key_kind::none; + written_by writer = written_by::row; +}; + +/** + * @brief A single-column foreign key: the column, the table it references, + * schema-qualified, and whether deleting that row deletes this one. + */ +struct masd_foreign_key { + std::string column; + std::string references; + bool cascade = false; +}; + +/** + * @brief An index: its name within the table, its columns, and the access + * method, operator class and predicate of a partial index, when stated. + */ +struct masd_index { + std::string name; + std::vector columns; + bool unique = false; + std::string method; + std::string opclass; + std::string where; +}; + +/** + * @brief A table of a masd.codegen.entity model and the row type over it. + * + * retained marks a table whose rows exist nowhere else, so a change to it + * needs a migration that says what becomes of them; its profile sets it. + * uniques are the table's unique constraints, each a list of columns. + */ +struct masd_entity { + std::string product; + std::string component; + std::string schema; + std::string entity; + std::string row_type; + std::string brief; + std::string profile; + bool retained = false; + std::vector columns; + std::vector foreign_keys; + std::vector indexes; + std::vector checks; + std::vector> uniques; +}; + +/** + * @brief A masd.codegen.schema model: the schemas of a component's + * database in the order they are created, and the functions created after + * every table, each as the SQL that creates it. + */ +struct masd_schema { + std::string product; + std::string component; + std::vector schemas; + std::vector functions; +}; + +} + +#endif diff --git a/projects/compass.model/include/compass.model/types/model_tables.hpp b/projects/compass.model/include/compass.model/types/model_tables.hpp index 5fe77622..665c7733 100644 --- a/projects/compass.model/include/compass.model/types/model_tables.hpp +++ b/projects/compass.model/include/compass.model/types/model_tables.hpp @@ -48,17 +48,21 @@ enum class model_type : std::uint8_t { service_registry, asset_class_catalogue, trade_type_catalogue, - outcome_catalogue + outcome_catalogue, + masd_entity, + masd_schema }; inline constexpr model_type model_types[] = { model_type::entity, model_type::component, model_type::operation, model_type::field_group, model_type::junction, model_type::family, model_type::service_registry, model_type::asset_class_catalogue, - model_type::trade_type_catalogue, model_type::outcome_catalogue}; + model_type::trade_type_catalogue, model_type::outcome_catalogue, + model_type::masd_entity, model_type::masd_schema}; /** - * @brief The name of @p t as #+type: writes it after ores.codegen. + * @brief The name of @p t as #+type: writes it after ores.codegen, or, for + * a type of the MASD library, after masd.codegen with masd_ before it. */ [[nodiscard]] constexpr std::string_view name_of(model_type t) noexcept { switch (t) { @@ -72,6 +76,8 @@ inline constexpr model_type model_types[] = { case model_type::asset_class_catalogue: return "asset_class_catalogue"; case model_type::trade_type_catalogue: return "trade_type_catalogue"; case model_type::outcome_catalogue: return "outcome_catalogue"; + case model_type::masd_entity: return "masd_entity"; + case model_type::masd_schema: return "masd_schema"; } return ""; } diff --git a/projects/compass.model/src/CMakeLists.txt b/projects/compass.model/src/CMakeLists.txt index d4ad17cb..e4974e79 100644 --- a/projects/compass.model/src/CMakeLists.txt +++ b/projects/compass.model/src/CMakeLists.txt @@ -31,6 +31,7 @@ add_library(${lib_target_name} ops/field_group.cpp ops/junction.cpp ops/load.cpp + ops/masd_entity.cpp ops/messages.cpp ops/operation.cpp ops/outcome_catalogue.cpp diff --git a/projects/compass.model/src/ops/load.cpp b/projects/compass.model/src/ops/load.cpp index abff100c..f2432b27 100644 --- a/projects/compass.model/src/ops/load.cpp +++ b/projects/compass.model/src/ops/load.cpp @@ -29,12 +29,17 @@ using types::model_type; using types::value_id; std::optional model_type_of(std::string_view type) noexcept { + if (type == "masd.codegen.entity") + return model_type::masd_entity; + if (type == "masd.codegen.schema") + return model_type::masd_schema; constexpr std::string_view prefix = "ores.codegen."; if (!type.starts_with(prefix)) return std::nullopt; type.remove_prefix(prefix.size()); for (const auto t : types::model_types) { - if (types::name_of(t) == type) + if (t != model_type::masd_entity && t != model_type::masd_schema && + types::name_of(t) == type) return t; } return std::nullopt; @@ -121,6 +126,12 @@ types::model_id load_model(builder& b, const document& d, model_type t, case model_type::trade_type_catalogue: load_trade_type_catalogue(c, root); break; + case model_type::masd_entity: + load_masd_entity(c, root); + break; + case model_type::masd_schema: + load_masd_schema(c, root); + break; } } catch (const model_error& e) { auto& v = b.tables().values; diff --git a/projects/compass.model/src/ops/loaders.hpp b/projects/compass.model/src/ops/loaders.hpp index 99f787c3..cf16e2c6 100644 --- a/projects/compass.model/src/ops/loaders.hpp +++ b/projects/compass.model/src/ops/loaders.hpp @@ -234,6 +234,13 @@ void load_service_registry(load_context& c, types::value_id root); void load_junction(load_context& c, types::value_id root); void load_trade_type_catalogue(load_context& c, types::value_id root); +/** + * @brief Writes under masd_entity and masd_schema what the physical space + * resolves an output path from: the component, the entity and its schema. + */ +void load_masd_entity(load_context& c, types::value_id root); +void load_masd_schema(load_context& c, types::value_id root); + } #endif diff --git a/projects/compass.model/src/ops/masd_entity.cpp b/projects/compass.model/src/ops/masd_entity.cpp new file mode 100644 index 00000000..0c1f78d5 --- /dev/null +++ b/projects/compass.model/src/ops/masd_entity.cpp @@ -0,0 +1,360 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include "compass.model/ops/masd_entity.hpp" + +#include +#include +#include "loaders.hpp" +#include "text.hpp" + +namespace compass::model::ops { + +namespace { + +using types::key_kind; +using types::written_by; + +constexpr std::string_view flag_keys[] = {"product", "component", "schema", + "profile", "row_type"}; + +constexpr std::string_view column_keys[] = {"type", "cpp_type", "nullable", + "default", "primary_key", "key_kind", "written_by", "computed", + "generated", "values", "enum", "member", "unique"}; + +constexpr std::string_view foreign_key_keys[] = {"references", "on_delete"}; + +constexpr std::string_view index_headers[] = {"name", "columns", "unique", + "where", "using", "opclass"}; + +constexpr std::string_view sql_sections[] = {"Indexes", "Checks", "Unique"}; + +constexpr std::string_view schema_flag_keys[] = {"product", "component"}; + +/** + * @brief The features a profile of a masd.codegen.entity may assign. + */ +constexpr std::string_view profile_features[] = {"retained"}; + +std::string listed(std::span names) { + std::string out; + for (const auto n : names) + out += (out.empty() ? "" : ", ") + std::string(n); + return out; +} + +void require_known(std::string_view key, std::span known, + std::string_view where) { + if (std::ranges::find(known, key) == known.end()) + throw model_error(std::string(where) + " has the property '" + + std::string(key) + "', which a masd.codegen model does not " + "have; it has " + listed(known)); +} + +bool flag(std::string_view value, std::string_view where) { + const auto v = trim(value); + if (v == "true") + return true; + if (v == "false") + return false; + throw model_error(std::string(where) + " is '" + std::string(v) + + "', which is neither true nor false"); +} + +std::vector words(std::string_view s, char separator = ' ') { + std::vector out; + while (!s.empty()) { + const auto at = separator == ' ' + ? s.find_first_of(" \t") : s.find(separator); + const auto word = trim(s.substr(0, at)); + if (!word.empty()) + out.emplace_back(word); + if (at == std::string_view::npos) + break; + s.remove_prefix(at + 1); + } + return out; +} + +key_kind key_kind_of(std::string_view v, std::string_view where) { + constexpr std::pair kinds[] = { + {"natural", key_kind::natural}, {"content_hash", key_kind::content_hash}, + {"owner", key_kind::owner}, {"ord", key_kind::ord}, + {"identity", key_kind::identity}}; + for (const auto& [name, kind] : kinds) + if (name == v) + return kind; + throw model_error(std::string(where) + " has the key_kind '" + + std::string(v) + "'; a key is natural, content_hash, owner, ord or " + "identity"); +} + +/** + * @brief The feature a cell of an Assignments table names: the + * description of a link, or the cell without its verbatim markers. + */ +std::string_view feature_of(std::string_view cell) { + cell = trim(cell); + if (cell.starts_with("[[")) { + const auto open = cell.find("]["); + const auto close = cell.rfind("]]"); + if (open != std::string_view::npos && close != std::string_view::npos && + close > open) + return trim(cell.substr(open + 2, close - open - 2)); + } + while (cell.starts_with('=')) + cell.remove_prefix(1); + while (cell.ends_with('=')) + cell.remove_suffix(1); + return cell; +} + +void apply_profile(types::masd_entity& e, const document_finder& find) { + if (e.profile.empty()) + return; + std::string file = e.profile; + std::ranges::replace(file, '-', '_'); + const auto path = "projects/modeling/variability_" + file + ".org"; + const auto d = find(path); + if (!d) + throw model_error("unknown profile '" + e.profile + "': no page " + + path); + outline o; + build_outline(d->source, *d->tables, o); + for (const auto& row : first_table_rows(o, section(o, node_id{0}, + "Assignments"))) { + const auto feature = feature_of(row.value_or("Feature")); + require_known(feature, profile_features, + "the profile '" + e.profile + "'"); + if (feature == "retained") + e.retained = flag(row.value_or("Value"), + "the profile's retained"); + } +} + +types::masd_column column_of(const outline& o, node_id n) { + types::masd_column c; + c.name = std::string(trim(o.titles[n.value])); + c.member = c.name; + const auto where = "the column '" + c.name + "'"; + for (const auto& [key, raw] : properties(o, n)) { + require_known(key, column_keys, where); + const auto value = trim(raw); + const auto at = where + "'s " + std::string(key); + if (key == "type") c.sql_type = value; + else if (key == "cpp_type") c.cpp_type = value; + else if (key == "default") c.default_value = value; + else if (key == "generated") c.generated = value; + else if (key == "enum") c.enum_name = value; + else if (key == "member") c.member = value; + else if (key == "values") c.values = words(value); + else if (key == "nullable") c.nullable = flag(value, at); + else if (key == "primary_key") c.primary_key = flag(value, at); + else if (key == "unique") c.unique = flag(value, at); + else if (key == "key_kind") c.key = key_kind_of(value, where); + else if (key == "written_by" || key == "computed") { + if (value == "database" && key == "written_by") + c.writer = written_by::database; + else if (value == "writer") + c.writer = written_by::writer; + else + throw model_error(at + " is '" + std::string(value) + + "'; it is " + (key == "computed" ? "writer" + : "database or writer")); + } + } + if (c.sql_type.empty()) + throw model_error(where + " states no type"); + if (c.key != key_kind::none && !c.primary_key) + throw model_error(where + " has a key_kind but is not a primary key"); + if (!c.values.empty() && c.sql_type != "text") + throw model_error(where + " has values but is not text"); + if (!c.generated.empty()) + c.writer = written_by::database; + return c; +} + +void require_column(const types::masd_entity& e, std::string_view name, + std::string_view where) { + if (std::ranges::find(e.columns, name, &types::masd_column::name) == + e.columns.end()) + throw model_error(std::string(where) + " names the column '" + + std::string(name) + "', which the model does not have"); +} + +void require_headers(const std::vector& rows, + std::span known, std::string_view where) { + for (const auto& row : rows) + for (const auto& cell : row.cells) + if (std::ranges::find(known, trim(cell.key)) == known.end()) + throw model_error(std::string(where) + " has the column '" + + std::string(cell.key) + "'; it has " + listed(known)); +} + +void read_sql(const outline& o, types::masd_entity& e) { + const auto sql = section(o, node_id{0}, "SQL"); + for (const auto n : children(o, sql)) { + const auto title = trim(o.titles[n.value]); + if (std::ranges::find(sql_sections, title) == std::end(sql_sections)) + throw model_error("* SQL has the section '" + std::string(title) + + "'; it has " + listed(sql_sections)); + const auto rows = own_table_rows(o, n); + if (title == "Indexes") { + require_headers(rows, index_headers, "the Indexes table"); + for (const auto& row : rows) { + types::masd_index i; + i.name = std::string(trim(row.value_or("name"))); + i.columns = words(row.value_or("columns"), ','); + i.unique = flag(row.value_or("unique", "false"), + "the index '" + i.name + "''s unique"); + i.method = std::string(trim(row.value_or("using"))); + i.opclass = std::string(trim(row.value_or("opclass"))); + i.where = std::string(trim(row.value_or("where"))); + for (const auto& c : i.columns) + require_column(e, c, "the index '" + i.name + "'"); + e.indexes.push_back(std::move(i)); + } + } else if (title == "Checks") { + constexpr std::string_view headers[] = {"expression"}; + require_headers(rows, headers, "the Checks table"); + for (const auto& row : rows) + e.checks.emplace_back(trim(row.value_or("expression"))); + } else { + constexpr std::string_view headers[] = {"columns"}; + require_headers(rows, headers, "the Unique table"); + for (const auto& row : rows) { + auto columns = words(row.value_or("columns"), ','); + for (const auto& c : columns) + require_column(e, c, "a unique constraint"); + e.uniques.push_back(std::move(columns)); + } + } + } +} + +} + +types::masd_entity read_masd_entity(const document& d, + const document_finder& find) { + outline o; + build_outline(d.source, *d.tables, o); + types::masd_entity e; + for (const auto& [key, value] : properties(o, section(o, node_id{0}, + "Flags"))) { + require_known(key, flag_keys, "* Flags"); + const std::string v(trim(value)); + if (key == "product") e.product = v; + else if (key == "component") e.component = v; + else if (key == "schema") e.schema = v; + else if (key == "profile") e.profile = v; + else e.row_type = v; + } + e.entity = std::string(trim(frontmatter(o, "entity_singular").value)); + e.brief = std::string(trim(frontmatter(o, "brief").value)); + if (e.entity.empty()) + throw model_error("the model states no #+entity_singular:"); + if (e.schema.empty()) + throw model_error("* Flags states no schema"); + if (e.row_type.empty()) + e.row_type = e.entity + "_row"; + apply_profile(e, find); + + for (const auto n : children(o, section(o, node_id{0}, "Columns"))) { + auto c = column_of(o, n); + if (c.enum_name.empty() && !c.values.empty()) + c.enum_name = e.entity + "_" + c.name; + if (std::ranges::find(e.columns, c.name, &types::masd_column::name) != + e.columns.end()) + throw model_error("the column '" + c.name + "' is stated twice"); + e.columns.push_back(std::move(c)); + } + if (e.columns.empty()) + throw model_error("the model has no * Columns"); + + for (const auto n : children(o, section(o, node_id{0}, "Foreign keys"))) { + types::masd_foreign_key f; + f.column = std::string(trim(o.titles[n.value])); + const auto where = "the foreign key '" + f.column + "'"; + for (const auto& [key, value] : properties(o, n)) { + require_known(key, foreign_key_keys, where); + if (key == "references") { + f.references = std::string(trim(value)); + } else if (trim(value) == "cascade") { + f.cascade = true; + } else { + throw model_error(where + "'s on_delete is '" + + std::string(trim(value)) + "'; it is cascade"); + } + } + if (f.references.empty()) + throw model_error(where + " states no references"); + require_column(e, f.column, where); + e.foreign_keys.push_back(std::move(f)); + } + read_sql(o, e); + return e; +} + +types::masd_schema read_masd_schema(const document& d) { + outline o; + build_outline(d.source, *d.tables, o); + types::masd_schema s; + for (const auto& [key, value] : properties(o, section(o, node_id{0}, + "Flags"))) { + require_known(key, schema_flag_keys, "* Flags"); + (key == "product" ? s.product : s.component) = trim(value); + } + const auto schemas = own_table_rows(o, section(o, node_id{0}, + "Schemas")); + constexpr std::string_view headers[] = {"name", "description"}; + require_headers(schemas, headers, "the Schemas table"); + for (const auto& row : schemas) + s.schemas.emplace_back(trim(row.value_or("name"))); + if (s.schemas.empty()) + throw model_error("the model names no schema under * Schemas"); + + const auto functions = section(o, node_id{0}, "Functions"); + if (!functions.is_none()) { + const auto end = o.subtree_ends[functions.value]; + for (std::size_t i = 0; i < o.block_nodes.size(); ++i) + if (o.block_nodes[i] >= functions && o.block_nodes[i] < end && + o.block_languages[i] == "sql") + s.functions.emplace_back(o.block_codes[i]); + } + return s; +} + +void load_masd_entity(load_context& c, types::value_id root) { + const auto e = read_masd_entity(c.d, c.find); + const auto m = c.b.object(root, "masd_entity"); + c.b.set(m, "product", e.product); + c.b.set(m, "component", e.component); + c.b.set(m, "schema", e.schema); + c.b.set(m, "entity_singular", e.entity); + c.b.set(m, "row_type", e.row_type); +} + +void load_masd_schema(load_context& c, types::value_id root) { + const auto s = read_masd_schema(c.d); + const auto m = c.b.object(root, "masd_schema"); + c.b.set(m, "product", s.product); + c.b.set(m, "component", s.component); +} + +} diff --git a/projects/compass.model/tests/CMakeLists.txt b/projects/compass.model/tests/CMakeLists.txt index c5b7fe63..1e0ad53c 100644 --- a/projects/compass.model/tests/CMakeLists.txt +++ b/projects/compass.model/tests/CMakeLists.txt @@ -28,6 +28,7 @@ add_executable(${tests_target_name} ops_load_family_tests.cpp ops_load_field_group_tests.cpp ops_load_junction_tests.cpp + ops_load_masd_entity_tests.cpp ops_load_operation_tests.cpp ops_load_outcome_catalogue_tests.cpp ops_load_service_registry_tests.cpp diff --git a/projects/compass.model/tests/load_fixture.hpp b/projects/compass.model/tests/load_fixture.hpp index be6024fe..97149122 100644 --- a/projects/compass.model/tests/load_fixture.hpp +++ b/projects/compass.model/tests/load_fixture.hpp @@ -25,10 +25,12 @@ #include #include #include +#include #include #include "compass.ingest/org/parser.hpp" #include "compass.model/io/json.hpp" #include "compass.model/ops/load.hpp" +#include "compass.model/ops/masd_entity.hpp" namespace compass::model::tests { @@ -93,6 +95,31 @@ class checkout final { return out; } + /** + * @brief Why load_model refuses the model at @p path, or empty when it + * loads. + */ + [[nodiscard]] std::string load_error(std::string_view path) const { + const auto doc = document_of(*index_.at(std::string(path))); + const auto type = ops::model_type_of(ops::declared_type(doc)); + types::model_tables tables; + ops::builder b(tables); + ops::load_cache cache; + std::string error; + std::ignore = ops::load_model(b, doc, *type, finder(), lister(), + cache, &error); + return error; + } + + /** + * @brief The masd.codegen.entity model at @p path, read with every + * other document of the checkout visible to it. + */ + [[nodiscard]] types::masd_entity masd_entity(std::string_view path) const { + return ops::read_masd_entity(document_of(*index_.at(std::string(path))), + finder()); + } + /** * @brief The physical-space overrides of the model at @p path, a later * pair winning as it does in a dict. diff --git a/projects/compass.model/tests/ops_load_masd_entity_tests.cpp b/projects/compass.model/tests/ops_load_masd_entity_tests.cpp new file mode 100644 index 00000000..d34ba4a9 --- /dev/null +++ b/projects/compass.model/tests/ops_load_masd_entity_tests.cpp @@ -0,0 +1,190 @@ +/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- + * + * Copyright (C) 2026 Marco Craveiro + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU General Public License as published by the Free Software + * Foundation; either version 3 of the License, or (at your option) any later + * version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 51 + * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ +#include +#include +#include "load_fixture.hpp" + +namespace { + +using compass::model::tests::checkout; +namespace types = compass::model::types; + +constexpr std::string_view model_path = + "projects/compass.db/modeling/compass.db.step_result.org"; + +const std::string retained_profile = R"org(#+title: Profile: Activity record +#+type: profile + +* Assignments + +| Feature | Value | +|----------+-------| +| retained | true | +)org"; + +std::string model(std::string_view flags, std::string_view outcome_extra, + std::string_view rest = {}) { + return std::string(R"org(#+title: compass.db.step_result +#+type: masd.codegen.entity +#+entity_singular: step_result +#+brief: The outcome of one step of a run. + +* Flags +:PROPERTIES: +:product: compass +:component: db +:schema: activity +)org") + std::string(flags) + R"org(:END: + +* Columns + +** run +:PROPERTIES: +:type: bigint +:primary_key: true +:key_kind: owner +:END: + +** step_ord +:PROPERTIES: +:type: integer +:primary_key: true +:key_kind: natural +:END: + +** outcome +:PROPERTIES: +:type: text +:values: pass fail blocked skipped +)org" + std::string(outcome_extra) + R"org(:END: + +** heading_ord +:PROPERTIES: +:type: integer +:nullable: true +:member: heading +:END: + +* Foreign keys + +** run +:PROPERTIES: +:references: activity.run +:on_delete: cascade +:END: +)org" + std::string(rest); +} + +checkout with(std::string source) { + checkout c; + c.add("projects/modeling/variability_activity_record.org", + retained_profile); + c.add(std::string(model_path), std::move(source)); + return c; +} + +} + +TEST_CASE("a masd.codegen.entity model reads into its table and row", + "[ops][load][masd]") { + const auto c = with(model(":profile: activity-record\n", + ":enum: step_outcome\n", R"org( +* SQL + +** Unique + +| columns | +|-------------------| +| run, heading_ord | +)org")); + REQUIRE(c.load_error(model_path).empty()); + const auto e = c.masd_entity(model_path); + CHECK(e.schema == "activity"); + CHECK(e.row_type == "step_result_row"); + CHECK(e.retained); + REQUIRE(e.columns.size() == 4); + CHECK(e.columns[0].key == types::key_kind::owner); + CHECK(e.columns[2].enum_name == "step_outcome"); + CHECK(e.columns[2].values.size() == 4); + CHECK(e.columns[3].member == "heading"); + CHECK(e.columns[3].nullable); + REQUIRE(e.foreign_keys.size() == 1); + CHECK(e.foreign_keys[0].cascade); + REQUIRE(e.uniques.size() == 1); + CHECK(e.uniques[0] == std::vector{"run", "heading_ord"}); +} + +TEST_CASE("a column's value list names its enumeration after the entity " + "unless the model names it", "[ops][load][masd]") { + const auto c = with(model("", "")); + CHECK(c.masd_entity(model_path).columns[2].enum_name == + "step_result_outcome"); + CHECK_FALSE(c.masd_entity(model_path).retained); +} + +TEST_CASE("a property the format does not have is a diagnostic", + "[ops][load][masd]") { + SECTION("on a column") { + const auto c = with(model("", ":colour: blue\n")); + const auto error = c.load_error(model_path); + CHECK(error.find("the column 'outcome' has the property 'colour'") != + std::string::npos); + } + SECTION("in * Flags") { + const auto c = with(model(":tenant: true\n", "")); + CHECK(c.load_error(model_path).find( + "* Flags has the property 'tenant'") != std::string::npos); + } + SECTION("as a value outside the property's list") { + const auto c = with(model("", ":written_by: someone\n")); + CHECK(c.load_error(model_path).find("'someone'") != + std::string::npos); + } +} + +TEST_CASE("an unknown profile or one with an unknown feature is a " + "diagnostic", "[ops][load][masd]") { + SECTION("a profile with no page") { + const auto c = with(model(":profile: record-everything\n", "")); + CHECK(c.load_error(model_path).find( + "unknown profile 'record-everything'") != std::string::npos); + } + SECTION("a profile of ORE Studio's entities") { + auto c = with(model(":profile: simple-lookup\n", "")); + c.add_modeling_documents(); + CHECK(c.load_error(model_path).find( + "has the property 'has_tenant_id'") != std::string::npos); + } +} + +TEST_CASE("a foreign key or constraint on a column the model lacks is a " + "diagnostic", "[ops][load][masd]") { + const auto c = with(model("", "", R"org( +* SQL + +** Unique + +| columns | +|--------------| +| run, steps | +)org")); + CHECK(c.load_error(model_path).find("names the column 'steps'") != + std::string::npos); +} diff --git a/projects/modeling/cpp_custom_types.org b/projects/modeling/cpp_custom_types.org new file mode 100644 index 00000000..f1bcdbb0 --- /dev/null +++ b/projects/modeling/cpp_custom_types.org @@ -0,0 +1,30 @@ +:PROPERTIES: +:ID: F4A0CD68-9550-4E81-944B-85369F4BCCAB +:END: +#+title: C++ Custom Types +#+description: The registry binding each C++ type a model of compass names, and the standard library does not have, to the header that defines it, so the generated code includes it. +#+type: knowledge +#+level: cross +#+filetags: :codegen:cpp:types:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +A column of a model may name any C++ type with =:cpp_type:=. The code +generated from it must include the header that defines the type, and for a +type outside the standard library only this registry says which header +that is. compass's =codegen= codec reads it from this path, as it reads +ORE Studio's registry from the same path there. + +* Detail + +A row binds one type, as the model spells it, to its header, quoted as the +=#include= writes it. The match covers wrapped forms: a column of +=std::optional= includes the same header as one of +=store::types::blob_id=. A standard type needs no row; the templates derive +its header from its name. + +* The registry + +| Type | Header | +|-------------------------+-------------------------------------| +| =store::types::blob_id= | ="compass.store/types/blob_id.hpp"= | diff --git a/projects/modeling/variability_activity_record.org b/projects/modeling/variability_activity_record.org new file mode 100644 index 00000000..a8c312b0 --- /dev/null +++ b/projects/modeling/variability_activity_record.org @@ -0,0 +1,34 @@ +:PROPERTIES: +:ID: E5F44751-C848-4506-9E31-7C9BF5A6DD4A +:END: +#+title: Profile: Activity record +#+description: A row of what people did, which exists nowhere else, so its table is retained: a change to it needs a migration that says what becomes of its rows. +#+type: profile +#+level: cross +#+filetags: :codegen:variability:profile:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is a profile of the =masd.codegen.entity= models of compass. A +model binds it with =:profile: activity-record= in its =* Flags= drawer. + +* Purpose + +A test run, a step's result, a note or a screenshot: activity that a sync +cannot recreate, because nothing but the database holds it until it is +exported. The profile marks the table =retained=. =schema.sql= says so +above the table, and the catalog test of the component's migrations names +a retained table that loses or retypes a column with no migration to do it. +The key is the model's own: most activity tables have an identity key, but +a step's result is keyed by its run and step and a screenshot by its blob +ID. + +* Reference entity + +=compass.db.run=, one run of a test scenario. + +* Assignments + +| Feature | Value | +|----------+-------| +| retained | true | diff --git a/projects/modeling/variability_bookkeeping.org b/projects/modeling/variability_bookkeeping.org new file mode 100644 index 00000000..988f95d6 --- /dev/null +++ b/projects/modeling/variability_bookkeeping.org @@ -0,0 +1,36 @@ +:PROPERTIES: +:ID: 4AA409ED-1748-4C77-9F59-987C9831E1AC +:END: +#+title: Profile: Bookkeeping +#+description: A table the migration runner creates for itself before any migration, which no template generates. +#+type: profile +#+level: cross +#+filetags: :codegen:variability:profile:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is a profile of the =masd.codegen.entity= models of compass. A +model binds it with =:profile: bookkeeping= in its =* Flags= drawer. + +* Purpose + +The migration runner records the migrations it applied and a few settings +in the schema =compass=, which it creates with hand-written SQL before it +applies the first migration, so neither a migration nor =schema.sql= can +create it. The model states the table so it is reviewed in the same form as +every other; the profile switches off every MASD facet, and =schema.sql= +leaves the schema out because its schema model does not list it. + +* Reference entity + +=compass.db.migration=, the migrations applied. + +* Assignments + +The profile assigns no feature. + +* Physical space + +| Address | Enabled | +|---------+---------| +| =masd= | false | diff --git a/projects/modeling/variability_content_addressed_row.org b/projects/modeling/variability_content_addressed_row.org new file mode 100644 index 00000000..73b1af8d --- /dev/null +++ b/projects/modeling/variability_content_addressed_row.org @@ -0,0 +1,37 @@ +:PROPERTIES: +:ID: CF32F7F8-DB07-45C5-BB63-6BD1CBBB85FD +:END: +#+title: Profile: Content-addressed row +#+description: A row keyed by the blob ID of what it describes, written once in bulk with COPY and never updated. +#+type: profile +#+level: cross +#+filetags: :codegen:variability:profile:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is a profile of the =masd.codegen.entity= models of compass. A +model binds it with =:profile: content-addressed-row= in its =* Flags= +drawer. + +* Purpose + +A row that describes some bytes, keyed by their blob ID: the same bytes +give the same row, so a row is written once, with =ON CONFLICT DO +NOTHING=, and a change to the bytes is a new row. Rows of this shape are +staged in bulk, so the profile switches on their COPY writer. The key's +=key_kind: content_hash= keeps it out of the row type: it is the identity +of the aggregate, which the writer takes beside the row. + +* Reference entity + +=compass.db.document=, the row of one org document of the corpus. + +* Assignments + +The profile assigns no feature. + +* Physical space + +| Address | Enabled | +|-------------------+---------| +| =masd.cpp.copy= | true | diff --git a/projects/modeling/variability_environment_state.org b/projects/modeling/variability_environment_state.org new file mode 100644 index 00000000..ed0853aa --- /dev/null +++ b/projects/modeling/variability_environment_state.org @@ -0,0 +1,27 @@ +:PROPERTIES: +:ID: 5CD7372C-F277-4DB4-B48B-5F0B2F4F0D0D +:END: +#+title: Profile: Environment state +#+description: A row of what a sync last saw of an environment, which every sync rewrites and a fresh sync recreates. +#+type: profile +#+level: cross +#+filetags: :codegen:variability:profile:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is a profile of the =masd.codegen.entity= models of compass. A +model binds it with =:profile: environment-state= in its =* Flags= drawer. + +* Purpose + +An environment and the paths it places: state a sync writes with its own +upserts and deletes, so it is not retained, and a model whose rows are +staged in bulk switches its COPY writer on itself. + +* Reference entity + +=compass.db.environment=, one worktree, branch or release. + +* Assignments + +The profile assigns no feature. diff --git a/projects/modeling/variability_owned_child_row.org b/projects/modeling/variability_owned_child_row.org new file mode 100644 index 00000000..54f1b958 --- /dev/null +++ b/projects/modeling/variability_owned_child_row.org @@ -0,0 +1,35 @@ +:PROPERTIES: +:ID: C9311F98-CD91-4801-A2A8-7D4CC3171DC2 +:END: +#+title: Profile: Owned child row +#+description: A row that belongs to a content-addressed row, keyed by its owner's key and its place among its siblings, written in bulk with its owner. +#+type: profile +#+level: cross +#+filetags: :codegen:variability:profile:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is a profile of the =masd.codegen.entity= models of compass. A +model binds it with =:profile: owned-child-row= in its =* Flags= drawer. + +* Purpose + +A heading, a section or a link of a document, or a step of a scenario: a +row that exists only as part of its owner, keyed by the owner's key and an +=ord=, its place in the owner's vector, and deleted with it. Both key +columns stay out of the row type; the COPY writer, which the profile +switches on, takes them beside the row. + +* Reference entity + +=compass.db.heading=, a heading of an org document. + +* Assignments + +The profile assigns no feature. + +* Physical space + +| Address | Enabled | +|-------------------+---------| +| =masd.cpp.copy= | true | diff --git a/share/masd/templates/masd.cpp.copy.header.org b/share/masd/templates/masd.cpp.copy.header.org new file mode 100644 index 00000000..11f9e354 --- /dev/null +++ b/share/masd/templates/masd.cpp.copy.header.org @@ -0,0 +1,76 @@ +:PROPERTIES: +:ID: 7CA0A2A7-86E0-4CBE-8EF4-5F53103E2F46 +:END: +#+title: masd.cpp.copy.header +#+description: The header of a table's COPY writer: its column list and the declaration of write_copy. Output projects/{component_dir}/include/{component_dir}/io/{entity}_copy.hpp. +#+type: archetype +#+output: projects/{component_dir}/include/{component_dir}/io/{entity}_copy.hpp +#+facet: masd.cpp.copy +#+level: cross +#+filetags: :codegen:templates:literate:archetype:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the archetype that writes the header of a table's COPY writer +for the [[id:FD814477-B747-4261-A54B-5647EC66E22F][masd.cpp.copy]] facet. + +* Context + +The context is the library's values and =masd_entity=: + +- =table=, =entity=, =row_type=, =io_namespace= and =copy_guard=. +- =copy.includes=: the headers of the column list, the parameters, the + component's =copy_writer= and the row type. +- =copy_column_lines=: the column list split into string literals that fit + the line, each with =text= and =last=; the literals concatenate. +- =copy_parameters=: the =declaration= of each key parameter. + +* Template + +The template source. compass's =tangle= codec writes it to +=masd_cpp_copy.hpp.mustache= beside this page. + +#+begin_src mustache :tangle masd_cpp_copy.hpp.mustache +{{! GENERATED FILE — tangled from share/masd/templates/masd.cpp.copy.header.org. Edit the org source. }} +{{{cpp_license}}} +{{#masd_entity}} +#ifndef {{copy_guard}} +#define {{copy_guard}} + +{{#copy}} +{{#includes}} +#include {{{include}}} +{{/includes}} +{{/copy}} + +namespace {{io_namespace}} { + +/** + * @brief The columns of {{table}} that write_copy writes, + * in its order, for the column list of a COPY ... FROM STDIN. + */ +inline constexpr std::string_view {{entity}}_copy_columns = +{{#copy_column_lines}} + "{{text}}"{{#last}};{{/last}} +{{/copy_column_lines}} + +/** + * @brief Writes a row of {{table}} to @p w, in the order of + * {{entity}}_copy_columns. + */ +void write_copy(ops::copy_writer& w, +{{#copy_parameters}} + {{{declaration}}}, +{{/copy_parameters}} + const types::{{row_type}}& r); + +} + +#endif +{{/masd_entity}} +#+end_src + +* See also + +- Parent facet: [[id:FD814477-B747-4261-A54B-5647EC66E22F][masd.cpp.copy]] +- [[id:0A34FA7B-14D4-44C2-9098-411AE3DF45BF][masd.cpp.copy.impl]]: the definition. diff --git a/share/masd/templates/masd.cpp.copy.impl.org b/share/masd/templates/masd.cpp.copy.impl.org new file mode 100644 index 00000000..288c903c --- /dev/null +++ b/share/masd/templates/masd.cpp.copy.impl.org @@ -0,0 +1,56 @@ +:PROPERTIES: +:ID: 0A34FA7B-14D4-44C2-9098-411AE3DF45BF +:END: +#+title: masd.cpp.copy.impl +#+description: The definition of a table's write_copy. Output projects/{component_dir}/src/io/{entity}_copy.cpp. +#+type: archetype +#+output: projects/{component_dir}/src/io/{entity}_copy.cpp +#+facet: masd.cpp.copy +#+level: cross +#+filetags: :codegen:templates:literate:archetype:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the archetype that writes the definition of a table's +=write_copy= for the [[id:FD814477-B747-4261-A54B-5647EC66E22F][masd.cpp.copy]] facet: one =field= call per column +of the column list, then =end=. + +* Context + +The context is the library's values and =masd_entity=: =copy_include=, +=io_namespace=, =row_type=, =copy_parameters= as the header has them, and +=copy_fields=, the =expression= of each column in order, a parameter's name +or the row's member. + +* Template + +The template source. compass's =tangle= codec writes it to +=masd_cpp_copy.cpp.mustache= beside this page. + +#+begin_src mustache :tangle masd_cpp_copy.cpp.mustache +{{! GENERATED FILE — tangled from share/masd/templates/masd.cpp.copy.impl.org. Edit the org source. }} +{{{cpp_license}}} +{{#masd_entity}} +#include "{{copy_include}}" + +namespace {{io_namespace}} { + +void write_copy(ops::copy_writer& w, +{{#copy_parameters}} + {{{declaration}}}, +{{/copy_parameters}} + const types::{{row_type}}& r) { +{{#copy_fields}} + w.field({{{expression}}}); +{{/copy_fields}} + w.end(); +} + +} +{{/masd_entity}} +#+end_src + +* See also + +- Parent facet: [[id:FD814477-B747-4261-A54B-5647EC66E22F][masd.cpp.copy]] +- [[id:7CA0A2A7-86E0-4CBE-8EF4-5F53103E2F46][masd.cpp.copy.header]]: the declaration. diff --git a/share/masd/templates/masd.cpp.copy.org b/share/masd/templates/masd.cpp.copy.org new file mode 100644 index 00000000..12866209 --- /dev/null +++ b/share/masd/templates/masd.cpp.copy.org @@ -0,0 +1,45 @@ +:PROPERTIES: +:ID: FD814477-B747-4261-A54B-5647EC66E22F +:END: +#+title: masd.cpp.copy +#+description: The writer of a table's rows in the text format of COPY ... FROM STDIN, and the column list it writes. Off unless a profile or the model switches it on. +#+type: facet +#+model_types: masd_entity +#+level: cross +#+facet_group: masd.cpp +#+default: off +#+filetags: :codegen:physical-space:cpp:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the node for the =masd.cpp.copy= facet of the MASD library. +Its archetypes are [[id:7CA0A2A7-86E0-4CBE-8EF4-5F53103E2F46][masd.cpp.copy.header]] and +[[id:0A34FA7B-14D4-44C2-9098-411AE3DF45BF][masd.cpp.copy.impl]]. + +* Summary + +A table filled in bulk is staged with =COPY ... FROM STDIN= and inserted +from the staging table. This facet writes the two things that must agree +with the table: the list of the columns a row writes, and =write_copy=, +which writes one row's fields in that order. + +* The masd.cpp.copy facet + +The writer writes every column but those the database or the writer's SQL +fills: an =identity= key, a =written_by= or =computed= column and a +=:generated:= one. A key the row type leaves out, a =content_hash=, an +=owner= or an =ord=, is a parameter of =write_copy=, before the row, in +table order; an =ord= is a =std::size_t=, the index into the owner's +vector. + +The writer is in =::::io= and writes through the +component's =ops::copy_writer=, declared in =/ops/copy_text.hpp=: +a class with a =field= overload for each member type and =end=, which ends +the row. The facet is off by default, because a table written by an +=INSERT= has no use for it; the profiles of rows written in bulk switch it +on in their =* Physical space= table. + +* See also + +- [[id:7CA0A2A7-86E0-4CBE-8EF4-5F53103E2F46][masd.cpp.copy.header]] and [[id:0A34FA7B-14D4-44C2-9098-411AE3DF45BF][masd.cpp.copy.impl]]: the archetypes. +- [[id:EB763415-450C-4D07-8CEA-0988D19BB0B3][masd.cpp.row]]: the row types it writes. diff --git a/share/masd/templates/masd.cpp.row.header.org b/share/masd/templates/masd.cpp.row.header.org new file mode 100644 index 00000000..4944af2c --- /dev/null +++ b/share/masd/templates/masd.cpp.row.header.org @@ -0,0 +1,109 @@ +:PROPERTIES: +:ID: 68A40681-4113-4769-81A6-6306A42A9985 +:END: +#+title: masd.cpp.row.header +#+description: The header of a table's row type and the enumerations of its value lists. Output projects/{component_dir}/include/{component_dir}/types/{entity}_row.hpp. +#+type: archetype +#+output: projects/{component_dir}/include/{component_dir}/types/{entity}_row.hpp +#+facet: masd.cpp.row +#+level: cross +#+filetags: :codegen:templates:literate:archetype:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the archetype that writes a table's row header for the +[[id:EB763415-450C-4D07-8CEA-0988D19BB0B3][masd.cpp.row]] facet, in the namespace =::::types=. + +* Context + +The context is the library's values (=cpp_license= among them, which +carries the generated-file marker) and =masd_entity=: + +- =table=, =entity=, =row_type=, =brief=, =types_namespace= and + =row_guard=, the include guard. +- =includes=: each =include= the members and enumerations need, standard + headers first, then the headers the custom type registry gives. +- =enums=: each with =name=, =column=, =first= and its =values=, each a + =value= with =last=. +- =members=: each with =member=, =cpp_type= and =initializer=, the value a + member starts with, if any: zero, false, or the value of its enumeration + the column defaults to, else the first. + +The enumerations are in the row's header rather than in headers of their +own because a model renders one file per archetype, and an enumeration +belongs to one column of one table. + +* Template + +The template source. compass's =tangle= codec writes it to +=masd_cpp_row.hpp.mustache= beside this page. + +#+begin_src mustache :tangle masd_cpp_row.hpp.mustache +{{! GENERATED FILE — tangled from share/masd/templates/masd.cpp.row.header.org. Edit the org source. }} +{{{cpp_license}}} +{{#masd_entity}} +#ifndef {{row_guard}} +#define {{row_guard}} + +{{#includes}} +#include {{{include}}} +{{/includes}} + +namespace {{types_namespace}} { +{{#enums}} + +/** + * @brief The values of {{table}}.{{column}}. + */ +enum class {{name}} { {{#values}}{{value}}{{^last}}, {{/last}}{{/values}} }; + +/** + * @brief Each value of {{name}} as {{table}} stores it. + */ +[[nodiscard]] constexpr std::string_view to_string({{name}} v) noexcept { + switch (v) { +{{#values}} + case {{name}}::{{value}}: return "{{value}}"; +{{/values}} + } + return "{{first}}"; +} + +/** + * @brief The {{name}} @p text names, or none for any other text. + */ +[[nodiscard]] constexpr std::optional<{{name}}> {{name}}_of( + std::string_view text) noexcept { +{{#values}} + if (text == "{{value}}") + return {{name}}::{{value}}; +{{/values}} + return std::nullopt; +} +{{/enums}} + +/** +{{#brief}} + * @brief {{brief}} + * + * A row of {{table}}. +{{/brief}} +{{^brief}} + * @brief A row of {{table}}. +{{/brief}} + */ +struct {{row_type}} { +{{#members}} + {{{cpp_type}}} {{member}}{{{initializer}}}; +{{/members}} +}; + +} + +#endif +{{/masd_entity}} +#+end_src + +* See also + +- Parent facet: [[id:EB763415-450C-4D07-8CEA-0988D19BB0B3][masd.cpp.row]] diff --git a/share/masd/templates/masd.cpp.row.org b/share/masd/templates/masd.cpp.row.org new file mode 100644 index 00000000..b81d8e1d --- /dev/null +++ b/share/masd/templates/masd.cpp.row.org @@ -0,0 +1,51 @@ +:PROPERTIES: +:ID: EB763415-450C-4D07-8CEA-0988D19BB0B3 +:END: +#+title: masd.cpp.row +#+description: The C++ row type of a table of a masd.codegen.entity model, with the enumeration of each column that holds a closed list of values. +#+type: facet +#+model_types: masd_entity +#+level: cross +#+facet_group: masd.cpp +#+filetags: :codegen:physical-space:cpp:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the node for the =masd.cpp.row= facet of the MASD library, +the plain C++ technical space =masd.cpp=. Its one archetype, +[[id:68A40681-4113-4769-81A6-6306A42A9985][masd.cpp.row.header]], holds the template. + +* Summary + +Projects a table onto the struct a program fills to write a row and reads +back: one member per column the row itself writes, in table order. It +targets no library: the row is a plain aggregate, and the code that moves +it in and out of the database is the component's own or the +[[id:FD814477-B747-4261-A54B-5647EC66E22F][masd.cpp.copy]] writer's. + +* The masd.cpp.row facet + +A column is a member unless something else writes it or it is the key of +something larger: + +| Column | In the row | Why | +|---------------------------------+------------+------------------------------------------------------| +| =key_kind: natural= or no key | yes | The row states it. | +| =key_kind: content_hash= | no | The identity of the aggregate the row belongs to. | +| =key_kind: owner= | no | The key of the row that owns this one. | +| =key_kind: ord= | no | The row's place in its owner's vector. | +| =key_kind: identity= | no | The database generates it. | +| =written_by: database= | no | Its default or expression fills it. | +| =written_by: writer=, =computed= | no | The writer's own SQL sets it. | + +A member's type is the column's =:cpp_type:= when stated, else its +enumeration when it has =:values:=, else the C++ type of its SQL type, and +=std::optional= of that when the column is =:nullable:=. Each column with +=:values:= gets an =enum class= named =_= or its =:enum:=, +with =to_string= and a parser, =_of=, that answers none for text the +list does not hold. + +* See also + +- [[id:68A40681-4113-4769-81A6-6306A42A9985][masd.cpp.row.header]]: the archetype and its template. +- [[id:883A9765-56E8-4CF8-9871-73066663022E][masd.sql.schema]]: the tables these rows are rows of. diff --git a/share/masd/templates/masd.sql.schema.create.org b/share/masd/templates/masd.sql.schema.create.org new file mode 100644 index 00000000..cbe84e17 --- /dev/null +++ b/share/masd/templates/masd.sql.schema.create.org @@ -0,0 +1,82 @@ +:PROPERTIES: +:ID: 16D8D930-4264-45BC-BC22-3046F9C57523 +:END: +#+title: masd.sql.schema.create +#+description: sql/schema.sql of a component: every schema its masd.codegen.schema model lists, the tables of the masd.codegen.entity models beside it, their indexes, and the schema's functions. Output projects/{component_dir}/sql/schema.sql. +#+type: archetype +#+output: projects/{component_dir}/sql/schema.sql +#+facet: masd.sql.schema +#+level: cross +#+filetags: :codegen:templates:literate:archetype:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the archetype that writes =sql/schema.sql= for the +[[id:883A9765-56E8-4CF8-9871-73066663022E][masd.sql.schema]] facet: the whole schema of a component at its current +version, as plain PostgreSQL with no tenancy, history or row-level +security. + +* Context + +The context is the library's values (=sql_license= among them) and +=masd_schema=, which the MASD schema context builds from the schema model +and every =masd.codegen.entity= model in the same directory: + +- =schemas=: in the model's order, each with its =name= and its =tables=. +- =tables=: each with =table=, the schema-qualified name; =retained=; + =definitions=, the column definitions then the table constraints, each + with =last= on the final one; and =indexes=, each a whole =statement=. +- =functions=: the =sql= of each function, as the model holds it. + +A column definition is the column's name and SQL type, then in order: +=GENERATED ALWAYS AS IDENTITY= for an =identity= key, =GENERATED ALWAYS AS +(...) STORED= for a =:generated:= column, =PRIMARY KEY= for the only key +column or =NOT NULL= for a column that is not =:nullable:=, =UNIQUE=, the +=DEFAULT=, the =REFERENCES= of its foreign key with =ON DELETE CASCADE=, +and the =CHECK= of its =:values:=. A key of several columns, each =* SQL ** +Unique= row and each =** Checks= row is a table constraint. An index is +named =_=, as PostgreSQL scopes index names to the schema. + +* Template + +The template source. compass's =tangle= codec writes it to +=masd_sql_schema.sql.mustache= beside this page. + +#+begin_src mustache :tangle masd_sql_schema.sql.mustache +{{! GENERATED FILE — tangled from share/masd/templates/masd.sql.schema.create.org. Edit the org source. }} +{{{sql_license}}} +/* + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_sql_schema.sql.mustache + * To modify, update the template and regenerate. + */ +{{#masd_schema}} +{{#schemas}} + +CREATE SCHEMA {{name}}; +{{#tables}} + +{{#retained}} +-- {{table}} is retained: its rows exist nowhere else, so a change +-- to it needs a migration. +{{/retained}} +CREATE TABLE {{table}} ( +{{#definitions}} + {{{definition}}}{{^last}},{{/last}} +{{/definitions}} +); +{{#indexes}} +{{{statement}}} +{{/indexes}} +{{/tables}} +{{/schemas}} +{{#functions}} + +{{{sql}}} +{{/functions}} +{{/masd_schema}} +#+end_src + +* See also + +- Parent facet: [[id:883A9765-56E8-4CF8-9871-73066663022E][masd.sql.schema]] diff --git a/share/masd/templates/masd.sql.schema.org b/share/masd/templates/masd.sql.schema.org new file mode 100644 index 00000000..fcc91c7d --- /dev/null +++ b/share/masd/templates/masd.sql.schema.org @@ -0,0 +1,45 @@ +:PROPERTIES: +:ID: 883A9765-56E8-4CF8-9871-73066663022E +:END: +#+title: masd.sql.schema +#+description: A component's whole PostgreSQL schema, generated from its masd.codegen.schema model and the masd.codegen.entity models beside it. +#+type: facet +#+model_types: masd_schema +#+level: cross +#+facet_group: masd.sql +#+filetags: :codegen:physical-space:sql:masd: +#+created: 2026-11-23 +#+updated: 2026-11-23 + +This page is the node for the =masd.sql.schema= facet of the MASD +library, the plain PostgreSQL technical space =masd.sql=. Its one +archetype, [[id:16D8D930-4264-45BC-BC22-3046F9C57523][masd.sql.schema.create]], holds the template. + +* Summary + +A component that owns a database describes each table as a +=masd.codegen.entity= model and the database as one =masd.codegen.schema= +model in the same =modeling/= directory. This facet projects the schema +model onto =sql/schema.sql=: every schema it lists, every table of those +schemas and every function, at the current version, in one script. + +* The masd.sql.schema facet + +The script is the specification of the schema, never a migration. A +database that holds data is changed by the component's migrations, which +are written by hand and frozen once released; a test builds one database +from the migrations and one from this script and compares their catalogs. +A change to a model therefore shows up twice in a pull request: as the +=git diff= of =schema.sql=, and as the migration that must produce it. + +Tables are written schema by schema, in the order the schema model lists +the schemas, and within a schema in an order where every table follows the +tables its foreign keys reference, ties broken by name. A table whose +profile marks it retained is introduced by a comment saying so: its rows +exist nowhere else, so the catalog test names it when it loses or retypes a +column with no migration. + +* See also + +- [[id:16D8D930-4264-45BC-BC22-3046F9C57523][masd.sql.schema.create]]: the archetype and its template. +- [[id:EB763415-450C-4D07-8CEA-0988D19BB0B3][masd.cpp.row]]: the row types over the same tables. diff --git a/share/masd/templates/masd_cpp_copy.cpp.mustache b/share/masd/templates/masd_cpp_copy.cpp.mustache new file mode 100644 index 00000000..fd87b444 --- /dev/null +++ b/share/masd/templates/masd_cpp_copy.cpp.mustache @@ -0,0 +1,20 @@ +{{! GENERATED FILE — tangled from share/masd/templates/masd.cpp.copy.impl.org. Edit the org source. }} +{{{cpp_license}}} +{{#masd_entity}} +#include "{{copy_include}}" + +namespace {{io_namespace}} { + +void write_copy(ops::copy_writer& w, +{{#copy_parameters}} + {{{declaration}}}, +{{/copy_parameters}} + const types::{{row_type}}& r) { +{{#copy_fields}} + w.field({{{expression}}}); +{{/copy_fields}} + w.end(); +} + +} +{{/masd_entity}} diff --git a/share/masd/templates/masd_cpp_copy.hpp.mustache b/share/masd/templates/masd_cpp_copy.hpp.mustache new file mode 100644 index 00000000..e6ce0297 --- /dev/null +++ b/share/masd/templates/masd_cpp_copy.hpp.mustache @@ -0,0 +1,37 @@ +{{! GENERATED FILE — tangled from share/masd/templates/masd.cpp.copy.header.org. Edit the org source. }} +{{{cpp_license}}} +{{#masd_entity}} +#ifndef {{copy_guard}} +#define {{copy_guard}} + +{{#copy}} +{{#includes}} +#include {{{include}}} +{{/includes}} +{{/copy}} + +namespace {{io_namespace}} { + +/** + * @brief The columns of {{table}} that write_copy writes, + * in its order, for the column list of a COPY ... FROM STDIN. + */ +inline constexpr std::string_view {{entity}}_copy_columns = +{{#copy_column_lines}} + "{{text}}"{{#last}};{{/last}} +{{/copy_column_lines}} + +/** + * @brief Writes a row of {{table}} to @p w, in the order of + * {{entity}}_copy_columns. + */ +void write_copy(ops::copy_writer& w, +{{#copy_parameters}} + {{{declaration}}}, +{{/copy_parameters}} + const types::{{row_type}}& r); + +} + +#endif +{{/masd_entity}} diff --git a/share/masd/templates/masd_cpp_row.hpp.mustache b/share/masd/templates/masd_cpp_row.hpp.mustache new file mode 100644 index 00000000..76c9a791 --- /dev/null +++ b/share/masd/templates/masd_cpp_row.hpp.mustache @@ -0,0 +1,63 @@ +{{! GENERATED FILE — tangled from share/masd/templates/masd.cpp.row.header.org. Edit the org source. }} +{{{cpp_license}}} +{{#masd_entity}} +#ifndef {{row_guard}} +#define {{row_guard}} + +{{#includes}} +#include {{{include}}} +{{/includes}} + +namespace {{types_namespace}} { +{{#enums}} + +/** + * @brief The values of {{table}}.{{column}}. + */ +enum class {{name}} { {{#values}}{{value}}{{^last}}, {{/last}}{{/values}} }; + +/** + * @brief Each value of {{name}} as {{table}} stores it. + */ +[[nodiscard]] constexpr std::string_view to_string({{name}} v) noexcept { + switch (v) { +{{#values}} + case {{name}}::{{value}}: return "{{value}}"; +{{/values}} + } + return "{{first}}"; +} + +/** + * @brief The {{name}} @p text names, or none for any other text. + */ +[[nodiscard]] constexpr std::optional<{{name}}> {{name}}_of( + std::string_view text) noexcept { +{{#values}} + if (text == "{{value}}") + return {{name}}::{{value}}; +{{/values}} + return std::nullopt; +} +{{/enums}} + +/** +{{#brief}} + * @brief {{brief}} + * + * A row of {{table}}. +{{/brief}} +{{^brief}} + * @brief A row of {{table}}. +{{/brief}} + */ +struct {{row_type}} { +{{#members}} + {{{cpp_type}}} {{member}}{{{initializer}}}; +{{/members}} +}; + +} + +#endif +{{/masd_entity}} diff --git a/share/masd/templates/masd_sql_schema.sql.mustache b/share/masd/templates/masd_sql_schema.sql.mustache new file mode 100644 index 00000000..bcc09c55 --- /dev/null +++ b/share/masd/templates/masd_sql_schema.sql.mustache @@ -0,0 +1,32 @@ +{{! GENERATED FILE — tangled from share/masd/templates/masd.sql.schema.create.org. Edit the org source. }} +{{{sql_license}}} +/* + * AUTO-GENERATED FILE - DO NOT EDIT MANUALLY + * Template: masd_sql_schema.sql.mustache + * To modify, update the template and regenerate. + */ +{{#masd_schema}} +{{#schemas}} + +CREATE SCHEMA {{name}}; +{{#tables}} + +{{#retained}} +-- {{table}} is retained: its rows exist nowhere else, so a change +-- to it needs a migration. +{{/retained}} +CREATE TABLE {{table}} ( +{{#definitions}} + {{{definition}}}{{^last}},{{/last}} +{{/definitions}} +); +{{#indexes}} +{{{statement}}} +{{/indexes}} +{{/tables}} +{{/schemas}} +{{#functions}} + +{{{sql}}} +{{/functions}} +{{/masd_schema}}