Skip to content
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

feat: impl dal for standalone tegg #197

Merged
merged 3 commits into from
Mar 22, 2024
Merged

feat: impl dal for standalone tegg #197

merged 3 commits into from
Mar 22, 2024

Conversation

killagu
Copy link
Contributor

@killagu killagu commented Mar 22, 2024

Checklist
  • npm test passes
  • tests and/or benchmarks are included
  • documentation is changed or added
  • commit message follows commit guidelines
Affected core subsystem(s)
Description of change

Summary by CodeRabbit

  • Refactor
    • Updated logging system across various components for consistency and improved performance.
  • New Features
    • Enhanced Data Access Layer (DAL) functionalities for improved data handling.
    • Added classes for lifecycle management and custom SQL extensions.
  • Documentation
    • Restructured and refined documentation for better clarity and readability.

Copy link

coderabbitai bot commented Mar 22, 2024

Warning

Rate Limit Exceeded

@killagu has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 4 minutes and 24 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.
Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.
Please see our FAQ for further information.

Commits Files that changed from the base of the PR and between 307c60d and b822856.

Walkthrough

The recent updates focus on the migration from EggLogger to a new Logger interface from @eggjs/tegg across various components. This includes adjustments in import statements, constructor parameters, and type declarations. Additionally, the project introduces enhancements in the data access layer (DAL), with the setup of new classes and interfaces for database interactions, including a specific implementation for managing Foo entities and their operations, alongside the necessary SQL scripts for table creation.

Changes

Files Change Summary
core/dal-runtime/src/BaseSqlMap.ts,
.../SqlMapLoader.ts,
plugin/dal/lib/DalTableEggPrototypeHook.ts
Updated EggLogger to Logger from @eggjs/tegg.
core/tegg/index.ts Introduced Logger interface.
plugin/dal/app.ts Added reference path declaration.
standalone/.../src/Runner.ts Added new imports and instantiated classes for DAL plugin lifecycle management.
standalone/.../test/fixtures/dal-module/... Added new DAL module test fixtures, including Foo entity, DAO classes, SQL extension, and script.

🐰✨
In the code's garden, changes bloom,
From logger's shift to DAL's new room.
Tables and queries, neatly dressed,
In digital meadows, they now rest.
Hop, skip, jump, in joy we unite,
For code that's cleaner, and bugs take flight. 🚀🌟
🐰✨

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 5

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 0c382d6 and a88237a.
Files ignored due to path filters (6)
  • plugin/dal/package.json is excluded by: !**/*.json
  • standalone/standalone/package.json is excluded by: !**/*.json
  • standalone/standalone/test/fixtures/dal-module/dal/structure/Foo.json is excluded by: !**/*.json
  • standalone/standalone/test/fixtures/dal-module/module.yml is excluded by: !**/*.yml
  • standalone/standalone/test/fixtures/dal-module/package.json is excluded by: !**/*.json
  • standalone/standalone/test/fixtures/dal-module/tsconfig.json is excluded by: !**/*.json
Files selected for processing (13)
  • core/dal-runtime/src/BaseSqlMap.ts (2 hunks)
  • core/dal-runtime/src/SqlMapLoader.ts (1 hunks)
  • core/tegg/index.ts (1 hunks)
  • plugin/dal/app.ts (1 hunks)
  • plugin/dal/lib/DalTableEggPrototypeHook.ts (1 hunks)
  • standalone/standalone/src/Runner.ts (5 hunks)
  • standalone/standalone/test/fixtures/dal-module/Foo.ts (1 hunks)
  • standalone/standalone/test/fixtures/dal-module/dal/dao/FooDAO.ts (1 hunks)
  • standalone/standalone/test/fixtures/dal-module/dal/dao/base/BaseFooDAO.ts (1 hunks)
  • standalone/standalone/test/fixtures/dal-module/dal/extension/FooExtension.ts (1 hunks)
  • standalone/standalone/test/fixtures/dal-module/dal/structure/Foo.sql (1 hunks)
  • standalone/standalone/test/fixtures/dal-module/main.ts (1 hunks)
  • standalone/standalone/test/index.test.ts (2 hunks)
Additional comments: 24
standalone/standalone/test/fixtures/dal-module/dal/extension/FooExtension.ts (1)
  • 15-20: The SQL mapping for findByName is correctly defined. Ensure that the placeholders are properly sanitized and handled to prevent SQL injection vulnerabilities.
standalone/standalone/test/fixtures/dal-module/dal/dao/FooDAO.ts (1)
  • 11-19: The FooDAO class is well-implemented, making good use of dependency injection and the singleton pattern. The findByName method is correctly defined.
plugin/dal/lib/DalTableEggPrototypeHook.ts (1)
  • 4-12: The replacement of EggLogger with the new Logger interface is correctly implemented. Ensure that the lifecycle hook functionality is thoroughly tested, especially the management of table models and SQL maps.
core/dal-runtime/src/SqlMapLoader.ts (1)
  • 3-12: The update to use the new Logger interface is correctly implemented. Consider adding more detailed error logging within the load method to aid in troubleshooting SQL map loading issues.
standalone/standalone/test/fixtures/dal-module/dal/structure/Foo.sql (1)
  • 1-44: The SQL schema for the egg_foo table is well-defined, covering a wide range of column types and indexes. Consider reviewing the defined indexes for necessity and performance impact, especially in production environments.
standalone/standalone/test/fixtures/dal-module/main.ts (1)
  • 7-92: The FooRunner class demonstrates the practical use of the DAL for database operations. Ensure that error handling is implemented for database operations and that input validation is performed for the properties set on the Foo object.
standalone/standalone/test/fixtures/dal-module/Foo.ts (7)
  • 13-18: The @Table decorator is correctly used to define table properties such as name, comment, character set, and collation. This is a good practice for ensuring that the table's metadata is clearly specified.
  • 19-24: The use of the @Index decorator to define a unique index on the name and col1 columns is appropriate. Specifying the index type and store type enhances the database's performance and search capabilities.
  • 31-37: The primary key column id is correctly defined with the @Column decorator, including properties like autoIncrement and a comment. This is essential for database integrity and identification of records.
  • 40-45: Using the uniqueKey: true option for the name column ensures that each record has a unique name. This is a good practice for data uniqueness and integrity.
  • 56-60: Consider adding a comment to the bitColumn definition to explain its purpose or usage within the application. While the column definition is correct, additional documentation can improve code maintainability.
  • 231-237: The definition of the enumColumn with specific allowed values ('A', 'B') is a good use of the ENUM type. This restricts the column to a set of predefined values, enhancing data integrity.
  • 247-250: The inclusion of a geometryColumn of type GEOMETRY demonstrates the capability to handle spatial data types. This is particularly useful for applications that require geographic or spatial data.
standalone/standalone/test/index.test.ts (1)
  • 8-8: The import statement for Foo is correctly added to support the new test case in the dal runner section. This ensures that the Foo class is available for testing.
core/dal-runtime/src/BaseSqlMap.ts (2)
  • 3-3: The update to import Logger from @eggjs/tegg instead of EggLogger aligns with the shift towards a more unified logging system tailored for Tegg. This is a positive change for consistency across the framework.
  • 14-16: The modification of the BaseSqlMapGenerator constructor to accept a Logger instance is correctly implemented. This ensures that the class uses the updated logging interface.
standalone/standalone/src/Runner.ts (3)
  • 33-37: The addition of imports for DAL-related classes (DalTableEggPrototypeHook, DalModuleLoadUnitHook, MysqlDataSourceManager, SqlMapManager, TableModelManager) is correctly done. These classes are essential for the DAL's lifecycle management within the standalone runner.
  • 157-162: The instantiation and registration of DalTableEggPrototypeHook and DalModuleLoadUnitHook within the Runner class are correctly implemented. This ensures that DAL-related hooks are properly integrated into the lifecycle management of the application.
  • 253-262: The cleanup process in the destroy method, which clears instances of MysqlDataSourceManager, SqlMapManager, and TableModelManager, is a good practice. It ensures that resources are properly released when the application is shutting down.
standalone/standalone/test/fixtures/dal-module/dal/dao/base/BaseFooDAO.ts (5)
  • 10-10: The comment warns against manual modifications as the file is auto-generated. This is good practice for generated code to prevent accidental edits. However, ensure there's a clear process or documentation on how to regenerate this file if the model or requirements change.
  • 14-16: Using @SingletonProto with AccessLevel.PUBLIC is appropriate for a DAO class that needs to be widely accessible within the application. This setup ensures that the class is treated as a singleton, which is a common pattern for DAOs to ensure efficient resource use and consistent access to the data source.
  • 26-230: The insert method dynamically constructs a data object for insertion based on the provided raw object. This approach is flexible but requires careful validation of input data to prevent SQL injection or other security vulnerabilities. Ensure that all data passed to this method is properly sanitized upstream and that the dataSource.executeRawScalar method includes adequate protection against injection attacks.
  • 233-442: Similar to the insert method, the update method constructs a new data object for updating records. It's crucial to ensure that the id parameter and the data object are properly validated and sanitized to prevent SQL injection and ensure data integrity. Additionally, consider implementing optimistic locking to handle concurrent updates safely.
  • 457-493: The various find methods demonstrate a consistent pattern for querying the database. Ensure that these methods are optimized for performance, especially for large datasets. Consider adding pagination support or query optimization techniques as needed.

Comment on lines +20 to +24
@Inject({
name: DataSourceInjectName,
})
@DataSourceQualifier('dal.foo.Foo')
protected readonly dataSource: DataSource<Foo>;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The search conducted across the repository for 'dal.foo.Foo' only found occurrences within @DataSourceQualifier annotations and did not reveal any actual configuration files or entries defining 'dal.foo.Foo'. This suggests that the data source configuration for 'dal.foo.Foo' might not exist or is not correctly set up, supporting the concerns raised in the review comment about potential misconfiguration leading to runtime errors or incorrect data source usage.

Analysis chain

The use of @Inject and @DataSourceQualifier to inject the DataSource is a clean way to manage dependencies. However, ensure that the qualifier string 'dal.foo.Foo' correctly matches the intended data source configuration. Misconfiguration here could lead to runtime errors or incorrect data source usage.


Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that the data source configuration for 'dal.foo.Foo' exists and is correctly set up.
grep -R "dal.foo.Foo" ./config

Length of output: 72



Script:

#!/bin/bash
# Perform a broader search for 'dal.foo.Foo' across the repository to find the data source configuration.
grep -R "dal.foo.Foo" .

Length of output: 254

Comment on lines +445 to +455
public async delete(id: number): Promise<DeleteResult> {
return this.dataSource.executeRawScalar('delete', {
id,
});
}

public async del(id: number): Promise<DeleteResult> {
return this.dataSource.executeRawScalar('delete', {
id,
});
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The delete and del methods are identical, providing two ways to delete a record by its id. Having duplicate functionality under different method names can lead to confusion and maintenance challenges. Consider removing one of the methods or clearly documenting the reason for the duplication.

-  public async del(id: number): Promise<DeleteResult> {
-    return this.dataSource.executeRawScalar('delete', {
-      id,
-    });
-  }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
public async delete(id: number): Promise<DeleteResult> {
return this.dataSource.executeRawScalar('delete', {
id,
});
}
public async del(id: number): Promise<DeleteResult> {
return this.dataSource.executeRawScalar('delete', {
id,
});
}
public async delete(id: number): Promise<DeleteResult> {
return this.dataSource.executeRawScalar('delete', {
id,
});
}

standalone/standalone/test/index.test.ts Outdated Show resolved Hide resolved
Comment on lines 1 to 6
import _ from 'lodash';
import { ColumnType, IndexType, SqlType, SqlMap, TableModel } from '@eggjs/dal-decorator';
import { type EggLogger } from 'egg';
import { Logger } from '@eggjs/tegg';
import { TemplateUtil } from './TemplateUtil';

export interface GenerateSqlMap {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [56-84]

Given the learning note about a GitHub issue opened to track the implementation of index left matching in the BaseSqlMapGenerator class, it's important to ensure that this feature is either implemented or tracked appropriately. If not already addressed, consider adding a comment or TODO in the code to remind of this pending enhancement.

Would you like me to open a follow-up GitHub issue to track the implementation of index left matching, or is there already an issue for this?

Comment on lines +12 to +18
export interface Logger {
debug(message?: any, ...optionalParams: any[]): void;
log(message?: any, ...optionalParams: any[]): void;
info(message?: any, ...optionalParams: any[]): void;
warn(message?: any, ...optionalParams: any[]): void;
error(message?: any, ...optionalParams: any[]): void;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tip

Codebase Verification

The findings indicate that EggLogger is still being used in various parts of the codebase, including core functionalities, plugins, and test fixtures. This suggests that not all components have been updated to use the newly introduced Logger interface. It's important for the development team to manually verify these occurrences to ensure they align with the intended architectural and compatibility goals, especially considering the potential for deliberate maintenance of EggLogger usage in certain scenarios.

Analysis chain

The Logger interface is well-defined, covering standard logging levels. Ensure that this interface is consistently implemented across the application and that existing logging calls are updated accordingly.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Search for files that might still be using the old `EggLogger` to ensure they've been updated.
rg --type ts "EggLogger"

Length of output: 2190

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between a88237a and 307c60d.
Files selected for processing (4)
  • core/dal-runtime/test/DataSource.test.ts (1 hunks)
  • plugin/controller/README.md (1 hunks)
  • plugin/dal/README.md (3 hunks)
  • standalone/standalone/test/index.test.ts (2 hunks)
Files skipped from review due to trivial changes (1)
  • core/dal-runtime/test/DataSource.test.ts
Files skipped from review as they are similar to previous changes (1)
  • standalone/standalone/test/index.test.ts
Additional comments: 1
plugin/controller/README.md (1)
  • 20-20: The modification to use the "extends": "@eggjs/tsconfig" directive in tsconfig.json aligns with best practices for maintaining consistent TypeScript configurations across projects. This change simplifies the configuration and leverages shared settings, which is beneficial for project maintainability.

@killagu killagu merged commit 56b259d into master Mar 22, 2024
10 checks passed
@killagu killagu deleted the feat/dal_standaline branch March 22, 2024 17:02
@@ -1,3 +1,5 @@
/// <reference path='./typings/index.d.ts'/>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

必须加这个声明才能找到类型定义?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants