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: Introduce backup and restore for postgres #37326

Open
wants to merge 28 commits into
base: release
Choose a base branch
from

Conversation

abhvsn
Copy link
Contributor

@abhvsn abhvsn commented Nov 11, 2024

Description

PR to add backup and restore functionality for Postgres.

Added support for backup and restore commands, but not to import-db and export-db. They are discouraged already anyway, and we can add support to them later if it's really needed. Or actually deprecate them and remove them along with MongoDB itself.

Fixes #35369

/test Sanity

🔍 Cypress test results

Warning

Tests have not run on the HEAD 9ff1b9c yet


Fri, 07 Feb 2025 10:51:41 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for PostgreSQL database backups and restoration.
    • Introduced a new PostgresDumpLink class for PostgreSQL export functionality.
    • Implemented restorePostgres function for restoring PostgreSQL databases.
  • Improvements

    • Standardized database name extraction with a new utility function.
    • Enhanced error handling and logging during backup and restoration processes.
    • Updated existing MongoDB handling to use the new standardized utility function.

Copy link
Contributor

coderabbitai bot commented Nov 11, 2024

Walkthrough

The changes in this pull request enhance backup functionality by integrating PostgreSQL support alongside existing MongoDB capabilities. Modifications include the addition of a new PostgresDumpLink class, updates to the backup and restore processes, and the introduction of new utility functions for database name extraction. Tests have been updated to reflect these changes, ensuring that both PostgreSQL and MongoDB URIs are handled correctly. Overall, the updates standardize the handling of database URLs and improve error handling in the backup and restore processes.

Changes

File Path Change Summary
app/client/packages/rts/src/ctl/backup/backup.test.ts Added tests for PostgreSQL dump command and updated MongoDB URI handling tests to use getDatabaseNameFromUrl.
app/client/packages/rts/src/ctl/backup/index.ts Modified run function to validate database URLs for MongoDB and PostgreSQL; added PostgreSQL link to backup chain.
app/client/packages/rts/src/ctl/backup/links/ManifestLink.ts Updated doBackup method to use getDatabaseNameFromUrl instead of getDatabaseNameFromMongoURI.
app/client/packages/rts/src/ctl/backup/links/MongoDumpLink.ts Modified doBackup to check if the database URL starts with "mongodb" before executing the export process.
app/client/packages/rts/src/ctl/backup/links/PostgresDumpLink.ts Introduced PostgresDumpLink class with doBackup method for PostgreSQL; added executePostgresDumpCMD function.
app/client/packages/rts/src/ctl/backup/links/index.ts Added export for PostgresDumpLink.
app/client/packages/rts/src/ctl/restore.ts Added restorePostgres function and modified restoreDatabase to call the appropriate restore function based on dbUrl.
app/client/packages/rts/src/ctl/utils.ts Renamed getDatabaseNameFromMongoURI to getDatabaseNameFromUrl and updated its parameter type.

Possibly related PRs

Suggested labels

Bug, ok-to-test

Suggested reviewers

  • pratapaprasanna
  • mohanarpit
  • nidhi-nair

🎉 In the realm of code, where backups reside,
PostgreSQL joins, with MongoDB side by side.
Functions revamped, with tests that now shine,
A sprinkle of magic, our databases align!
So here's to the changes, both bold and bright,
In the world of backups, we now take flight! 🚀

Warning

Rate limit exceeded

@sharat87 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 20 minutes and 20 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

Reviewing files that changed from the base of the PR and between 4252c0e and e03d925.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4252c0e and e03d925.

📒 Files selected for processing (1)
  • app/client/packages/rts/src/ctl/backup/links/PostgresDumpLink.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/client/packages/rts/src/ctl/backup/links/PostgresDumpLink.ts

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>, please review it.
    • Generate unit testing code 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 testing code 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Nov 11, 2024
@abhvsn abhvsn closed this Nov 11, 2024
@abhvsn abhvsn reopened this Nov 11, 2024
@abhvsn abhvsn self-assigned this Nov 11, 2024
@abhvsn abhvsn changed the title chore: Introduce backup and restore for postgres feat: Introduce backup and restore for postgres Nov 11, 2024
@abhvsn abhvsn added Enhancement New feature or request and removed skip-changelog Adding this label to a PR prevents it from being listed in the changelog labels Nov 11, 2024
@abhvsn
Copy link
Contributor Author

abhvsn commented Nov 11, 2024

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/11784388675.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37326.
recreate: .

1 similar comment
Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/11784388675.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37326.
recreate: .

@abhvsn
Copy link
Contributor Author

abhvsn commented Nov 11, 2024

/build-deploy-preview skip-tests=true

Copy link

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/11784652237.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37326.
recreate: .

Copy link

Deploy-Preview-URL: https://ce-37326.dp.appsmith.com

@github-actions github-actions bot added DB Infrastructure Pod Pod to handle database infrastructure High This issue blocks a user from building or impacts a lot of users Move to Postgres Issues required to be solved for the move to Postgres as repository layer Task A simple Todo labels Nov 12, 2024
@abhvsn abhvsn marked this pull request as ready for review November 13, 2024 04:43
@abhvsn abhvsn added the ok-to-test Required label for CI label Nov 13, 2024
Copy link
Contributor

@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.

Actionable comments posted: 13

🧹 Outside diff range and nitpick comments (7)
deploy/docker/fs/opt/appsmith/utils/bin/export_db.js (1)

Line range hint 43-65: Improve error handling and application state management

The error handling could be more specific and ensure proper application restart in all scenarios.

+  const DatabaseExportError = class extends Error {
+    constructor(message, cause) {
+      super(message);
+      this.cause = cause;
+      this.name = 'DatabaseExportError';
+    }
+  };
+
   try {
     check_supervisord_status_cmd = '/usr/bin/supervisorctl >/dev/null 2>&1 ';
     shell.exec(check_supervisord_status_cmd, function (code) {
       if (code > 0) {
-        shell.echo('application is not running, starting supervisord');
+        throw new DatabaseExportError('Supervisord is not running');
         shell.exec('/usr/bin/supervisord');
       }
     });
deploy/docker/fs/opt/appsmith/utils/bin/utils.js (1)

Add PostgreSQL support and remove MongoDB dependencies in utils.js

The preprocessMongoDBURI function is still present and PostgreSQL support is not implemented.

  • deploy/docker/fs/opt/appsmith/utils/bin/utils.js (Line 125)
🔗 Analysis chain

Line range hint 1-201: Verify PostgreSQL support in utility functions

Several utility functions in this file were originally designed for MongoDB. Let's verify they work correctly with PostgreSQL.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for PostgreSQL-specific handling in the codebase
rg -l 'postgres|postgresql' --type js

# Check for any potential MongoDB-specific operations that might need PostgreSQL equivalents
ast-grep --pattern 'MongoClient|mongoose|mongodb' 

Length of output: 1305


Script:

#!/bin/bash
# Verify PostgreSQL support within utils.js
ast-grep --pattern 'PostgreSQL|pg' deploy/docker/fs/opt/appsmith/utils/bin/utils.js

# Check if MongoDB functions are still being used or referenced in utils.js
ast-grep --pattern 'preprocessMongoDBURI' deploy/docker/fs/opt/appsmith/utils/bin/utils.js

Length of output: 279

deploy/docker/fs/opt/appsmith/utils/bin/backup.test.js (1)

59-67: Add test cases for edge cases in PostgreSQL connection string

While the basic test case looks good, consider adding tests for:

  • Invalid connection strings
  • Connection strings with special characters
  • Different PostgreSQL connection string formats
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2)

38-46: Avoid redundant utils.getDburl() calls

Pass dbUrl as a parameter to get_table_or_collection_len to prevent multiple calls.

Apply this diff:

- function get_table_or_collection_len() {
+ function get_table_or_collection_len(dbUrl) {

Update the call at line 63:

- const collectionsLen = get_table_or_collection_len();
+ const collectionsLen = get_table_or_collection_len(dbUrl);

12-16: Handle unsupported database types

Add an else clause to handle cases where the database type is neither MongoDB nor PostgreSQL.

Apply this diff:

  } else if (dbUrl.startsWith('postgresql')) {
    restore_postgres_db(dbUrl);
+ } else {
+   console.error(`Unsupported database type: ${dbUrl}`);
+   process.exit(1);
  }
deploy/docker/fs/opt/appsmith/utils/bin/backup.js (1)

128-133: Store database URL in a variable to avoid multiple function calls

Currently, utils.getDburl() is called multiple times. Consider storing the result in a variable for efficiency.

Apply this diff to implement the change:

+      const dbUrl = utils.getDburl();
-      if (utils.getDburl().startsWith('mongodb')) {
+      if (dbUrl.startsWith('mongodb')) {
-        await executeMongoDumpCMD(destFolder, utils.getDburl())
+        await executeMongoDumpCMD(destFolder, dbUrl)
-      } else if (utils.getDburl().startsWith('postgresql')) {
+      } else if (dbUrl.startsWith('postgresql')) {
-        await executePostgresDumpCMD(destFolder, utils.getDburl());
+        await executePostgresDumpCMD(destFolder, dbUrl);
       }
deploy/docker/fs/opt/appsmith/utils/bin/restore.js (1)

64-65: Use consistent methods for database type checks

For consistency, use dbUrl.startsWith('postgresql') instead of dbUrl.includes('postgresql') when checking for PostgreSQL URLs.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7ba83bf and be3f228.

📒 Files selected for processing (7)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonDBConfig.java (1 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/backup.js (4 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/backup.test.js (2 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/export_db.js (1 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (3 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/restore.js (1 hunks)
  • deploy/docker/fs/opt/appsmith/utils/bin/utils.js (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • app/server/appsmith-server/src/main/java/com/appsmith/server/configurations/CommonDBConfig.java
🔇 Additional comments (4)
deploy/docker/fs/opt/appsmith/utils/bin/utils.js (1)

198-199: LGTM: Module exports are properly updated

The new functions are correctly exported.

deploy/docker/fs/opt/appsmith/utils/bin/import_db.js (2)

26-26: Use the correct database name in pg_restore command

The database name is hardcoded as appsmith. Ensure this matches the database in dbUrl or extract the database name dynamically.

Consider updating the command:

- const cmd = `pg_restore -U postgres -d appsmith --verbose --clean ${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}`;
+ const dbName = utils.getDbNameFromUrl(dbUrl);
+ const cmd = `pg_restore -U postgres -d ${dbName} --verbose --clean ${Constants.RESTORE_PATH}/${Constants.DUMP_FILE_NAME}`;

Ensure you have a utility function getDbNameFromUrl to extract the database name.


25-28: 🛠️ Refactor suggestion

Declare restore_postgres_db with const and pass dbUrl as a parameter

For consistency and proper scope, declare the function with const and pass dbUrl.

Apply this diff:

- restore_postgres_db = (dbUrl) => {
+ const restore_postgres_db = (dbUrl) => {

Likely invalid or redundant comment.

deploy/docker/fs/opt/appsmith/utils/bin/restore.js (1)

86-87: Verify getDatabaseNameFromDBURI supports PostgreSQL URIs

Confirm that utils.getDatabaseNameFromDBURI correctly parses database names from PostgreSQL URIs, as it now handles both MongoDB and PostgreSQL.

deploy/docker/fs/opt/appsmith/utils/bin/export_db.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/export_db.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/utils.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/backup.test.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/import_db.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/backup.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/backup.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/restore.js Outdated Show resolved Hide resolved
deploy/docker/fs/opt/appsmith/utils/bin/restore.js Outdated Show resolved Hide resolved
@sharat87 sharat87 reopened this Jan 27, 2025
@github-actions github-actions bot added the Platform Administration Pod Issues related to platform administration & management label Jan 27, 2025
Copy link

github-actions bot commented Feb 3, 2025

This PR has been closed because of inactivity.

@github-actions github-actions bot closed this Feb 3, 2025
@sharat87 sharat87 reopened this Feb 4, 2025
@sharat87
Copy link
Member

sharat87 commented Feb 4, 2025

/build-deploy-preview skip-tests=true

Copy link

github-actions bot commented Feb 4, 2025

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/13129876896.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37326.
recreate: .

Copy link

github-actions bot commented Feb 4, 2025

Deploy-Preview-URL: https://ce-37326.dp.appsmith.com

@sharat87 sharat87 removed the Stale label Feb 4, 2025
@sharat87
Copy link
Member

sharat87 commented Feb 6, 2025

/build-deploy-preview skip-tests=true

Copy link

github-actions bot commented Feb 6, 2025

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/13183201360.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37326.
recreate: .

Copy link

github-actions bot commented Feb 6, 2025

Deploy-Preview-URL: https://ce-37326.dp.appsmith.com

@sharat87
Copy link
Member

sharat87 commented Feb 7, 2025

/build-deploy-preview skip-tests=true

Copy link

github-actions bot commented Feb 7, 2025

Deploying Your Preview: https://github.com/appsmithorg/appsmith/actions/runs/13198341017.
Workflow: On demand build Docker image and deploy preview.
skip-tests: true.
env: ``.
PR: 37326.
recreate: .

Copy link

github-actions bot commented Feb 7, 2025

Deploy-Preview-URL: https://ce-37326.dp.appsmith.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DB Infrastructure Pod Pod to handle database infrastructure Enhancement New feature or request High This issue blocks a user from building or impacts a lot of users Move to Postgres Issues required to be solved for the move to Postgres as repository layer Platform Administration Pod Issues related to platform administration & management Task A simple Todo
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Feat: Backup and restore support for Postgres
4 participants