Skip to content

init computed deployment variable value #516

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

jsbroks
Copy link
Member

@jsbroks jsbroks commented Apr 28, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced support for deployment variable values by distinguishing between direct values and references, allowing for more flexible configuration options.
  • Bug Fixes

    • Improved data validation to ensure consistency between variable value types and their associated fields.

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

Walkthrough

The schema for the deploymentVariableValue table was updated to support two distinct ways of storing variable values: direct values and references. This was accomplished by introducing a valueType column to indicate the mode, making the value column nullable, and adding new fields (reference and path) for reference types. A SQL check constraint was added to enforce that only the appropriate fields are set depending on the valueType, ensuring data consistency at the database level.

Changes

File(s) Change Summary
packages/db/src/schema/deployment-variables.ts Modified deploymentVariableValue schema: added valueType (default "direct"), made value nullable, added reference and path, and enforced a check constraint for field exclusivity based on valueType.

Poem

In the warren of tables, a change hops through,
Value types split—now two, not a few!
Direct or reference, the schema decides,
With checks and constraints, consistency abides.
The fields now align, as the rabbits decree,
Data’s more structured—oh, what glee! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

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

🧹 Nitpick comments (2)
packages/db/src/schema/deployment-variables.ts (2)

86-91: Strengthen the valid_value_type CHECK to forbid empty arrays and blank text.

Current predicate allows:

INSERT … (value_type='reference', reference='', path='{}');

Both reference = '' and path = '{}' are probably invalid.
Appending additional predicates keeps the intent tight:

-      (value_type = 'reference' AND value IS NULL AND reference IS NOT NULL AND path IS NOT NULL)
+      (value_type = 'reference'
+        AND value IS NULL
+        AND reference <> ''
+        AND path IS NOT NULL
+        AND cardinality(path) > 0)

Likewise you may want jsonb_typeof(value) IS NOT NULL when valueType='direct'.


78-79: JSONB unique index may cause performance & operator-class issues.

PostgreSQL requires a b-tree operator class for jsonb; without one the index will fail to create.
If uniqueness of raw JSON is really required, consider hashing:

CREATE UNIQUE INDEX … ON deployment_variable_value(variable_id, md5(value::text));

Drizzle: uniqueIndex().on(t.variableId, sqlmd5(${t.value}::text)).

If strict JSON equality is not essential, rethink the approach (see previous comment).

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 566766c and 6e48d48.

📒 Files selected for processing (1)
  • packages/db/src/schema/deployment-variables.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{ts,tsx}`: **Note on Error Handling:** Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error...

**/*.{ts,tsx}: Note on Error Handling:
Avoid strict enforcement of try/catch blocks. Code may use early returns, Promise chains (.then().catch()), or other patterns for error handling. These are acceptable as long as they maintain clarity and predictability.

  • packages/db/src/schema/deployment-variables.ts
🧬 Code Graph Analysis (1)
packages/db/src/schema/deployment-variables.ts (1)
packages/validators/src/resources/conditions/resource-condition.ts (1)
  • ResourceCondition (29-39)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Typecheck
  • GitHub Check: Lint
  • GitHub Check: build (linux/amd64)
  • GitHub Check: build (linux/amd64)

Comment on lines +63 to +64
valueType: text("value_type").notNull().default("direct"), // 'direct' | 'reference'

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider promoting valueType to a Postgres enum for stronger guarantees.

text("value_type") works, but misses out on type–level safety in the DB and allows silent typos ("diret" etc.).
Replacing it with a dedicated pgEnum("value_type", ["direct", "reference"]) (or re-using a shared enum) will:

  • eliminate invalid literals at the DB layer,
  • simplify the CHECK constraint,
  • improve schema self-documentation.

Diff sketch:

-import {
-  boolean,
-  foreignKey,
-  jsonb,
-  pgTable,
-  text,
-  uniqueIndex,
-  uuid,
-} from "drizzle-orm/pg-core";
+import {
+  boolean,
+  foreignKey,
+  jsonb,
+  pgTable,
+  pgEnum,
+  text,
+  uniqueIndex,
+  uuid,
+} from "drizzle-orm/pg-core";

+const valueTypeEnum = pgEnum("deployment_variable_value_type", [
+  "direct",
+  "reference",
+]);

...
-    valueType: text("value_type").notNull().default("direct"),
+    valueType: valueTypeEnum("value_type").notNull().default("direct"),

Comment on lines +69 to 76
// Direct value fields
value: jsonb("value").$type<any>(),
sensitive: boolean("sensitive").notNull().default(false),

// Reference fields
reference: text("reference"),
path: text("path").array(),
},
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

value / reference uniqueness coverage is incomplete

The existing unique index uniq is (variable_id, value).
For rows whose valueType = 'reference', value is always NULL, so all reference rows for the same variable can coexist with identical reference + path – probably unintended.

Recommend expanding the uniqueness criteria:

-    uniq: uniqueIndex().on(t.variableId, t.value),
+    uniq: uniqueIndex("deployment_variable_value_unique").on(
+      t.variableId,
+      sql`COALESCE(value, to_jsonb(reference || ':' || array_to_string(path, '.')))`,
+    ),

or (cleaner) create two partial unique indexes:

CREATE UNIQUE INDEX ... ON deployment_variable_value(variable_id, value)
  WHERE value_type = 'direct';

CREATE UNIQUE INDEX ... ON deployment_variable_value(variable_id, reference, path)
  WHERE value_type = 'reference';

Drizzle supports uniqueIndex().on(...).where(sql``) if you prefer all-TS.


🏁 Script executed:

#!/usr/bin/env bash
set -e

# Locate the deployment-variables.ts file
FILE=$(fd 'deployment-variables.ts$' -t f | head -n1)
echo "Found file: $FILE"
echo

# Display the first 200 lines to inspect schema and indexes
echo "=== File Content (lines 1-200) ==="
sed -n '1,200p' "$FILE"
echo

# Search for uniqueIndex definitions
echo "=== uniqueIndex occurrences ==="
grep -n "uniqueIndex" "$FILE" || true
echo

# Search for valueType column definition
echo "=== valueType occurrences ==="
grep -n "valueType" "$FILE" || true

Length of output: 6469


Ensure uniqueness for both direct and reference values

The current uniq index on deployment_variable_value(variable_id, value) only applies to rows where value_type = 'direct'. For reference-type rows (value_type = 'reference), value is always NULL, so multiple rows with the same (variable_id, reference, path) can slip through.

Apply two partial unique indexes:

• In packages/db/src/schema/deployment-variables.ts, update the table definition for deploymentVariableValue:

  (t) => ({
-   uniq: uniqueIndex().on(t.variableId, t.value),
+   // Unique for direct values only
+   directValueUniq: uniqueIndex('deployment_variable_value_value_unique')
+     .on(t.variableId, t.value)
+     .where(sql`value_type = 'direct'`),
+
+   // Unique for reference values only
+   referenceValueUniq: uniqueIndex('deployment_variable_value_reference_unique')
+     .on(t.variableId, t.reference, t.path)
+     .where(sql`value_type = 'reference'`),

    variableIdFk: foreignKey({ columns: [t.variableId], foreignColumns: [deploymentVariable.id] })
      .onUpdate("restrict")
      .onDelete("cascade"),

    check: sql`CONSTRAINT valid_value_type CHECK (
      (value_type = 'direct' AND value IS NOT NULL AND reference IS NULL AND path IS NULL) OR
      (value_type = 'reference' AND value IS NULL AND reference IS NOT NULL AND path IS NOT NULL)
    )`,
  }),

This enforces uniqueness separately for direct and reference entries.

📝 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
// Direct value fields
value: jsonb("value").$type<any>(),
sensitive: boolean("sensitive").notNull().default(false),
// Reference fields
reference: text("reference"),
path: text("path").array(),
},
// … earlier in deployment-variables.ts …
export const deploymentVariableValue = mysqlTable(
'deployment_variable_value',
{
id: serial('id').primaryKey(),
variableId: int('variable_id').notNull(),
valueType: text('value_type').notNull(),
// Direct value fields
value: jsonb('value').$type<any>(),
sensitive: boolean('sensitive').notNull().default(false),
// Reference fields
reference: text('reference'),
path: text('path').array(),
},
(t) => ({
// Unique for direct values only
directValueUniq: uniqueIndex('deployment_variable_value_value_unique')
.on(t.variableId, t.value)
.where(sql`value_type = 'direct'`),
// Unique for reference values only
referenceValueUniq: uniqueIndex('deployment_variable_value_reference_unique')
.on(t.variableId, t.reference, t.path)
.where(sql`value_type = 'reference'`),
variableIdFk: foreignKey({
columns: [t.variableId],
foreignColumns: [deploymentVariable.id],
})
.onUpdate('restrict')
.onDelete('cascade'),
check: sql`CONSTRAINT valid_value_type CHECK (
(value_type = 'direct' AND value IS NOT NULL AND reference IS NULL AND path IS NULL) OR
(value_type = 'reference' AND value IS NULL AND reference IS NOT NULL AND path IS NOT NULL)
)`,
}),
);

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.

1 participant