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

Add Cast for JSON #265

Open
wants to merge 4 commits into
base: master
Choose a base branch
from

Conversation

matthewjumpsoffbuildings
Copy link
Contributor

@matthewjumpsoffbuildings matthewjumpsoffbuildings commented Feb 25, 2025

Added a custom Cast class to support handling JSON columns, updated readme to remove JSON from unsupported

I am not sure if this is still necessary but this is the approach I use to get JSON columns working smoothly

Summary by CodeRabbit

  • New Features

    • Introduced JSON column casting to enhance how the library handles JSON data types.
  • Documentation

    • Updated the documentation with a new section that provides clear guidance and examples for using the new JSON functionality.

Copy link

coderabbitai bot commented Feb 25, 2025

Walkthrough

The pull request introduces a new "JSON Type" section in the README to document handling JSON columns, including a code snippet that demonstrates casting JSON attributes using the SpannerJson class. Additionally, a new file is added under src/Casts/ which defines two classes, SpannerJson and SpannerJsonType, to manage JSON attribute casting and provide type annotations. The update also removes the previous note regarding unsupported JSON data types.

Changes

File Change Summary
README.md Added a new "JSON Type" section with documentation and a code snippet for casting JSON columns. Removed the outdated reference to unsupported JSON data.
src/Casts/SpannerJson.php Introduced new file defining SpannerJson for attribute casting and SpannerJsonType for providing type annotation functionality.

Suggested labels

enhancement, waiting for review

Suggested reviewers

  • Uyan712

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 PHPStan (2.0.3)

/bin/bash: line 1: /vendor/bin/phpstan: No such file or directory

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

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

@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)
src/Casts/SpannerJson.php (1)

22-28: Add class and method documentation.

Consider adding PHPDoc blocks to explain the purpose of the class and method.

+/**
+ * Custom JSON type for Google Cloud Spanner.
+ * Extends PgJsonb to provide JSON support with unspecified type annotation.
+ */
 class SpannerJsonType extends PgJsonb
 {
+    /**
+     * Returns the type annotation code for JSON values.
+     *
+     * @return int
+     */
     public function typeAnnotation()
     {
         return TypeAnnotationCode::TYPE_ANNOTATION_CODE_UNSPECIFIED;
     }
 }
README.md (1)

237-247: Enhance JSON Type documentation.

Consider adding more context about JSON type support:

  • Purpose and benefits of using JSON columns
  • Any limitations or performance considerations
  • Example of reading/writing JSON data
 ### JSON Type
 
-In order to use JSON columns, use the provided Cast on your model as below
+Google Cloud Spanner supports storing and querying JSON data. To work with JSON columns in your Laravel models, use the provided `SpannerJson` cast as shown below:
 
 ```php
 use Colopl\Spanner\Casts\SpannerJson;
 
 protected $casts = [
     'json_column_name' => SpannerJson::class,
 ]

+#### Example Usage
+
+php +// Writing JSON data +$model->json_column_name = ['key' => 'value']; + +// Reading JSON data +$data = $model->json_column_name; // Returns array +
+
+#### Limitations and Considerations
+
+- JSON columns are stored as strings in the database
+- Consider indexing specific JSON fields if you need to query them frequently
+- Large JSON objects may impact performance


<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 LanguageTool</summary>

[style] ~238-~238: Consider a shorter alternative to avoid wordiness.
Context: ...have these conversions.  ### JSON Type  In order to use JSON columns, use the provided Cast...

(IN_ORDER_TO_PREMIUM)

</details>
<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

237-237: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 03dbf66b58566989e1eb77c1546dc615eeb32e1d and f671a3db1e2610b7ec454878daaabdc128d8369b.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `README.md` (1 hunks)
* `src/Casts/SpannerJson.php` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 LanguageTool</summary>

<details>
<summary>README.md</summary>

[style] ~238-~238: Consider a shorter alternative to avoid wordiness.
Context: ...have these conversions.  ### JSON Type  In order to use JSON columns, use the provided Cast...

(IN_ORDER_TO_PREMIUM)

</details>

</details>
<details>
<summary>🪛 markdownlint-cli2 (0.17.2)</summary>

<details>
<summary>README.md</summary>

237-237: Heading style
Expected: setext; Actual: atx

(MD003, heading-style)

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (1)</summary>

* GitHub Check: Run-PHPUnit

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment on lines +11 to +14
public function get($model, $key, $value, $attributes)
{
return json_decode((string) $value, true);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for JSON decoding.

The get method should handle potential JSON decoding errors and null values explicitly.

 public function get($model, $key, $value, $attributes)
 {
-    return json_decode((string) $value, true);
+    if ($value === null) {
+        return null;
+    }
+    $decoded = json_decode((string) $value, true);
+    if (json_last_error() !== JSON_ERROR_NONE) {
+        throw new \JsonException(json_last_error_msg());
+    }
+    return $decoded;
 }
📝 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
public function get($model, $key, $value, $attributes)
{
return json_decode((string) $value, true);
}
public function get($model, $key, $value, $attributes)
{
if ($value === null) {
return null;
}
$decoded = json_decode((string) $value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \JsonException(json_last_error_msg());
}
return $decoded;
}

Comment on lines +16 to +19
public function set($model, $key, $value, $attributes)
{
return [$key => new SpannerJsonType($value)];
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for JSON values.

The set method should validate the input value to ensure it can be encoded as JSON.

 public function set($model, $key, $value, $attributes)
 {
+    if ($value !== null && !is_array($value) && !is_object($value)) {
+        throw new \InvalidArgumentException('The given value must be array, object or null.');
+    }
     return [$key => new SpannerJsonType($value)];
 }
📝 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
public function set($model, $key, $value, $attributes)
{
return [$key => new SpannerJsonType($value)];
}
public function set($model, $key, $value, $attributes)
{
if ($value !== null && !is_array($value) && !is_object($value)) {
throw new \InvalidArgumentException('The given value must be array, object or null.');
}
return [$key => new SpannerJsonType($value)];
}

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