{
  "clusterId": "41_INFRA_Database",
  "featureFocus": "Database Schema, Migrations, and Seed Data",
  "documentationReport": "{\n  \"title\": \"Database Schema, Migrations, and Seeding\",\n  \"overview\": \"The Xikolo project leverages PostgreSQL as its primary data store, serving both the main application and its suite of microservices. This comprehensive documentation outlines the architecture, configuration, schema design, migration strategies, and seeding processes that govern the project's data layer. Key components include the PostgreSQL Database itself, ActiveRecord for ORM, the Fx Gem for managing database functions, and the Scenic Gem for handling database views, all augmented by a rich set of PostgreSQL extensions.\",\n  \"components\": [\n    \"PostgreSQL Database\",\n    \"ActiveRecord\",\n    \"Fx Gem\",\n    \"Scenic Gem\",\n    \"PostgreSQL Extensions\"\n  ],\n  \"functional_domain\": \"Database Management\",\n  \"sections\": [\n    {\n      \"title\": \"Database Configuration\",\n      \"description\": \"Database configurations are centrally managed through `config/database.yml`, ensuring consistency across the main application and all microservices (e.g., account, course, news, notification, pinboard, quiz, timeeffort). All environments (development, test, integration, production) share common settings, including the `postgresql` adapter, a configurable connection pool size, and a statement timeout of 10 seconds. These settings are largely driven by environment variables such as `DATABASE_URL`, `CONCURRENCY`, and `RAILS_MAX_THREADS`, promoting flexible deployment.\",\n      \"sources\": [\n        \"config/database.yml\",\n        \"services/account/config/database.yml\",\n        \"services/course/config/database.yml\",\n        \"services/news/config/database.yml\",\n        \"services/notification/config/database.yml\",\n        \"services/pinboard/config/database.yml\",\n        \"services/quiz/config/database.yml\",\n        \"services/timeeffort/config/database.yml\"\n      ]\n    },\n    {\n      \"title\": \"Schema Design and Features\",\n      \"description\": \"The database schema, defined in `db/schema.rb` and auto-generated by Active Record (currently based on `ActiveRecord::Schema[7.2]`), reflects a robust learning platform. A key architectural decision is the extensive utilization of PostgreSQL-specific features, managed in part by the Fx and Scenic gems.\",\n      \"sub_sections\": [\n        {\n          \"title\": \"PostgreSQL Extensions\",\n          \"details\": \"The schema explicitly enables `hstore` (for key-value storage), `pg_trgm` (for trigram-based full-text search), `pgcrypto` (for cryptographic functions), `plpgsql` (for procedural language support), `unaccent` (for accent removal), and `uuid-ossp` (for UUID generation).\",\n          \"sources\": [\n            \"db/schema.rb\"\n          ]\n        },\n        {\n          \"title\": \"Custom UUID Generation\",\n          \"details\": \"Most tables use UUIDs as primary keys, with a custom PostgreSQL function `uuid_generate_v7ms()` serving as the default generator. This function, managed via the Fx Gem, generates UUID v7 with millisecond precision, indicating a modern approach to unique identifier generation.\",\n          \"sources\": [\n            \"db/schema.rb\",\n            \"Source 1 (C04_Database_Schema_Migrations)\"\n          ]\n        },\n        {\n          \"title\": \"Enums\",\n          \"details\": \"Several custom enums are defined to constrain column values, including `link_target`, `node_type`, `offer_category`, `payment_frequency`, and `sort_mode`.\",\n          \"sources\": [\n            \"db/schema.rb\"\n          ]\n        },\n        {\n          \"title\": \"Advanced Data Types\",\n          \"details\": \"The schema makes heavy use of `jsonb` for storing structured JSON data (e.g., `translations`, `recipients`, `config`, `vendor_data`) and `hstore` for key-value pairs (e.g., `description`, `payload`, `policy_url`, `preferences`, `settings`). Array columns are also prevalent for storing lists of values (e.g., `groups`, `teacher_ids`, `learning_goals`, `tags`, `permissions`).\",\n          \"sources\": [\n            \"db/schema.rb\"\n          ]\n        },\n        {\n          \"title\": \"Full-Text Search\",\n          \"details\": \"The `questions` table includes a `tsv` column of type `tsvector` with a `gin_trgm_ops` opclass index, indicating advanced full-text search capabilities utilizing `pg_trgm`.\",\n          \"sources\": [\n            \"db/schema.rb\"\n          ]\n        },\n        {\n          \"title\": \"Views\",\n          \"details\": \"A materialized view `embed_courses` is defined, which denormalizes course data by joining with `classifiers` and `teachers` to provide a more efficient query interface for certain course attributes. This view is managed using the Scenic Gem.\",\n          \"sources\": [\n            \"db/schema.rb\",\n            \"Source 1 (C04_Database_Schema_Migrations)\"\n          ]\n        },\n        {\n          \"title\": \"Foreign Keys\",\n          \"details\": \"Explicit foreign key constraints are defined between various tables, ensuring data integrity and maintaining relationships across the schema.\",\n          \"sources\": [\n            \"db/schema.rb\"\n          ]\n        }\n      ],\n      \"sources\": [\n        \"db/schema.rb\",\n        \"Source 1 (C04_Database_Schema_Migrations)\"\n      ]\n    },\n    {\n      \"title\": \"Database Migrations\",\n      \"description\": \"Database migrations are a critical part of the project's development workflow. The `docs/app/development/best_practices/database_migrations.md` document outlines best practices, emphasizing that migrations are used for both schema and data alterations and should ideally be reversible.\",\n      \"sub_sections\": [\n        {\n          \"title\": \"Data Migration Workflow\",\n          \"details\": \"For data migrations, a multi-step workflow is recommended: creating new tables, adapting code to write to both old and new resources, migrating data, updating code to use only the new resource, and finally removing deprecated attributes.\",\n          \"sources\": [\n            \"docs/app/development/best_practices/database_migrations.md\"\n          ]\n        },\n        {\n          \"title\": \"Performance Considerations\",\n          \"details\": \"Performance considerations for migrations include using bulk table migrations, batch processing (`find_each`, `in_batches`), dropping and re-adding indices, and judiciously skipping validations or using plain SQL for efficiency.\",\n          \"sources\": [\n            \"docs/app/development/best_practices/database_migrations.md\"\n          ]\n        },\n        {\n          \"title\": \"Best Practices\",\n          \"details\": \"It is also recommended to mock models within migrations to prevent future breakage due to model name changes.\",\n          \"sources\": [\n            \"docs/app/development/best_practices/database_migrations.md\"\n          ]\n        }\n      ],\n      \"sources\": [\n        \"docs/app/development/best_practices/database_migrations.md\"\n      ]\n    },\n    {\n      \"title\": \"Seed Data\",\n      \"description\": \"Seed data is loaded via `db/seeds.rb`, which dynamically loads all Ruby files from `db/seeds/all/**/*.rb` and then `db/seeds/<env>/**/*.rb` (where `<env>` defaults to `Rails.env` or can be overridden by `SEED_ENV`). This allows for a structured and environment-specific approach to populating initial database content, with alphabetical ordering ensuring consistent load order.\",\n      \"sources\": [\n        \"db/seeds.rb\"\n      ]\n    }\n  ]\n}",
  "componentMapPatch": {
    "components": {
      "Database Configuration": {
        "type": "Configuration",
        "description": "Manages PostgreSQL database connection settings for various environments (development, test, integration, production) across the main application and microservices. Utilizes environment variables for sensitive data and dynamic scaling of connection pools.",
        "interactions": {
          "interaction_0": "Rails Application: Reads configuration to establish database connections.",
          "interaction_1": "Deployment Tooling: Overrides production settings during deployment.",
          "interaction_2": "Environment Variables: Reads `DATABASE_URL`, `CONCURRENCY`, `RAILS_MAX_THREADS` for dynamic settings."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "config/database.yml",
            "services/account/config/database.yml",
            "services/course/config/database.yml",
            "services/news/config/database.yml",
            "services/notification/config/database.yml",
            "services/pinboard/config/database.yml",
            "services/quiz/config/database.yml",
            "services/timeeffort/config/database.yml"
          ]
        }
      },
      "Database Schema": {
        "type": "Data Structure",
        "description": "Defines the structure of the PostgreSQL database, including tables, columns, data types, indexes, and constraints. It extensively leverages PostgreSQL-specific features like UUIDs, `jsonb`, `hstore`, custom enums, and a custom UUID generation function. Includes a denormalized view for courses.",
        "interactions": {
          "interaction_0": "Active Record ORM: Provides the Ruby interface for interacting with the database tables and views.",
          "interaction_1": "PostgreSQL Database: Implements the defined schema, extensions, enums, and functions.",
          "interaction_2": "Migration System: Applies and manages changes to the schema over time.",
          "interaction_3": "Custom UUID Generator (uuid_generate_v7ms): Utilizes this function for default primary key generation.",
          "interaction_4": "embed_courses View: Provides a denormalized view for efficient querying of course-related data."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "Migration System (Active Record Migrations)": {
        "type": "Framework Component",
        "description": "Manages incremental changes to the database schema and data. Adheres to best practices for data migrations, including multi-step processes for attribute refactoring, performance optimizations (e.g., bulk operations, batch processing), and ensuring reversibility where possible.",
        "interactions": {
          "interaction_0": "Database Schema: Applies structural and data changes to the database.",
          "interaction_1": "Rails Application: Executes migrations during deployment and development cycles.",
          "interaction_2": "Models: Migrations may interact with (mocked) Active Record models for data transformations."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb",
            "docs/app/development/best_practices/database_migrations.md"
          ]
        }
      },
      "Seed Data Loader": {
        "type": "Utility",
        "description": "Facilitates loading initial or development data into the database. It supports environment-specific seeding by loading files from `db/seeds/all` and then `db/seeds/<env>`, ensuring a consistent load order through alphabetical file processing.",
        "interactions": {
          "interaction_0": "Rails Environment: Determines which environment-specific seed files to load.",
          "interaction_1": "Database: Inserts initial data based on the loaded seed files."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/seeds.rb"
          ]
        }
      },
      "Custom UUID Generator (uuid_generate_v7ms)": {
        "type": "Database Function",
        "description": "A custom PostgreSQL function that generates UUIDs following the v7 specification with millisecond precision. This function is extensively used as the default primary key generator for most tables in the Xikolo database.",
        "interactions": {
          "interaction_0": "Database Schema: Set as the default value for `id` columns in many tables.",
          "interaction_1": "Active Record: Automatically invoked when new records are created without an explicit UUID."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "PostgreSQL Database": {
        "type": "Data Store",
        "description": "The primary relational database system for the application, extensively configured with custom extensions and functions.",
        "interactions": {
          "interaction_0": "ActiveRecord interacts with PostgreSQL for all data operations.",
          "interaction_1": "Fx gem interacts with PostgreSQL to manage functions.",
          "interaction_2": "Scenic gem interacts with PostgreSQL to manage views."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "Gemfile",
            "db/schema.rb"
          ]
        }
      },
      "ActiveRecord": {
        "type": "ORM",
        "description": "Ruby on Rails' Object-Relational Mapping layer, responsible for defining the application's data models and interacting with the PostgreSQL database.",
        "interactions": {
          "interaction_0": "Manages schema migrations and definitions.",
          "interaction_1": "Interacts with PostgreSQL for CRUD operations.",
          "interaction_2": "Utilizes Fx and Scenic for advanced database features."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb",
            "docs/app/development/best_practices/database_migrations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 18,
              "code": "module Patch\n  module ActiveRecord\n    module SelectUniq\n      # AR calls `select_values.uniq`. This can talk very much time when\n      # e.g. the select values are complex Arel nodes.\n      #\n      # This patch removes `.uniq` as it is deemed as not necessary.\n      #\n      def build_select(arel)\n        if select_values.any?\n          arel.project(*arel_columns(select_values))\n        else\n          super\n        end\n      end\n    end\n\n    ::ActiveRecord::Relation.prepend SelectUniq\n  end\nend",
              "source": "services/course/lib/patch/activerecord_select_uniq.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/lib/patch/activerecord_select_uniq.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Fx Gem": {
        "type": "Library",
        "description": "A Ruby gem used to manage database functions, ensuring they are dumped at the beginning of the schema file for correct dependency resolution.",
        "interactions": {
          "interaction_0": "Configures schema dumping behavior for PostgreSQL functions.",
          "interaction_1": "Integrates with ActiveRecord's migration process."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "config/initializers/fx.rb",
            "db/schema.rb"
          ]
        }
      },
      "Scenic Gem": {
        "type": "Library",
        "description": "A Ruby gem used to manage database views, allowing them to be versioned and managed like migrations.",
        "interactions": {
          "interaction_0": "Defines and manages the `embed_courses` view.",
          "interaction_1": "Integrates with ActiveRecord's migration process."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "PostgreSQL Extensions": {
        "type": "Database Feature",
        "description": "A suite of enabled PostgreSQL extensions (`hstore`, `pg_trgm`, `pgcrypto`, `plpgsql`, `unaccent`, `uuid-ossp`) providing advanced database capabilities.",
        "interactions": {
          "interaction_0": "Provide underlying functionality for data types, search, and custom functions."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "uuid_generate_v7ms Function": {
        "type": "Database Function",
        "description": "A custom PostgreSQL function written in `plpgsql` to generate UUID v7, used as the default primary key for most tables.",
        "interactions": {
          "interaction_0": "Called by ActiveRecord during record creation to assign primary keys."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "Custom Enum Types": {
        "type": "Database Feature",
        "description": "PostgreSQL enum types (`link_target`, `node_type`, `offer_category`, `payment_frequency`, `sort_mode`) used to enforce specific sets of values for columns, improving data integrity and readability.",
        "interactions": {
          "interaction_0": "Enforce data constraints on various table columns."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "embed_courses View": {
        "type": "Database View",
        "description": "A PostgreSQL view that denormalizes course-related data, combining information from multiple tables for simplified and efficient querying, particularly for frontend display.",
        "interactions": {
          "interaction_0": "Provides a consolidated data source for course information.",
          "interaction_1": "Used by application logic to retrieve complex course details."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/schema.rb"
          ]
        }
      },
      "Database Seeding Mechanism": {
        "type": "Process",
        "description": "The system for populating the database with initial or sample data, supporting environment-specific seed files.",
        "interactions": {
          "interaction_0": "Loads seed data into the PostgreSQL database via ActiveRecord."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "db/seeds.rb"
          ]
        }
      },
      "PaperTrail Gem": {
        "type": "Library",
        "description": "A Ruby gem used for auditing changes to ActiveRecord models, indicated by the presence of the `versions` table.",
        "interactions": {
          "interaction_0": "Records changes to tracked models in the `versions` table."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "Gemfile",
            "db/schema.rb"
          ]
        }
      },
      "DelayedJob Gem": {
        "type": "Library",
        "description": "A Ruby gem for handling background jobs, indicated by the `delayed_jobs` table in the schema.",
        "interactions": {
          "interaction_0": "Stores and manages asynchronous tasks for background processing."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "Gemfile",
            "db/schema.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 21,
              "code": "class ApplicationJob < ActiveJob::Base\n  queue_as 'default'\n\n  # The max amount of time a job is allowed to run before it is stopped.\n  # Must be less than the global `max_run_time` default,\n  # see config/initializers/delayed.rb.\n  # Allow a regular job to run for 20 minutes, which is the delayed gem default.\n  def max_run_time\n    20.minutes\n  end\n\n  # Automatically retry jobs that encountered a deadlock.\n  # retry_on ActiveRecord::Deadlocked\n\n  # Most jobs are safe to ignore if the underlying records are no longer available.\n  # discard_on ActiveJob::DeserializationError\n\n  # Should be used to indicate explicit retries to ActiveJob.\n  # This error is ignored by Sentry.\n  class ExpectedRetry < StandardError; end\nend",
              "source": "app/assets/admin/reports/report-jobs.js"
            },
            {
              "startLine": 3,
              "endLine": 19,
              "code": "class LongRunningApplicationJob < ApplicationJob\n  queue_as 'long_running'\n\n  # The max amount of time a job is allowed to run before it is stopped.\n  # Must be less than the global `max_run_time` default,\n  # see config/initializers/delayed.rb.\n  # Long-running jobs are allowed to run for 10 hours, which is the globally\n  # configured maximum runtime.\n  def max_run_time\n    10.hours\n  end\n\n  def max_attempts\n    5\n  end\nend",
              "source": "app/assets/admin/reports/report-jobs.js"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/assets/admin/reports/report-jobs.js",
              "relevance": 5
            },
            {
              "path": "app/jobs/application_job.rb",
              "relevance": 5
            },
            {
              "path": "app/jobs/long_running_application_job.rb",
              "relevance": 5
            }
          ]
        }
      }
    },
    "microservices": {},
    "interactions": {
      "interaction_0": "Rails Application: Reads configuration to establish database connections.",
      "interaction_1": "Deployment Tooling: Overrides production settings during deployment.",
      "interaction_2": "Environment Variables: Reads `DATABASE_URL`, `CONCURRENCY`, `RAILS_MAX_THREADS` for dynamic settings.",
      "interaction_3": "Active Record ORM: Provides the Ruby interface for interacting with the database tables and views.",
      "interaction_4": "PostgreSQL Database: Implements the defined schema, extensions, enums, and functions.",
      "interaction_5": "Migration System: Applies and manages changes to the schema over time.",
      "interaction_6": "Custom UUID Generator (uuid_generate_v7ms): Utilizes this function for default primary key generation.",
      "interaction_7": "embed_courses View: Provides a denormalized view for efficient querying of course-related data.",
      "interaction_8": "Database Schema: Applies structural and data changes to the database.",
      "interaction_9": "Rails Application: Executes migrations during deployment and development cycles.",
      "interaction_10": "Models: Migrations may interact with (mocked) Active Record models for data transformations.",
      "interaction_11": "Rails Environment: Determines which environment-specific seed files to load.",
      "interaction_12": "Database: Inserts initial data based on the loaded seed files.",
      "interaction_13": "Database Schema: Set as the default value for `id` columns in many tables.",
      "interaction_14": "Active Record: Automatically invoked when new records are created without an explicit UUID.",
      "interaction_15": "ActiveRecord interacts with PostgreSQL for all data operations.",
      "interaction_16": "Fx gem interacts with PostgreSQL to manage functions.",
      "interaction_17": "Scenic gem interacts with PostgreSQL to manage views.",
      "interaction_18": "Manages schema migrations and definitions.",
      "interaction_19": "Interacts with PostgreSQL for CRUD operations.",
      "interaction_20": "Utilizes Fx and Scenic for advanced database features.",
      "interaction_21": "Configures schema dumping behavior for PostgreSQL functions.",
      "interaction_22": "Integrates with ActiveRecord's migration process.",
      "interaction_23": "Defines and manages the `embed_courses` view.",
      "interaction_24": "Integrates with ActiveRecord's migration process.",
      "interaction_25": "Provide underlying functionality for data types, search, and custom functions.",
      "interaction_26": "Called by ActiveRecord during record creation to assign primary keys.",
      "interaction_27": "Enforce data constraints on various table columns.",
      "interaction_28": "Provides a consolidated data source for course information.",
      "interaction_29": "Used by application logic to retrieve complex course details.",
      "interaction_30": "Loads seed data into the PostgreSQL database via ActiveRecord.",
      "interaction_31": "Records changes to tracked models in the `versions` table.",
      "interaction_32": "Stores and manages asynchronous tasks for background processing."
    },
    "technicalDebt": []
  }
}