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

chore(rethinkdb): QueryMap: One-shot #10005

Merged
merged 1 commit into from
Jul 19, 2024
Merged

chore(rethinkdb): QueryMap: One-shot #10005

merged 1 commit into from
Jul 19, 2024

Conversation

mattkrick
Copy link
Member

@mattkrick mattkrick commented Jul 19, 2024

Description

moves QueryMap to PG

Summary by CodeRabbit

  • Refactor

    • Migrated database operations from RethinkDB to PostgreSQL for improved performance and scalability.
  • Chores

    • Introduced new database migration scripts to ensure seamless transition and data integrity during the switch to PostgreSQL.
  • Performance Improvements

    • Enhanced query retrieval and execution processes by utilising PostgreSQL, leading to faster and more reliable data access.

Copy link
Contributor

coderabbitai bot commented Jul 19, 2024

Walkthrough

This update transitions the database operations for query persistence and retrieval from RethinkDB to PostgreSQL. Key functions and classes now utilise PostgreSQL methods, and a new migration script has been introduced to handle the transition of the QueryMap table from RethinkDB to PostgreSQL. Various scripts and server files have been adjusted to reflect these changes, ensuring a smoother and more efficient database interaction.

Changes

Files/Paths Change Summary
packages/server/__tests__/common.ts Modified persistQuery function to switch from getRethink to getKysely and updated insertion syntax.
packages/server/database/rethinkDriver.ts Removed QueryMap from RethinkSchema and updated MeetingTemplate to include 'orgId' index.
packages/server/graphql/CompiledQueryCache.ts Switched from getRethink to getKysely for database operations in CompiledQueryCache class.
packages/server/graphql/DocumentCache.ts Changed query string retrieval to use getKysely instead of getRethink in DocumentCache class.
packages/server/postgres/migrations/... Added migration script to create and populate QueryMap table in PostgreSQL and handle rollback.
scripts/toolboxSrc/preDeploy.ts Updated storePersistedQueries to use getKysely for PostgreSQL operations and added cleanup call.
scripts/toolboxSrc/primeIntegrations.ts Removed getPg() and pg.end() calls, and streamlined integration process logging.

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

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • 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/schema.v2.json

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.

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: 9

Comment on lines +10 to +14
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper resource cleanup for PostgreSQL connection.

The PostgreSQL connection created by Kysely should be properly closed after the migration to avoid potential resource leaks.

-  const pg = new Kysely<any>({
-    dialect: new PostgresDialect({
-      pool: getPg()
-    })
-  })
+  const pg = new Kysely<any>({
+    dialect: new PostgresDialect({
+      pool: getPg()
+    })
+  })
+  try {
+    // Migration logic here
+  } finally {
+    await pg.destroy()
+  }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
const pg = new Kysely<any>({
dialect: new PostgresDialect({
pool: getPg()
})
})
try {
// Migration logic here
} finally {
await pg.destroy()
}

Comment on lines +22 to +26
const queries = await r
.table('QueryMap')
.filter((row) => row('createdAt').default(null).ne(null))
.run()
await pg.insertInto('QueryMap').values(queries).execute()
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for data migration.

Currently, there is no error handling for the data migration from RethinkDB to PostgreSQL. Consider wrapping the migration logic in a try-catch block to handle potential errors gracefully.

-  const queries = await r
-    .table('QueryMap')
-    .filter((row) => row('createdAt').default(null).ne(null))
-    .run()
-  await pg.insertInto('QueryMap').values(queries).execute()
+  try {
+    const queries = await r
+      .table('QueryMap')
+      .filter((row) => row('createdAt').default(null).ne(null))
+      .run()
+    await pg.insertInto('QueryMap').values(queries).execute()
+  } catch (error) {
+    console.error('Failed to migrate data from RethinkDB to PostgreSQL:', error)
+    throw error
+  }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const queries = await r
.table('QueryMap')
.filter((row) => row('createdAt').default(null).ne(null))
.run()
await pg.insertInto('QueryMap').values(queries).execute()
try {
const queries = await r
.table('QueryMap')
.filter((row) => row('createdAt').default(null).ne(null))
.run()
await pg.insertInto('QueryMap').values(queries).execute()
} catch (error) {
console.error('Failed to migrate data from RethinkDB to PostgreSQL:', error)
throw error
}

Comment on lines +30 to +35
const client = new Client(getPgConfig())
await client.connect()
await client.query(`
DROP TABLE "QueryMap";
` /* Do undo magic */)
await client.end()
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling and proper resource cleanup.

Currently, there is no error handling for the PostgreSQL connection and query execution. Additionally, ensure the client is properly closed in case of errors.

-  const client = new Client(getPgConfig())
-  await client.connect()
-  await client.query(`
-    DROP TABLE "QueryMap";
-    ` /* Do undo magic */)
-  await client.end()
+  const client = new Client(getPgConfig())
+  try {
+    await client.connect()
+    await client.query(`
+      DROP TABLE "QueryMap";
+      ` /* Do undo magic */)
+  } catch (error) {
+    console.error('Failed to drop table "QueryMap":', error)
+    throw error
+  } finally {
+    await client.end()
+  }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const client = new Client(getPgConfig())
await client.connect()
await client.query(`
DROP TABLE "QueryMap";
` /* Do undo magic */)
await client.end()
const client = new Client(getPgConfig())
try {
await client.connect()
await client.query(`
DROP TABLE "QueryMap";
` /* Do undo magic */)
} catch (error) {
console.error('Failed to drop table "QueryMap":', error)
throw error
} finally {
await client.end()
}

Comment on lines +15 to +21
await sql`
CREATE TABLE IF NOT EXISTS "QueryMap" (
"id" VARCHAR(24) PRIMARY KEY,
"query" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
`.execute(pg)
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve SQL execution for table creation.

Instead of using raw SQL, consider using Kysely's schema builder for better readability and maintainability.

-  await sql`
-    CREATE TABLE IF NOT EXISTS "QueryMap" (
-      "id" VARCHAR(24) PRIMARY KEY,
-      "query" TEXT NOT NULL,
-      "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
-    )
-  `.execute(pg)
+  await pg.schema
+    .createTable('QueryMap')
+    .ifNotExists()
+    .addColumn('id', 'varchar(24)', (col) => col.primaryKey())
+    .addColumn('query', 'text', (col) => col.notNull())
+    .addColumn('createdAt', 'timestamp', (col) => col.notNull().defaultTo(pg.fn.now()))
+    .execute()
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await sql`
CREATE TABLE IF NOT EXISTS "QueryMap" (
"id" VARCHAR(24) PRIMARY KEY,
"query" TEXT NOT NULL,
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
)
`.execute(pg)
await pg.schema
.createTable('QueryMap')
.ifNotExists()
.addColumn('id', 'varchar(24)', (col) => col.primaryKey())
.addColumn('query', 'text', (col) => col.notNull())
.addColumn('createdAt', 'timestamp', (col) => col.notNull().defaultTo(pg.fn.now()))
.execute()

import getPgConfig from '../getPgConfig'

export async function up() {
await connectRethinkDB()
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for RethinkDB connection.

Currently, there is no error handling for the RethinkDB connection. Consider wrapping the connection logic in a try-catch block to handle potential connection failures gracefully.

-  await connectRethinkDB()
+  try {
+    await connectRethinkDB()
+  } catch (error) {
+    console.error('Failed to connect to RethinkDB:', error)
+    throw error
+  }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await connectRethinkDB()
try {
await connectRethinkDB()
} catch (error) {
console.error('Failed to connect to RethinkDB:', error)
throw error
}

.select('query')
.where('id', '=', docId)
.executeTakeFirst()
let queryString = queryStringRes?.query
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure queryStringRes is defined before accessing its properties.

Add a check to ensure queryStringRes is defined before accessing its query property to avoid potential runtime errors.

-      let queryString = queryStringRes?.query
+      let queryString = queryStringRes ? queryStringRes.query : undefined
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let queryString = queryStringRes?.query
let queryString = queryStringRes ? queryStringRes.query : undefined

Comment on lines +19 to +24
const pg = getKysely()
const queryStringRes = await pg
.selectFrom('QueryMap')
.select('query')
.where('id', '=', docId)
.executeTakeFirst()
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for PostgreSQL query execution.

Currently, there is no error handling for the PostgreSQL query execution. Consider wrapping the query logic in a try-catch block to handle potential errors gracefully.

-      const pg = getKysely()
-      const queryStringRes = await pg
-        .selectFrom('QueryMap')
-        .select('query')
-        .where('id', '=', docId)
-        .executeTakeFirst()
+      const pg = getKysely()
+      let queryStringRes
+      try {
+        queryStringRes = await pg
+          .selectFrom('QueryMap')
+          .select('query')
+          .where('id', '=', docId)
+          .executeTakeFirst()
+      } catch (error) {
+        console.error('Failed to retrieve query string from PostgreSQL:', error)
+        throw error
+      }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const pg = getKysely()
const queryStringRes = await pg
.selectFrom('QueryMap')
.select('query')
.where('id', '=', docId)
.executeTakeFirst()
const pg = getKysely()
let queryStringRes
try {
queryStringRes = await pg
.selectFrom('QueryMap')
.select('query')
.where('id', '=', docId)
.executeTakeFirst()
} catch (error) {
console.error('Failed to retrieve query string from PostgreSQL:', error)
throw error
}

@@ -41,6 +37,7 @@ const preDeploy = async () => {

// The we can prime the DB & CDN
await Promise.all([storePersistedQueries(), primeIntegrations(), pushToCDN()])
await getKysely().destroy()
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper resource cleanup for PostgreSQL connection.

The PostgreSQL connection created by Kysely should be properly closed after the pre-deployment tasks to avoid potential resource leaks.

-  await getKysely().destroy()
+  try {
+    await getKysely().destroy()
+  } catch (error) {
+    console.error('Failed to destroy PostgreSQL connection:', error)
+    throw error
+  }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
await getKysely().destroy()
try {
await getKysely().destroy()
} catch (error) {
console.error('Failed to destroy PostgreSQL connection:', error)
throw error
}

Comment on lines +24 to +26
const pg = getKysely()
const res = await pg.insertInto('QueryMap').values(records).onConflict((oc) => oc.doNothing()).returning('id').execute()
console.log(`🔗 QueryMap Persistence Complete: ${res.length} records added`)
Copy link
Contributor

Choose a reason for hiding this comment

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

Add error handling for PostgreSQL query execution.

Currently, there is no error handling for the PostgreSQL query execution. Consider wrapping the query logic in a try-catch block to handle potential errors gracefully.

-  const pg = getKysely()
-  const res = await pg.insertInto('QueryMap').values(records).onConflict((oc) => oc.doNothing()).returning('id').execute()
-  console.log(`🔗 QueryMap Persistence Complete: ${res.length} records added`)
+  const pg = getKysely()
+  try {
+    const res = await pg.insertInto('QueryMap').values(records).onConflict((oc) => oc.doNothing()).returning('id').execute()
+    console.log(`🔗 QueryMap Persistence Complete: ${res.length} records added`)
+  } catch (error) {
+    console.error('Failed to persist queries to PostgreSQL:', error)
+    throw error
+  }
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const pg = getKysely()
const res = await pg.insertInto('QueryMap').values(records).onConflict((oc) => oc.doNothing()).returning('id').execute()
console.log(`🔗 QueryMap Persistence Complete: ${res.length} records added`)
const pg = getKysely()
try {
const res = await pg.insertInto('QueryMap').values(records).onConflict((oc) => oc.doNothing()).returning('id').execute()
console.log(`🔗 QueryMap Persistence Complete: ${res.length} records added`)
} catch (error) {
console.error('Failed to persist queries to PostgreSQL:', error)
throw error
}

@github-actions github-actions bot requested a review from tianrunhe July 19, 2024 01:04
@mattkrick mattkrick merged commit 28553e4 into master Jul 19, 2024
7 checks passed
@mattkrick mattkrick deleted the chore/QueryMap branch July 19, 2024 15:43
@github-actions github-actions bot mentioned this pull request Jul 19, 2024
24 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant