-
Notifications
You must be signed in to change notification settings - Fork 0
Active record #6
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
84ee66b
to
ba2d493
Compare
…Schema. Enhance table management and query execution features, including support for SQLite and PostgreSQL URIs. Add functionality for dumping schema structure to a file and improve error logging for database operations. Remove deprecated record and relations modules, and introduce a new active_record module with enhanced functionality for model definitions, querying, and associations. This refactor includes the addition of attributes, callbacks, and validations, streamlining the ORM capabilities for better usability and maintainability. Add comprehensive tests for ActiveRecord features including attributes, callbacks, insertable, and updateable modules. Implement validations for user models and enhance error handling. This update improves the overall robustness and reliability of the ORM functionality. Add tests for deleteable functionality in ActiveRecord, including record deletion by ID, field matching, and all records deletion. Implement error handling for non-existent records and nil IDs. Enhance callback execution during deletion processes. Refactor ActiveRecord tests to utilize TestUser model, enhancing attribute handling, callback execution, and validation processes. Update tests for insertable, updateable, and queryable functionalities to ensure consistency and reliability across the ORM framework. Refactor ActiveRecord update methods to streamline attribute assignment using a new attributes method. Update tests to directly verify user attributes after updates, enhancing clarity and reducing redundancy in the test suite. Enhance ActiveRecord functionality by implementing belongs_to association in the relations module. Add tests for the Post model to verify user associations, including creation, updating, and deletion of associated users. Update queryable tests to reflect changes in grouping functionality. Additionally, introduce a new posts table in the schema for improved data handling. Refactor ActiveRecord tests and introduce new model relationships. Remove unused code and enhance callback tracking functionality. Add tests for has_one, has_many, and many_to_many associations, ensuring proper creation, deletion, and retrieval of associated records. Update schema to support new models and relationships, improving overall ORM capabilities. Formatting Add save! method with exception handling and custom error classes Improve error handling for connection vs no results errors in find methods Add memoization and reload functionality to has_many associations Add validation context and remove redundant GreaterThan module Add error handling and dialect-specific SQL formatting The commit adds comprehensive error handling and moves SQL formatting logic to dialect classes. It introduces a new error hierarchy and standardizes SQL Remove trailing whitespace and fix method parameter formatting Implement lazy loading for many-to-many associations and add find_or_create_by Fix migration table handling and make timestamps nullable for SQLite support Refactor table alias syntax and improve error handling in Repository methods I don't see any file changes provided to analyze. Please share the code changes you'd like me to summarize in a commit message. Improve error handling and refactor table schema definitions Add new database schema files and refactor dialect classes This commit introduces new database schema files and refactors the dialect classes to enhance structure and maintainability. It includes the addition of a base dialect class that consolidates common functionalities across different database dialects, improving code organization and readability. Additionally, the JSON column method in the table class has been updated to support custom types, and various dialect implementations have been adjusted to inherit from the new base class. Refactor SQL query generation and enhance dialect support This commit removes the returning clause from DELETE and INSERT SQL queries for consistency. It introduces a method to retrieve the current timestamp function based on the database dialect, improving timestamp handling across different database types. Additionally, the initialization of the Expression generator has been simplified to directly use the adapter's dialect method. Refactor CustomerModel and enhance timestamp handling across dialects This commit removes the old CustomerModel spec file and introduces a new implementation with default values for properties. Additionally, it updates the current timestamp method in MySQL, PostgreSQL, and SQLite dialects to return a formatted timestamp string, improving consistency in timestamp handling across different database types. Update database connection string and enhance documentation This commit updates the DATABASE_URL in the .env file for improved security by removing the username from the connection string. Additionally, it enhances the .windsurfrules file by formatting the content into a more structured format with comments for better readability. Minor whitespace adjustments were made in schema files and the CustomerModel spec file to maintain consistency. Refactor CustomerModel to set default values for properties This commit updates the CustomerModel by assigning default values to the city and balance properties, as well as the created_at and updated_at timestamps. The initialize method has been reformatted for improved readability while maintaining functionality. Update database connection string, enhance documentation, and remove unused test files This commit updates the DATABASE_URL in the .env file by removing the username for improved security. The .windsurfrules file is reformatted with comments for better readability. Additionally, it removes the unused test_schema.db and test.db files to clean up the project structure. Update user update spec and clean up SQLite drop column warning This commit modifies the user update spec to assert that the result is a TestUser instance after an update. Additionally, it cleans up the SQLite dialect by removing an unnecessary warning log for the DROP COLUMN workaround, streamlining the code while maintaining functionality. Add foreign key support in table definitions and SQL generation This commit introduces the ability to define foreign key constraints in table definitions, enhancing the CQL::Table class with methods to add foreign keys. It also updates the SQL generation process to include foreign key definitions in CREATE TABLE statements across different dialects. Additionally, comprehensive tests for foreign key operations have been added to ensure correct functionality and error handling for mismatched column counts. Refactor foreign key definition syntax and enhance documentation This commit updates the foreign key definition syntax in the schema specifications for both PostgreSQL and SQLite, aligning it with the new method signature. It also enhances the documentation for the foreign key method in the alter_table module, clarifying parameter usage and providing examples. Additionally, it ensures that default names are generated for foreign keys when not explicitly provided, improving usability and consistency across the codebase. Add support for unique and check constraints in table definitions This commit introduces the ability to define unique and check constraints within table definitions in the CQL::Table class. It adds methods for creating unique and check constraints, enhancing the SQL generation process to include these constraints in CREATE TABLE statements across different dialects. Comprehensive tests have been added to validate the functionality of these new features, ensuring correct behavior and error handling. Update migration version handling and improve rollback functionality This commit modifies the migration version handling in the CQL::Migration module by changing the type from Int64 to Int32 for applied migrations. It also enhances the rollback method to utilize database transactions, ensuring that rolled back migrations are accurately tracked and printed. Additionally, a default version value is introduced in the BaseMigration class, along with a method to enforce version definition in subclasses, improving overall migration management. Add project rules and guidelines for CQL usage This commit introduces a new project.mdc file that outlines the rules and guidelines for using the Crystal programming language (v1.15.1) and adhering to SOLID principles in software design. It includes a description of the CQL (Crystal Query Language) ORM library, highlighting its key features such as type safety, macro-powered DSL, and support for major relational databases. This addition aims to provide clarity and direction for developers working on the project. --wip-- Refactor Process.new usage in structure_dump for MySQL and PostgreSQL dialects Enhance CQL with foreign key support and improve query handling This commit introduces several enhancements to the CQL (Crystal Query Language) library. It adds foreign key definitions in the Northwind schema, ensuring proper relationships between tables. Additionally, the query handling has been improved to support string aliases for tables and columns, enhancing the flexibility of query construction. The changes also include updates to the query methods to accept both string and symbol types, improving usability and consistency across the codebase. Comprehensive tests have been added to validate these new features and ensure correct functionality. Update database connection string and enhance project documentation This commit updates the DATABASE_URL in the .env file to use 'postgres' as the username for improved security. Additionally, it adds a note in the project.mdc file regarding the limitations of the Crystal programming language in dynamically creating symbols. The query_spec.cr file has been updated to ensure SQL queries are formatted correctly, including adjustments to WHERE clauses and JOIN conditions for clarity. Furthermore, the table_spec.cr file now uses Int64 for count queries to ensure consistency across the codebase. Refactor query and table specifications for improved readability and consistency This commit enhances the clarity of the query and table specifications by adjusting formatting and comments throughout the codebase. Changes include consistent spacing in join conditions, improved alias handling in query methods, and refined comments for better understanding. Additionally, unnecessary lines have been removed to streamline the code, contributing to overall maintainability. Add JSONBConverter module for handling JSON data in CQL This commit introduces a new CQL::DB::JSONBConverter module to manage JSON data conversion between database result sets and JSON format. The UserPref struct has been updated to utilize this new converter, enhancing the handling of JSON preferences. Additionally, the import statements in cql.cr have been adjusted to include the new converters directory, ensuring proper module loading. Add .tool-versions file and remove obsolete structure.sql This commit introduces a new .tool-versions file specifying Crystal version 1.15.1 for consistent development environments. Additionally, the obsolete structure.sql file has been removed, streamlining the project and eliminating unnecessary files. Various adjustments have been made to improve code organization and clarity across the codebase. Refactor column documentation and simplify table assignment in InternalHelpers This commit removes an unnecessary blank line in the CQL::Column documentation for improved clarity. Additionally, it refactors the assignment of the table property in the InternalHelpers module to use a more concise syntax, enhancing code readability. These changes contribute to a cleaner and more maintainable codebase. Refactor CQL::Schema definition to require adapter parameter This commit updates the CQL::Schema.define method to require an adapter parameter, enhancing clarity and ensuring that the correct database adapter is explicitly specified during schema initialization. Corresponding changes have been made in the schema_spec tests to reflect this new requirement, improving the robustness of the schema setup process. Refactor spec structure and enhance test coverage for CQL This commit reorganizes the spec files by consolidating helper requirements and removing obsolete spec_helper files. It introduces new test files for migration, query, schema, and table functionalities, significantly improving test coverage for the CQL library. Additionally, it implements a custom password validator and various model specifications, ensuring robust validation and callback mechanisms. These changes contribute to a more structured and maintainable testing environment, enhancing the overall quality of the codebase. Update SQLite database paths in GitHub Actions workflow This commit modifies the paths for SQLite database files in the GitHub Actions workflow configuration. The database files are now created in the ./spec/support/db directory instead of ./spec/db, ensuring better organization of support files. The permissions for the database files remain unchanged, maintaining the required access settings. Remove unnecessary blank line in tabledb_schema definition for improved clarity Update Crystal Docker image version in GitHub Actions workflow to 1.15.1 for consistency across environments
105e9ab
to
cb5afe4
Compare
…Update test to use a variable for invalid path, enhancing clarity and maintainability.
… indentation in CQL::Schema definition. This change enhances code clarity and maintainability.
…es, improving type safety and clarity in the insertable functionality.
…nality This commit introduces a new Scopes module within the CQL::ActiveRecord namespace, allowing for the definition of query scopes that can be chained. Additionally, the model class now includes the Scopes module to enable this feature. Minor adjustments were made to the Queryable module to support the new functionality.
This commit introduces a new test suite for the ScopesPost model, validating various query scopes such as published, recent, and category-based retrievals. The tests ensure that the defined scopes function correctly and can be chained effectively, enhancing the overall reliability of the ActiveRecord implementation.
…ality This commit modifies the ScopesPost model to enhance the constructor by adding a trailing comma for better syntax consistency. Additionally, a blank line was removed in the CQL::ActiveRecord::Model module to streamline the code. These changes contribute to improved readability and maintainability of the codebase.
This commit introduces a new MergeQuery class that encapsulates the logic for merging properties from one Query object into another. The merge operation includes handling distinct clauses, select columns, joins, where conditions, group by, having, order by, limit, and offset. Additionally, comprehensive tests for query merging have been added to ensure correct behavior across various scenarios, enhancing the overall functionality and reliability of the query system.
This commit introduces the ScopesPost model along with its associated database schema and setup function. The model defines various query scopes, including published, recent, and category-based retrievals. Additionally, a new helper function for setting up the database with sample data is added, facilitating testing of the ActiveRecord functionality. These changes enhance the testability and organization of the codebase.
…opesPost model to improve code quality and maintainability.
This commit introduces several improvements to the CQL::ActiveRecord::Insertable module, including enhanced tests for the .create! and .find_or_create_by methods. The tests now verify that created records return the correct instance and persist in the database. Additionally, the create! method signatures have been updated to specify return types, improving type safety. New methods for handling attribute hashes and back columns have also been added, enhancing the overall functionality and usability of the insertable operations.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull Request Overview
This pull request introduces new test suites for the CQL ORM library’s Active Record implementation while updating SQL formatting and file paths to improve consistency. Key changes include:
- Adding tests for attributes, callbacks, deletions, insertions, and various query operations.
- Refining SQL output formatting by removing redundant parentheses and adjusting returning clause expectations.
- Updating file paths and environment configurations for database connections and integrating updated dialect tests.
Reviewed Changes
Copilot reviewed 131 out of 131 changed files in this pull request and generated 2 comments.
Show a summary per file
File | Description |
---|---|
spec/operations/insert_spec.cr | Reformatted insert query chains and adjusted returning clause expectations. |
spec/operations/delete_spec.cr | Updated SQL formatting and removed unused returning clause calls. |
spec/operations/active_record/updateable_spec.cr | Added tests for updating records, including edge cases with empty attribute hashes. |
spec/operations/active_record/queryable_spec.cr | Introduced chainable query method tests. |
spec/operations/active_record/insertable_spec.cr | Expanded tests for record creation under various conditions. |
spec/operations/active_record/deleteable_spec.cr | Reviewed delete methods along with callbacks execution order. |
spec/models/customer_model_spec.cr | Removed obsolete CustomerModel test file. |
spec/integration/dialects/* | Added/updated tests for SQLite, Postgres, and MySQL dialect specific SQL generation. |
spec/integration/adapters/* | Updated schema tests including alteration, foreign key changes, and error handling. |
spec/core/schema_spec.cr | Enhanced schema building and query execution tests. |
spec/core/migration_spec.cr | Adjusted migration tests with updated file paths and version type. |
db/structure.sql | Removed outdated structure definitions. |
.github/workflows/crystal.yml | Updated database file paths and added clients for Postgres and MySQL. |
.env | Changed DATABASE_URL to use an empty password with Postgres. |
.cursor/rules/project.mdc | Added project configuration rules for Crystal ORM. |
Comments suppressed due to low confidence (1)
spec/models/customer_model_spec.cr:1
- The CustomerModel file has been removed; ensure that no other tests or code depend on this obsolete model.
struct CustomerModel
id = user.id! | ||
|
||
expect_raises(CQL::Error) do | ||
TestUser.update!(id, {} of Symbol => DB::Any) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] Consider using a typed initializer (e.g. 'Hash(Symbol, DB::Any).new') instead of '{} of Symbol => DB::Any' for setting empty attributes to improve clarity.
TestUser.update!(id, {} of Symbol => DB::Any) | |
TestUser.update!(id, Hash(Symbol, DB::Any).new) |
Copilot uses AI. Check for mistakes.
@@ -1 +1 @@ | |||
DATABASE_URL=postgres://example:example@localhost:5432/example | |||
DATABASE_URL=postgres://postgres:@localhost:5432/example |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The database URL now uses an empty password; in production environments, consider setting a secure non-empty password to reduce security risks.
DATABASE_URL=postgres://postgres:@localhost:5432/example | |
DATABASE_URL=postgres://postgres:securepassword@localhost:5432/example |
Copilot uses AI. Check for mistakes.
…clarity This commit modifies the example structures in the callbacks, definition, and model files to include the CQL::ActiveRecord::Model module. This change enhances the clarity of the examples by explicitly showing the correct inheritance structure for ActiveRecord models.
This commit updates the README.md to improve clarity regarding the use of CQL's Active Record pattern, including changes to the struct definitions to utilize CQL::ActiveRecord::Model. Additionally, it enhances various documentation sections, such as FAQs and core concepts, to provide clearer explanations and examples. Several outdated or redundant files have been removed to streamline the documentation structure, ensuring a more cohesive user experience.
…arted, and handling migrations This commit enhances the documentation across several guides, including troubleshooting, complex queries, getting started with CQL Active Record, and handling migrations. Key updates include improved formatting, expanded examples, and detailed explanations of concepts such as advanced filtering, joins, and best practices for migrations. These changes aim to provide clearer guidance and a more comprehensive understanding of using CQL effectively.
… CRUD operations, model definitions, migrations, pagination, and validations This commit introduces comprehensive documentation covering various aspects of CQL Active Record, including lifecycle callbacks, CRUD operations, model definitions, database migrations, pagination methods, and validation mechanisms. Each section provides clear examples and explanations to enhance user understanding and facilitate effective usage of the framework. The updates aim to improve the overall documentation structure and usability for developers working with CQL.
… for consistency This commit updates the example model definitions in the CRUD operations, pagination, and persistence details guides to remove commented-out code and ensure a consistent structure. The changes enhance clarity and readability, making it easier for users to understand how to define models using CQL::ActiveRecord::Model.
This commit enhances the CQL Guides section by adding a welcome message and outlining the topics covered, including Active Record, querying, migrations, and relationships. It also provides navigation instructions for users to effectively utilize the guides. Additionally, minor formatting adjustments were made to the Active Record migration documentation for clarity. These updates aim to improve the overall usability and accessibility of the documentation for Crystal developers.
This commit introduces comprehensive guides for various relationships in CQL Active Record, including `BelongsTo`, `HasOne`, `HasMany`, and `ManyToMany`. Each guide provides detailed explanations, schema definitions, model examples, and practical usage scenarios to help developers understand and implement these relationships effectively. The updates aim to improve the clarity and usability of the documentation, facilitating better learning and application of CQL's Active Record features.
…structure This commit refines the Active Record documentation by updating the links for relationship guides to point to the correct paths within the documentation structure. The changes enhance navigation and clarity for users seeking to understand model associations, ensuring that the documentation is more user-friendly and accessible. Additionally, minor formatting adjustments were made to maintain consistency throughout the guides.
…and structural updates This commit introduces detailed guides for `BelongsTo`, `HasOne`, `HasMany`, and `ManyToMany` relationships in CQL Active Record, providing schema definitions, model examples, and practical usage scenarios. Additionally, it updates the documentation structure for improved navigation and clarity, ensuring users can easily access and understand the various model associations. Minor formatting adjustments were also made to maintain consistency throughout the guides.
This commit updates the documentation structure for CQL Active Record, correcting paths and enhancing navigation. It includes changes to model definitions to consistently use the `includes` syntax for `CQL::ActiveRecord::Model`. Additionally, it removes the outdated querying guide and refines links in the README for better accessibility. These updates aim to improve the overall clarity and usability of the documentation for developers.
This commit modifies the SUMMARY.md file by adding links to the "Getting Started" and "Complex Queries" guides, improving the overall structure and accessibility of the documentation. The changes aim to facilitate easier navigation for users seeking to understand CQL Active Record features.
…s, and migration patterns in CQL This commit introduces detailed guides covering schema alterations, CRUD operations (creating, reading, updating, and deleting records), and the migration process within the CQL framework. Each section includes real-world examples, method explanations, and best practices to enhance user understanding and facilitate effective database management. The updates aim to improve the overall clarity and usability of the documentation for developers working with CQL.
This commit modifies the links in the SUMMARY.md file to point to the newly structured guides for querying and complex queries within the CQL Active Record documentation. The changes enhance navigation and ensure users can easily access the relevant resources, improving the overall clarity and usability of the documentation.
This commit introduces a new module, CQL::ActiveRecord::Transactional, which provides a `transaction` method for models. This method allows operations to be executed within a database transaction, ensuring that changes are committed only if the block executes successfully. Additionally, comprehensive tests have been added to verify the transaction behavior, including commit and rollback scenarios. Dummy models and schemas for testing have also been created to support these functionalities.
…n block parameters This commit simplifies the error handling in the CQL schema execution methods by removing redundant rescue blocks. It also updates the transaction block parameters in the CQL::ActiveRecord::Transactional module to use an underscore for unused variables, enhancing code clarity. Additionally, minor adjustments were made to the transactional schema definition.
This commit introduces a new section on Transactions in the README.md, detailing how to maintain data integrity using ACID-compliant database transactions. A link to the dedicated Transactions guide has also been added to the SUMMARY.md for improved navigation.
This commit significantly refines the Transactions guide, enhancing clarity and structure. The introduction now emphasizes the importance of transactions in ensuring data integrity within Crystal applications using CQL's Active Record pattern. Key concepts such as ACID properties, practical examples, and best practices for transaction management are elaborated upon. Additionally, the guide includes detailed explanations of transaction logic through banking operations, ensuring users understand the critical role of transactions in complex business scenarios.
This commit introduces a comprehensive implementation of optimistic locking in CQL, allowing for safe concurrent updates to records. A new version column mechanism is added to prevent conflicts during updates, along with detailed documentation on its usage and best practices. Additionally, tests have been created to validate the functionality of optimistic locking within Active Record models, ensuring robust error handling and version management during concurrent modifications.
This commit adds a new guide on Optimistic Locking in CQL, detailing its implementation, use cases, and best practices for handling concurrent updates. The SUMMARY.md file is updated to include a link to this new guide, enhancing the documentation's structure and accessibility for users. Additionally, minor formatting adjustments were made in the codebase for clarity.
This commit expands the documentation on nested transactions within the CQL Active Record guide. It includes detailed scenarios demonstrating the behavior of inner and outer transactions, including successful commits, rollbacks, and exception handling. Key points about savepoints, rollback mechanisms, and the implications of outer transaction rollbacks are clarified to improve user understanding of complex transaction workflows. The overall structure and clarity of the guide are also enhanced.
This commit updates the transaction block parameters in the tests for CQL::ActiveRecord::Transactional to use an underscore for unused variables. This change enhances code clarity and consistency across the test suite, ensuring that the focus remains on relevant variables while maintaining readability.
This commit streamlines the documentation on nested transactions in the CQL Active Record guide. It clarifies the use of savepoints, rollback mechanisms, and the implications of exceptions within inner transactions. The structure is improved for better readability, and key scenarios are summarized to enhance user understanding of complex transaction workflows. Emphasis is placed on the importance of using nested transactions judiciously to manage independent rollback scopes within larger operations.
This commit enhances the CQL Active Record documentation by introducing sections on explicit commit and rollback mechanisms within transaction blocks. It provides clear examples demonstrating how to manually control transaction outcomes, including scenarios for triggering rollbacks based on business logic and explicitly committing changes. Additionally, an important note is included regarding the usability of the transaction object after commit or rollback, improving user understanding of transaction management in CQL.
This pull request introduces significant updates to the CQL ORM library, including new features, test enhancements, and codebase refinements. Key changes involve improvements to schema handling, database compatibility, and testing structure. Below is a categorized summary of the most important changes:
Schema and Database Enhancements:
spec/core/schema_spec.cr
. This includes error handling for invalid database URIs and malformed queries.references
andreferences_columns
for better readability. [1] [2]Testing and Validation:
spec/core/schema_spec.cr
. These tests ensure robust handling of edge cases and database-specific behaviors.Codebase Organization:
spec/migration_spec.cr
was moved tospec/core/migration_spec.cr
, and adapter-specific tests were moved tospec/integration/adapters/
. [1] [2]spec/support/db/
for consistency and maintainability. [1] [2]Configuration and Environment:
.env
to use a more secure and realisticDATABASE_URL
format for PostgreSQL connections..github/workflows/crystal.yml
by adding support for PostgreSQL and MySQL clients and improving SQLite database handling.Documentation and Rules:
.cursor/rules/project.mdc
, emphasizing adherence to SOLID principles and the use of idiomatic Crystal programming practices.These changes collectively improve the functionality, maintainability, and reliability of the CQL ORM library while ensuring compatibility with major relational databases.