Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Consolidate metadata into a single column (#14414)

Damian Legawiec208c290f1eea
diff --git a/CLAUDE.md b/CLAUDE.md
index da347ced4e..6f7383839f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -204,7 +204,7 @@ end
- Target version: existing migrations keep their `ActiveRecord::Migration[7.2]` marker; new 6.0 migrations may target `[8.1]` — the 6.0 line requires Rails 8.1 (decisions.md 2026-07-29)
- No foreign key constraints
- No default values on string/status columns (statuses are set by the creating workflow); integer, decimal and boolean columns DO carry defaults (`quantity` 1, amounts 0) so raw inserts can't produce nulls
-- New tables get a single `metadata` JSON column — no `public_metadata`/`private_metadata` split (legacy tables keep theirs)
+- Every metadata-carrying table has a single `metadata` JSON column — the `public_metadata`/`private_metadata` split was consolidated in 6.0
- Always add `null: false` on required columns
- One migration per feature when possible
- Data transformations go in rake tasks, never in migrations
@@ -343,11 +343,11 @@ The Store API is a customer-facing surface. The Admin API is a back-office surfa
- Computed display values (`display_total`, `purchasable`, `in_stock`)
- Customer-facing pricing (`price`, `compare_at_price`, `prior_price` for EU Omnibus)
- **No timestamps** (`created_at`, `updated_at`, `deleted_at`) — these leak operational info and aren't useful to customers
-- **No internal state** — never expose `cost_price`, internal status flags, soft-delete columns, audit logs, internal notes, private metadata, or admin-only relations (vendors, fulfillment providers)
+- **No internal state** — never expose `cost_price`, internal status flags, soft-delete columns, audit logs, internal notes, `metadata`, or admin-only relations (vendors, fulfillment providers)
**Admin serializer (back-office):**
- Always include `created_at`, `updated_at`, and `deleted_at` (when paranoid)
-- Cost price, margins, internal notes, private metadata
+- Cost price, margins, internal notes, `metadata`
- Internal status, audit fields (`approved_by_id`, `cancelled_by_id`)
- Operational relations (stock movements, fulfillment providers, internal customer tags)
- Anything an admin needs to see but a customer must not
@@ -364,8 +364,8 @@ end
# Admin serializer — extends store, adds back-office attributes + timestamps
module Spree::Api::V3::Admin
class ProductSerializer < V3::ProductSerializer
- typelize cost_price: 'number | null', private_metadata: 'Record<string, unknown> | null'
- attributes :status, :cost_price, :private_metadata, :created_at, :updated_at, :deleted_at
+ typelize cost_price: 'number | null', metadata: 'Record<string, unknown> | null'
+ attributes :status, :cost_price, :metadata, :created_at, :updated_at, :deleted_at
end
end
```
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index bd3fb96bc0..71833a49c9 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,64 @@
+## 2026-08-09: Metadata consolidated to one column — `public_metadata` dropped, `private_metadata` renamed
+
+Implements the 2026-03-16 consolidation decision. All thirty metadata-carrying
+tables lose `public_metadata` and have `private_metadata` renamed to `metadata`,
+so the column, the accessor and the API field finally share one name.
+`Spree::Metadata` keeps its place but collapses to a single attribute plus the
+`HashSerializer` — the alias indirection that made `metadata` a method forwarding
+to another column is gone. `Spree::Collection`, which had been declaring its own
+consolidated column to sidestep the concern, now just includes it.
+
+**Three shape decisions.**
+
+*`public_metadata` data is preserved, not discarded.* The original note called the
+column unused, which holds for Spree's own code — nothing read it, and it was
+never exposed in the Store API — but is not provably true of host applications
+that had a writable JSON column sitting there for four years. A dropped column has
+no rollback, so `spree:upgrade:consolidate_metadata` merges it into
+`private_metadata` first, private winning on key collision since that is the side
+the accessor and the API always read.
+
+*The merge lives inside the migration, not in a manifest step.* The obvious home
+was a pre-migration upgrade task, but `spree:upgrade` runs manifests *after*
+`db:migrate` — both the rake runner and the CLI's upgrade command sequence it that
+way. A merge scheduled there would find `public_metadata` already dropped and
+silently do nothing, losing exactly the data it existed to protect. Documentation
+telling operators to run a step "before migrate" would have been asking them to
+fight their own tooling. `spree:upgrade:consolidate_metadata` stays in the manifest
+as a safety net for schemas changed out of band, not as the primary path.
+
+*The rename is `rename_column`, not add-and-backfill.* Instant on PostgreSQL and
+MySQL, data stays in place.
+
+*No hardcoded table lists, in either direction.* Legacy tables are discovered by
+column: the pair was added across a dozen migrations and several of those tables have
+since been renamed (`spree_shipping_methods`, `spree_prototypes`, `spree_taxons`), so
+a static list would already be wrong. Rollback needs the inverse answer, and shape
+cannot supply it — a table we renamed and one born with a single `metadata` column look
+identical afterwards. An early version hardcoded the exclusions and was doubly wrong:
+it missed `spree_customers`, and it would have swept up `active_storage_blobs`, whose
+unrelated `metadata` column a shape-based rollback would have renamed, breaking every
+attachment. `up` now records what it renames and `down` reverses exactly that.
+
+Both the migration and the task use raw SQL rather than Active Record. Beyond the
+models already pointing at the new name, PostgreSQL has no equality operator for
+`json`, so `where.not(public_metadata: [nil, {}])` raises `PG::UndefinedFunction` —
+green on SQLite, broken on the databases most production installs actually run.
+
+**No bridge for `public_metadata`** — a recorded exception to the "every 6.0 rename
+keeps the legacy name one release" convention. The column is being removed rather
+than renamed, and it already carried a deprecation warning through 5.x.
+`private_metadata` does get the usual one-release bridge with a warning.
+
+**What this does not change.** Metadata and metafields stay two systems. Metadata
+is the schemaless developer escape hatch — no definition, write-only from the
+Store API's perspective, for integration ids and sync state. Metafields (custom
+fields) stay merchant-defined structured data with types, definitions and
+storefront visibility. Customer-visible structured data belongs in a metafield,
+never in metadata.
+
+Plan: `docs/plans/6.0-consolidate-metadata-columns.md`.
+
## 2026-08-07: `Claim#claim_type` dropped — the reason vocabulary is the only "what went wrong" axis
Reverses the two-axis design in `6.0-returns-exchanges-claims.md`, which
@@ -926,6 +987,13 @@ Matches OSS platform C (`public: boolean`) and OSS platform B (`visibleInStorefr
Ships with the 6.0 model rename wave. See `5.4-6.0-custom-fields-rename.md`.
## 2026-03-16: Consolidate metadata — drop public_metadata, keep metadata JSON column
+
+> **Amended 2026-08-09 on one point:** `public_metadata` is **merged into
+> `metadata`, not discarded**. "Unused" holds for Spree's own code but is not
+> provably true of host applications, and a dropped column has no rollback. The
+> merge runs inside the migration. Everything else below stands — see the
+> 2026-08-09 entry at the top of this file.
+
Drop `public_metadata` column (never exposed in Store API, unused). Rename
`private_metadata` → `metadata` in the database. Simplify the `Spree::Metadata`
concern to a single `metadata` JSON column with no alias indirection.
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
index 3ca7268f77..fd891b0dd8 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb
@@ -218,7 +218,6 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do
expect(response).to have_http_status(:created)
expect(json_response).not_to have_key('metadata')
- expect(json_response).not_to have_key('private_metadata')
end
end
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb
index 9db75638bc..34969e856c 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/line_item_serializer_spec.rb
@@ -10,7 +10,7 @@ RSpec.describe Spree::Api::V3::Admin::LineItemSerializer do
describe 'metadata' do
context 'when line item has metadata' do
- before { line_item.update!(private_metadata: { 'gift_note' => 'Happy Birthday!', 'engraving' => 'J.D.' }) }
+ before { line_item.update!(metadata: { 'gift_note' => 'Happy Birthday!', 'engraving' => 'J.D.' }) }
it 'returns the metadata' do
expect(subject['metadata']).to eq({ 'gift_note' => 'Happy Birthday!', 'engraving' => 'J.D.' })
diff --git a/spree/api/spec/serializers/spree/api/v3/admin/order_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/admin/order_serializer_spec.rb
index c2cf4ea3dc..5d58a8450d 100644
--- a/spree/api/spec/serializers/spree/api/v3/admin/order_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/admin/order_serializer_spec.rb
@@ -9,7 +9,7 @@ RSpec.describe Spree::Api::V3::Admin::OrderSerializer do
describe 'metadata' do
context 'when order has metadata' do
- before { order.update!(private_metadata: { 'source' => 'mobile_app', 'campaign' => 'summer' }) }
+ before { order.update!(metadata: { 'source' => 'mobile_app', 'campaign' => 'summer' }) }
it 'returns the metadata' do
expect(subject['metadata']).to eq({ 'source' => 'mobile_app', 'campaign' => 'summer' })
@@ -27,7 +27,7 @@ RSpec.describe Spree::Api::V3::Admin::OrderSerializer do
let(:order) { create(:order_with_line_items, store: store) }
let(:base_params) { { store: store, currency: store.default_currency, expand: 'items' } }
- before { order.line_items.first.update!(private_metadata: { 'gift' => true }) }
+ before { order.line_items.first.update!(metadata: { 'gift' => true }) }
it 'uses admin line item serializer with metadata' do
line_item_data = subject['items'].first
diff --git a/spree/api/spec/serializers/spree/api/v3/line_item_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/line_item_serializer_spec.rb
index 36235262cf..a8ec5cfd0f 100644
--- a/spree/api/spec/serializers/spree/api/v3/line_item_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/line_item_serializer_spec.rb
@@ -91,9 +91,8 @@ RSpec.describe Spree::Api::V3::LineItemSerializer do
end
it 'does not expose metadata in Store API responses' do
- line_item.update!(private_metadata: { 'gift_note' => 'Happy Birthday!' })
+ line_item.update!(metadata: { 'gift_note' => 'Happy Birthday!' })
expect(subject).not_to have_key('metadata')
- expect(subject).not_to have_key('private_metadata')
end
describe 'compare_at_amount' do
diff --git a/spree/api/spec/serializers/spree/api/v3/payment_source_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/payment_source_serializer_spec.rb
index f25cbc9b9e..3649cf1c1a 100644
--- a/spree/api/spec/serializers/spree/api/v3/payment_source_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/payment_source_serializer_spec.rb
@@ -25,8 +25,7 @@ RSpec.describe Spree::Api::V3::PaymentSourceSerializer do
end
it 'does not expose metadata in Store API responses' do
- payment_source.update!(public_metadata: { 'email' => '[email protected]' })
- expect(subject).not_to have_key('public_metadata')
+ payment_source.update!(metadata: { 'email' => '[email protected]' })
expect(subject).not_to have_key('metadata')
end
end
diff --git a/spree/core/app/models/concerns/spree/metadata.rb b/spree/core/app/models/concerns/spree/metadata.rb
index 52456b84d3..0653e3652d 100644
--- a/spree/core/app/models/concerns/spree/metadata.rb
+++ b/spree/core/app/models/concerns/spree/metadata.rb
@@ -5,31 +5,26 @@ module Spree
include Spree::Metafields unless included_modules.include?(Spree::Metafields)
included do
- attribute :public_metadata, default: {}
- attribute :private_metadata, default: {}
+ attribute :metadata, default: {}
- serialize :public_metadata, coder: HashSerializer
- serialize :private_metadata, coder: HashSerializer
+ serialize :metadata, coder: HashSerializer
end
- # `metadata` is the primary API-facing accessor.
- # It maps to `private_metadata` under the hood (Stripe-style: write-only, never returned in Store API).
- def metadata
- private_metadata
+ # Deprecated alias for the renamed `metadata` column. Removed in Spree 6.1.
+ #
+ # Only the reader and writer are bridged. The column is gone, so the attribute
+ # methods Active Record generated alongside it — `private_metadata?`,
+ # `private_metadata_changed?`, `private_metadata_was`,
+ # `private_metadata_before_type_cast` and the rest of the dirty-tracking family
+ # — no longer exist and raise NoMethodError. Call the `metadata` equivalents.
+ def private_metadata
+ Spree::Deprecation.warn('private_metadata is deprecated and will be removed in Spree 6.1. Use metadata instead.')
+ metadata
end
- def metadata=(value)
- self.private_metadata = value
- end
-
- def public_metadata=(value)
- unless value.blank? || value == {}
- Spree::Deprecation.warn(
- 'public_metadata is deprecated and will be removed in Spree 6.0. ' \
- 'Use metadata instead. For customer-visible structured data, use metafields with display_on: \'both\'.'
- )
- end
- super
+ def private_metadata=(value)
+ Spree::Deprecation.warn('private_metadata= is deprecated and will be removed in Spree 6.1. Use metadata= instead.')
+ self.metadata = value
end
# https://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index 73c807a62f..ae5aa801a6 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -26,7 +26,7 @@ module Spree
# we're not freezing this on purpose so developers can extend and manage
# those attributes depending of the logic of their applications
ADDRESS_FIELDS = %w(firstname lastname company address1 address2 city state zipcode country phone)
- EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label customer_id public_metadata private_metadata)
+ EXCLUDED_KEYS_FOR_COMPARISON = %w(id updated_at created_at deleted_at label customer_id metadata)
if defined?(Spree::Security::Addresses)
include Spree::Security::Addresses
end
diff --git a/spree/core/app/models/spree/asset.rb b/spree/core/app/models/spree/asset.rb
index 1a7ef286c4..36e1829270 100644
--- a/spree/core/app/models/spree/asset.rb
+++ b/spree/core/app/models/spree/asset.rb
@@ -70,7 +70,7 @@ module Spree
# STI was disabled in Spree::Image, keep it disabled here
self.inheritance_column = nil
- store_accessor :private_metadata, :session_uploaded_assets_uuid
+ store_accessor :metadata, :session_uploaded_assets_uuid
scope :with_session_uploaded_assets_uuid, lambda { |uuid|
where(session_id: uuid)
}
diff --git a/spree/core/app/models/spree/collection.rb b/spree/core/app/models/spree/collection.rb
index cc9fd3ae50..6885d3b3bb 100644
--- a/spree/core/app/models/spree/collection.rb
+++ b/spree/core/app/models/spree/collection.rb
@@ -24,12 +24,7 @@ module Spree
include Spree::TranslatableResource
include Spree::TranslatableResourceSlug
- include Spree::Metafields
-
- # Single consolidated metadata JSON column (drops public_metadata; see
- # docs/plans/decisions.md 2026-03-16 "Consolidate metadata"). Write-only
- # developer escape hatch — never exposed in the Store API.
- attribute :metadata, default: -> { {} }
+ include Spree::Metadata
#
# Slug / permalink — FriendlyId with history (mirrors Spree::Category; flat, no hierarchy).
diff --git a/spree/core/app/models/spree/credit_card.rb b/spree/core/app/models/spree/credit_card.rb
index 636c9ed81b..27f5bb211c 100644
--- a/spree/core/app/models/spree/credit_card.rb
+++ b/spree/core/app/models/spree/credit_card.rb
@@ -69,7 +69,7 @@ module Spree
alias_attribute :brand, :cc_type
alias_attribute :last4, :last_digits
- store_accessor :private_metadata, :wallet
+ store_accessor :metadata, :wallet
# Returns the type of wallet the card is associated with, eg. "apple_pay", "google_pay", etc.
# @return [String]
diff --git a/spree/core/app/models/spree/order_promotion.rb b/spree/core/app/models/spree/order_promotion.rb
index 1caab7090f..d94d84a586 100644
--- a/spree/core/app/models/spree/order_promotion.rb
+++ b/spree/core/app/models/spree/order_promotion.rb
@@ -8,7 +8,7 @@ module Spree
belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :order_promotions
belongs_to :promotion, class_name: 'Spree::Promotion'
- delegate :name, :description, :code, :public_metadata, to: :promotion
+ delegate :name, :description, :code, to: :promotion
delegate :currency, to: :owner
validates :promotion, presence: true
diff --git a/spree/core/app/workflows/spree/carts/add_item.rb b/spree/core/app/workflows/spree/carts/add_item.rb
index 0bedfc3678..ef5072f555 100644
--- a/spree/core/app/workflows/spree/carts/add_item.rb
+++ b/spree/core/app/workflows/spree/carts/add_item.rb
@@ -10,14 +10,13 @@ module Spree
# @param cart [Spree::Cart, Spree::Order] draft orders ride the same pipeline
# @param variant [Spree::Variant]
# @param quantity [Integer, nil] defaults to 1
- # @param metadata [Hash] primary API param (maps to private metadata)
- def perform(variant:, cart: nil, order: nil, quantity: nil, metadata: {}, public_metadata: {}, private_metadata: {}, options: {})
+ # @param metadata [Hash] schemaless developer metadata stored on the line item
+ def perform(variant:, cart: nil, order: nil, quantity: nil, metadata: {}, options: {})
if order
Spree::Deprecation.warn('Calling Spree::Carts::AddItem with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')
cart ||= order
end
- super(cart: cart, variant: variant, quantity: quantity, metadata: metadata,
- public_metadata: public_metadata, private_metadata: private_metadata, options: options)
+ super(cart: cart, variant: variant, quantity: quantity, metadata: metadata, options: options)
# Veto point — purchase limits, B2B eligibility, per-group rules.
# Outside the transaction: nothing has been written yet, so a
@@ -62,11 +61,7 @@ module Spree
target = item_options[:fulfillment] || item_options[:shipment]
@line_item.target_fulfillment = target if target
- # `metadata` is the primary API param (maps to private_metadata).
- # Legacy `public_metadata`/`private_metadata` params kept for backward compatibility.
- resolved_metadata = metadata.presence || private_metadata
- @line_item.metadata = resolved_metadata.to_h if resolved_metadata.present?
- @line_item.public_metadata = public_metadata.to_h if public_metadata.present?
+ @line_item.metadata = metadata.to_h if metadata.present?
failure(@line_item) unless @line_item.save
diff --git a/spree/core/db/migrate/20260809120001_consolidate_metadata_columns.rb b/spree/core/db/migrate/20260809120001_consolidate_metadata_columns.rb
new file mode 100644
index 0000000000..383f2e2fca
--- /dev/null
+++ b/spree/core/db/migrate/20260809120001_consolidate_metadata_columns.rb
@@ -0,0 +1,120 @@
+class ConsolidateMetadataColumns < ActiveRecord::Migration[7.2]
+ # Records which tables this migration renamed, so `down` reverses exactly those.
+ # Dropped on the way back down.
+ CONSOLIDATED_TABLES_REGISTRY = :spree_consolidated_metadata_tables
+
+ # The merge lives here rather than in the upgrade rake task because the manifest
+ # runs AFTER db:migrate (see upgrade.rake and the CLI's upgrade command) — a
+ # merge step scheduled there would find public_metadata already dropped and
+ # silently lose whatever it held.
+ def up
+ tables = legacy_tables
+ return if tables.empty?
+
+ create_table CONSOLIDATED_TABLES_REGISTRY, if_not_exists: true do |t|
+ t.string :table_name, null: false
+ end
+
+ tables.each do |table_name|
+ merge_public_metadata_into_private(table_name)
+
+ rename_column table_name, :private_metadata, :metadata
+ remove_column table_name, :public_metadata
+
+ connection.exec_insert(
+ "INSERT INTO #{connection.quote_table_name(CONSOLIDATED_TABLES_REGISTRY)} (table_name) " \
+ "VALUES (#{connection.quote(table_name)})"
+ )
+ end
+ end
+
+ # Restores the column shape, NOT the original split of values. The merge is
+ # one-way: once public keys are folded into `metadata` there is no record of
+ # which side they came from, and keeping a shadow copy of a column being deleted
+ # would defeat the consolidation. Rolling back therefore returns every value
+ # under `private_metadata` and leaves `public_metadata` empty — code that reads
+ # the public side sees nothing.
+ #
+ # Set FORCE_METADATA_ROLLBACK=true to accept that and proceed.
+ def down
+ tables = consolidated_tables
+
+ if tables.any? && ENV['FORCE_METADATA_ROLLBACK'] != 'true'
+ raise ActiveRecord::IrreversibleMigration,
+ 'Rolling back would restore the public_metadata column empty: the merge into ' \
+ 'metadata is one-way and the original split is not recoverable. Re-run with ' \
+ 'FORCE_METADATA_ROLLBACK=true to restore the column shape and accept the loss.'
+ end
+
+ tables.each do |table_name|
+ rename_column table_name, :metadata, :private_metadata
+
+ change_table table_name do |t|
+ if t.respond_to?(:jsonb)
+ t.jsonb :public_metadata
+ else
+ t.json :public_metadata
+ end
+ end
+ end
+
+ drop_table CONSOLIDATED_TABLES_REGISTRY, if_exists: true
+ end
+
+ private
+
+ # Copies public_metadata into private_metadata, private winning on key collision
+ # since that is the side the `metadata` accessor and the API have always read.
+ # Row by row: merging two JSON documents in one UPDATE would need a different
+ # expression per adapter, and this runs once.
+ def merge_public_metadata_into_private(table_name)
+ quoted_table = connection.quote_table_name(table_name)
+ rows = connection.select_all(
+ "SELECT id, public_metadata, private_metadata FROM #{quoted_table} WHERE public_metadata IS NOT NULL"
+ )
+
+ rows.each do |row|
+ public_metadata = parse_json(row['public_metadata'])
+ next if public_metadata.blank?
+
+ merged = public_metadata.merge(parse_json(row['private_metadata']))
+
+ connection.exec_update(
+ "UPDATE #{quoted_table} SET private_metadata = #{connection.quote(merged.to_json)} " \
+ "WHERE id = #{connection.quote(row['id'])}"
+ )
+ end
+ end
+
+ # Anything that isn't a Hash — an array or scalar an application stored in the
+ # untyped column, unparseable text — becomes {} rather than aborting the migration.
+ def parse_json(value)
+ parsed = value.is_a?(String) ? (JSON.parse(value) rescue nil) : value
+
+ parsed.is_a?(Hash) ? parsed : {}
+ end
+
+ # Tables still carrying the legacy pair. The columns are the whole signal: a table
+ # born with a single `metadata` column has no `public_metadata`, so it can never
+ # match. A table that somehow has all three is skipped rather than guessed at —
+ # renaming onto an existing `metadata` would fail anyway.
+ def legacy_tables
+ connection.tables.select do |table_name|
+ column_exists?(table_name, :private_metadata) &&
+ column_exists?(table_name, :public_metadata) &&
+ !column_exists?(table_name, :metadata)
+ end
+ end
+
+ # Tables this migration consolidated, identified by the marker it wrote on the way
+ # up rather than by shape. Shape alone cannot distinguish a table we renamed from
+ # one that was born with a single `metadata` column — both end up with exactly that
+ # column — and reversing the latter would break models that have always read it.
+ def consolidated_tables
+ return [] unless connection.table_exists?(CONSOLIDATED_TABLES_REGISTRY)
+
+ connection.select_values(
+ "SELECT table_name FROM #{connection.quote_table_name(CONSOLIDATED_TABLES_REGISTRY)}"
+ ).select { |table_name| column_exists?(table_name, :metadata) }
+ end
+end
diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rb
index aef3593cba..b74d987bd3 100644
--- a/spree/core/lib/spree/permitted_attributes.rb
+++ b/spree/core/lib/spree/permitted_attributes.rb
@@ -276,7 +276,7 @@ module Spree
@@user_attributes = [:email, :bill_address_id, :ship_address_id, :password, :first_name, :last_name,
:password_confirmation, :selected_locale, :avatar, :accepts_email_marketing, :phone,
:internal_note,
- { public_metadata: {}, private_metadata: {}, tag_list: [], customer_group_ids: [] }]
+ { metadata: {}, tag_list: [], customer_group_ids: [] }]
@@variant_attributes = [
:name, :presentation, :cost_price, :discontinue_on, :lock_version,
diff --git a/spree/core/lib/spree/testing_support/metadata.rb b/spree/core/lib/spree/testing_support/metadata.rb
index 7383fe8d7a..259fd5117a 100644
--- a/spree/core/lib/spree/testing_support/metadata.rb
+++ b/spree/core/lib/spree/testing_support/metadata.rb
@@ -1,66 +1,68 @@
shared_examples_for 'metadata' do |factory: described_class.name.demodulize.underscore.to_sym|
subject { FactoryBot.create(factory) }
- it { expect(subject.has_attribute?(:public_metadata)).to be_truthy }
- it { expect(subject.has_attribute?(:private_metadata)).to be_truthy }
+ it { expect(subject.has_attribute?(:metadata)).to be_truthy }
- it { expect(subject.public_metadata).to eq({}) }
- it { expect(subject.private_metadata).to eq({}) }
+ it { expect(subject.metadata).to eq({}) }
- it { expect(subject.public_metadata.class).to eq(ActiveSupport::HashWithIndifferentAccess) }
- it { expect(subject.private_metadata.class).to eq(ActiveSupport::HashWithIndifferentAccess) }
+ it { expect(subject.metadata.class).to eq(ActiveSupport::HashWithIndifferentAccess) }
+
+ it 'no longer carries the split metadata columns' do
+ expect(subject.has_attribute?(:public_metadata)).to be_falsey
+ expect(subject.has_attribute?(:private_metadata)).to be_falsey
+ end
it 'reads data as symbolized keys' do
- string = subject.public_metadata[:color] = 'red'
- number = subject.public_metadata[:priority] = 1
- array = subject.public_metadata[:keywords] = ['k1', 'k2']
- hash = subject.public_metadata[:additional_data] = { size: 'big', material: 'wool' }
+ string = subject.metadata[:color] = 'red'
+ number = subject.metadata[:priority] = 1
+ array = subject.metadata[:keywords] = ['k1', 'k2']
+ hash = subject.metadata[:additional_data] = { size: 'big', material: 'wool' }
subject.save!
- expect(subject.public_metadata[:color]).to eq(string)
- expect(subject.public_metadata[:priority]).to eq(number)
- expect(subject.public_metadata[:keywords]).to eq(array)
- expect(subject.public_metadata[:additional_data]).to eq(hash.stringify_keys)
+ expect(subject.metadata[:color]).to eq(string)
+ expect(subject.metadata[:priority]).to eq(number)
+ expect(subject.metadata[:keywords]).to eq(array)
+ expect(subject.metadata[:additional_data]).to eq(hash.stringify_keys)
end
it 'reads data as not symbolized keys' do
- string = subject.public_metadata[:color] = 'red'
- number = subject.public_metadata[:priority] = 1
- array = subject.public_metadata[:keywords] = ['k1', 'k2']
- hash = subject.public_metadata[:additional_data] = { size: 'big', material: 'wool' }
+ string = subject.metadata[:color] = 'red'
+ number = subject.metadata[:priority] = 1
+ array = subject.metadata[:keywords] = ['k1', 'k2']
+ hash = subject.metadata[:additional_data] = { size: 'big', material: 'wool' }
subject.save!
- expect(subject.public_metadata['color']).to eq(string)
- expect(subject.public_metadata['priority']).to eq(number)
- expect(subject.public_metadata['keywords']).to eq(array)
- expect(subject.public_metadata['additional_data']).to eq(hash.stringify_keys)
+ expect(subject.metadata['color']).to eq(string)
+ expect(subject.metadata['priority']).to eq(number)
+ expect(subject.metadata['keywords']).to eq(array)
+ expect(subject.metadata['additional_data']).to eq(hash.stringify_keys)
end
it 'can query records by metadata properties', skip: (ENV['DB'].blank? || ENV['DB'] == 'mysql') do
- subject.public_metadata[:color] = 'red'
- subject.public_metadata[:priority] = 1
- subject.public_metadata[:keywords] = ['k1', 'k2']
- subject.public_metadata[:additional_data] = { size: 'big', material: 'wool' }
+ subject.metadata[:color] = 'red'
+ subject.metadata[:priority] = 1
+ subject.metadata[:keywords] = ['k1', 'k2']
+ subject.metadata[:additional_data] = { size: 'big', material: 'wool' }
subject.save!
- expect(described_class.where("public_metadata->>'color' = ?", 'red').count).to eq(1)
- expect(described_class.where("public_metadata->>'priority' = ?", '1').count).to eq(1)
- expect(described_class.where("public_metadata -> 'keywords' ? :keyword", keyword: 'k1').count).to eq(1)
- expect(described_class.where("public_metadata -> 'additional_data' ->> 'size' = :size", size: 'big').count).to eq(1)
+ expect(described_class.where("metadata->>'color' = ?", 'red').count).to eq(1)
+ expect(described_class.where("metadata->>'priority' = ?", '1').count).to eq(1)
+ expect(described_class.where("metadata -> 'keywords' ? :keyword", keyword: 'k1').count).to eq(1)
+ expect(described_class.where("metadata -> 'additional_data' ->> 'size' = :size", size: 'big').count).to eq(1)
end
it 'can query records by metadata properties', skip: ENV['DB'] == 'postgres' do
- subject.public_metadata[:color] = 'red'
- subject.public_metadata[:priority] = 1
- subject.public_metadata[:additional_data] = { size: 'big', material: 'wool' }
+ subject.metadata[:color] = 'red'
+ subject.metadata[:priority] = 1
+ subject.metadata[:additional_data] = { size: 'big', material: 'wool' }
subject.save!
- expect(described_class.where("JSON_EXTRACT(public_metadata, '$.color') = ?", 'red').count).to eq(1)
- expect(described_class.where("JSON_EXTRACT(public_metadata, '$.priority') = 1").count).to eq(1)
- expect(described_class.where("JSON_EXTRACT(public_metadata, '$.additional_data.size') = :size", size: 'big').count).to eq(1)
+ expect(described_class.where("JSON_EXTRACT(metadata, '$.color') = ?", 'red').count).to eq(1)
+ expect(described_class.where("JSON_EXTRACT(metadata, '$.priority') = 1").count).to eq(1)
+ expect(described_class.where("JSON_EXTRACT(metadata, '$.additional_data.size') = :size", size: 'big').count).to eq(1)
end
end
diff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
index 7d0c5c9592..0b6cb97d5e 100644
--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
@@ -20,6 +20,21 @@ to: "6.0"
docs: "https://spreecommerce.org/docs/developer/upgrades/5.6-to-6.0"
steps:
+ - id: consolidate_metadata
+ name: "Check for leftover split metadata columns"
+ task: "spree:upgrade:consolidate_metadata"
+ notes: |
+ Spree 6.0 collapses the public_metadata / private_metadata column pair into a
+ single metadata column. The migration performs the merge itself, before it
+ drops public_metadata, so a normal db:migrate needs nothing from this step.
+
+ This is a safety net for installs whose schema was changed out of band — a
+ manually dropped column, a half-applied migration, or an extension table that
+ adopted the same pair and was skipped. It reports and merges anything still
+ carrying both columns.
+
+ Idempotent, and a no-op on an already-consolidated schema.
+
- id: remove_master_variant
name: "Migrate products off the master variant"
task: "spree:remove_master_variant"
diff --git a/spree/core/lib/tasks/consolidate_metadata.rake b/spree/core/lib/tasks/consolidate_metadata.rake
new file mode 100644
index 0000000000..b9f938efae
--- /dev/null
+++ b/spree/core/lib/tasks/consolidate_metadata.rake
@@ -0,0 +1,73 @@
+module Spree
+ module MetadataConsolidator
+ # JSON columns come back as a Hash on some adapters and a String on others.
+ # Anything that isn't a Hash — an array or scalar an application stored in the
+ # untyped column, unparseable text — becomes {} rather than aborting the run.
+ def self.parse(value)
+ parsed = value.is_a?(String) ? (JSON.parse(value) rescue nil) : value
+
+ parsed.is_a?(Hash) ? parsed : {}
+ end
+ end
+end
+
+namespace :spree do
+ namespace :upgrade do
+ desc <<~DESC
+ Reports whether any table still carries the pre-6.0 public_metadata /
+ private_metadata pair, and merges public_metadata into private_metadata if so.
+
+ The 6.0 migration does this merge itself, before it drops the column, so a
+ normal `db:migrate` needs nothing from this task. It exists for installs whose
+ schema was changed out of band — a manually dropped column, a half-applied
+ migration, an extension table that adopted the pair and was missed.
+
+ Keys present in both columns keep the private value, matching the migration.
+ Idempotent, and a no-op on an already-consolidated schema.
+ DESC
+ task consolidate_metadata: :environment do
+ connection = ActiveRecord::Base.connection
+
+ tables = connection.tables.select do |table_name|
+ connection.column_exists?(table_name, :public_metadata) &&
+ connection.column_exists?(table_name, :private_metadata)
+ end
+
+ if tables.empty?
+ puts ' No table carries both metadata columns — nothing to do.'
+ next
+ end
+
+ merged_total = 0
+
+ tables.sort.each do |table_name|
+ quoted_table = connection.quote_table_name(table_name)
+ # Selected rather than filtered in SQL: PostgreSQL has no equality operator
+ # for `json`, so `WHERE public_metadata <> '{}'` is not portable.
+ rows = connection.select_all(
+ "SELECT id, public_metadata, private_metadata FROM #{quoted_table} WHERE public_metadata IS NOT NULL"
+ )
+
+ merged_for_table = 0
+
+ rows.each do |row|
+ public_metadata = Spree::MetadataConsolidator.parse(row['public_metadata'])
+ next if public_metadata.blank?
+
+ merged = public_metadata.merge(Spree::MetadataConsolidator.parse(row['private_metadata']))
+
+ connection.exec_update(
+ "UPDATE #{quoted_table} SET private_metadata = #{connection.quote(merged.to_json)} " \
+ "WHERE id = #{connection.quote(row['id'])}"
+ )
+ merged_for_table += 1
+ end
+
+ merged_total += merged_for_table
+ puts " #{table_name}: merged #{merged_for_table} row(s)." if merged_for_table.positive?
+ end
+
+ puts " Done. Merged #{merged_total} row(s) across #{tables.size} table(s) still carrying both columns."
+ end
+ end
+end
diff --git a/spree/core/lib/tasks/migrate_returns.rake b/spree/core/lib/tasks/migrate_returns.rake
index 7b864c51f1..5ad27ff4f3 100644
--- a/spree/core/lib/tasks/migrate_returns.rake
+++ b/spree/core/lib/tasks/migrate_returns.rake
@@ -79,10 +79,6 @@ module Spree
# Numberless rows are stamped with their legacy id at copy time, which is
# the only durable link back to the source row.
- #
- # Reads the `metadata` COLUMN, not `#metadata` — the Spree::Metadata
- # concern maps that reader to `private_metadata`, which these tables do
- # not have, so the accessor would silently return {}.
def migrated_numberless_ids
@migrated_numberless_ids ||=
(Spree::Return.where.not(metadata: nil).pluck(:metadata) +
diff --git a/spree/core/lib/tasks/typed_adjustments_migration.rake b/spree/core/lib/tasks/typed_adjustments_migration.rake
index c823c212ce..7d8f0e3e20 100644
--- a/spree/core/lib/tasks/typed_adjustments_migration.rake
+++ b/spree/core/lib/tasks/typed_adjustments_migration.rake
@@ -8,7 +8,7 @@
# and remains the rollback source.
# - Order totals are never touched; a per-order reconciliation asserts the
# typed sums match the order's stored totals. Orders that do not reconcile
-# are logged and marked recalculation-frozen (private_metadata flag), never
+# are logged and marked recalculation-frozen (metadata flag), never
# force-balanced.
# - Idempotent: orders with any typed rows already present are skipped.
namespace :spree do
@@ -104,7 +104,7 @@ namespace :spree do
if frozen_reason
order.update_columns(
- private_metadata: (order.private_metadata || {}).merge(
+ metadata: (order.metadata || {}).merge(
'typed_adjustments_frozen' => frozen_reason,
'typed_adjustments_frozen_at' => Time.current.iso8601
)
diff --git a/spree/core/spec/lib/tasks/consolidate_metadata_spec.rb b/spree/core/spec/lib/tasks/consolidate_metadata_spec.rb
new file mode 100644
index 0000000000..c76e76d731
--- /dev/null
+++ b/spree/core/spec/lib/tasks/consolidate_metadata_spec.rb
@@ -0,0 +1,222 @@
+require 'spec_helper'
+require 'rake'
+
+describe 'metadata consolidation' do
+ before(:all) do
+ Rake::Task.define_task(:environment)
+ load Spree::Core::Engine.root.join('lib', 'tasks', 'consolidate_metadata.rake')
+ end
+
+ let(:connection) { ActiveRecord::Base.connection }
+ let(:table_name) { 'spree_legacy_metadata_fixtures' }
+ let(:quoted_table) { connection.quote_table_name(table_name) }
+
+ # The real tables are consolidated by the migration, so both the migration's
+ # merge and the safety-net rake task are exercised against a synthetic table
+ # still carrying the pre-6.0 pair — the state an out-of-band install is in.
+ before do
+ connection.drop_table table_name, if_exists: true
+ connection.create_table table_name do |t|
+ if t.respond_to?(:jsonb)
+ t.jsonb :public_metadata
+ t.jsonb :private_metadata
+ else
+ t.json :public_metadata
+ t.json :private_metadata
+ end
+ end
+ end
+
+ after do
+ connection.drop_table table_name, if_exists: true
+ connection.drop_table :spree_consolidated_metadata_tables, if_exists: true
+ end
+
+ def insert_row(public_metadata:, private_metadata:)
+ connection.exec_insert(
+ "INSERT INTO #{quoted_table} (public_metadata, private_metadata) VALUES " \
+ "(#{connection.quote(public_metadata&.to_json)}, #{connection.quote(private_metadata&.to_json)})"
+ )
+ connection.select_values("SELECT id FROM #{quoted_table} ORDER BY id DESC").first
+ end
+
+ def merged_metadata_for(id)
+ value = connection.select_value(
+ "SELECT private_metadata FROM #{quoted_table} WHERE id = #{connection.quote(id)}"
+ )
+ Spree::MetadataConsolidator.parse(value)
+ end
+
+ shared_examples 'a metadata merge' do
+ it 'merges disjoint keys from both columns' do
+ id = insert_row(public_metadata: { 'pub' => 'p' }, private_metadata: { 'priv' => 'q' })
+
+ merge
+
+ expect(merged_metadata_for(id)).to eq('pub' => 'p', 'priv' => 'q')
+ end
+
+ it 'keeps the private value when a key exists in both columns' do
+ id = insert_row(public_metadata: { 'k' => 'public' }, private_metadata: { 'k' => 'private' })
+
+ merge
+
+ expect(merged_metadata_for(id)).to eq('k' => 'private')
+ end
+
+ it 'copies public metadata onto rows that have no private metadata' do
+ id = insert_row(public_metadata: { 'pub' => 'p' }, private_metadata: nil)
+
+ merge
+
+ expect(merged_metadata_for(id)).to eq('pub' => 'p')
+ end
+
+ it 'leaves rows with an empty or missing public metadata untouched' do
+ empty = insert_row(public_metadata: {}, private_metadata: { 'only' => 'private' })
+ missing = insert_row(public_metadata: nil, private_metadata: { 'only' => 'private' })
+
+ merge
+
+ expect(merged_metadata_for(empty)).to eq('only' => 'private')
+ expect(merged_metadata_for(missing)).to eq('only' => 'private')
+ end
+
+ it 'is idempotent' do
+ id = insert_row(public_metadata: { 'k' => 'public' }, private_metadata: { 'k' => 'private' })
+
+ merge
+ merge
+
+ expect(merged_metadata_for(id)).to eq('k' => 'private')
+ end
+
+ # The columns are untyped JSON, so an application could have stored an array or
+ # a scalar. Those are unusable as metadata but must not abort the run.
+ it 'discards non-hash values rather than failing' do
+ array_public = insert_row(public_metadata: %w[a b], private_metadata: { 'priv' => 'kept' })
+ scalar_public = insert_row(public_metadata: 42, private_metadata: { 'priv' => 'kept' })
+ array_private = insert_row(public_metadata: { 'pub' => 'kept' }, private_metadata: %w[a b])
+
+ expect { merge }.not_to raise_error
+
+ expect(merged_metadata_for(array_public)).to eq('priv' => 'kept')
+ expect(merged_metadata_for(scalar_public)).to eq('priv' => 'kept')
+ expect(merged_metadata_for(array_private)).to eq('pub' => 'kept')
+ end
+ end
+
+ # The path every upgrading install actually takes.
+ describe 'the migration' do
+ let(:migration) do
+ require Spree::Core::Engine.root.join('db', 'migrate', '20260809120001_consolidate_metadata_columns.rb')
+ ConsolidateMetadataColumns.new.tap { |m| m.verbose = false }
+ end
+
+ def merge
+ migration.send(:merge_public_metadata_into_private, table_name)
+ end
+
+ # Runs the real `up` against the fixture alone, so the registry it writes — the
+ # thing `down` reads — is populated for real rather than stubbed.
+ def consolidate_fixture
+ allow(migration).to receive(:legacy_tables).and_return([table_name])
+ migration.up
+ end
+
+ def with_rollback_override
+ allow(ENV).to receive(:[]).and_call_original
+ allow(ENV).to receive(:[]).with('FORCE_METADATA_ROLLBACK').and_return('true')
+ yield
+ end
+
+ it_behaves_like 'a metadata merge'
+
+ # These were born with a single `metadata` column. Nothing names them: they are
+ # excluded because they have no `public_metadata` to pair with, and because the
+ # migration never recorded renaming them.
+ it 'never touches tables that were born with a single metadata column' do
+ native_tables = %w[spree_collections spree_carts spree_returns spree_tax_lines spree_customers]
+
+ expect(migration.send(:legacy_tables)).not_to include(*native_tables)
+ expect(migration.send(:consolidated_tables)).not_to include(*native_tables)
+ end
+
+ # active_storage_blobs carries its own unrelated `metadata` column. Selecting
+ # rollback targets by shape would sweep it up and rename Rails' column, breaking
+ # every attachment; the registry can only ever name tables this migration renamed.
+ it 'never touches a non-Spree table that happens to have a metadata column' do
+ skip 'Active Storage not installed' unless connection.table_exists?(:active_storage_blobs)
+
+ expect(migration.send(:legacy_tables)).not_to include('active_storage_blobs')
+ expect(migration.send(:consolidated_tables)).not_to include('active_storage_blobs')
+ end
+
+ # The full `up` pass, not just the merge helper: the fixture table goes in
+ # carrying the legacy pair and comes out with one column holding merged values.
+ # Scoped to the fixture so the run doesn't consolidate the whole test schema.
+ it 'merges and consolidates the columns in one pass' do
+ id = insert_row(public_metadata: { 'pub' => 'kept', 'clash' => 'public' },
+ private_metadata: { 'clash' => 'private', 'priv' => 'kept' })
+
+ allow(migration).to receive(:legacy_tables).and_return([table_name])
+ migration.up
+
+ columns = connection.columns(table_name).map(&:name)
+ expect(columns).to include('metadata')
+ expect(columns).not_to include('public_metadata', 'private_metadata')
+
+ value = connection.select_value("SELECT metadata FROM #{quoted_table} WHERE id = #{connection.quote(id)}")
+ expect(Spree::MetadataConsolidator.parse(value)).to eq(
+ 'pub' => 'kept', 'priv' => 'kept', 'clash' => 'private'
+ )
+ end
+
+ it 'refuses to roll back without an explicit override' do
+ consolidate_fixture
+
+ expect { migration.down }.to raise_error(ActiveRecord::IrreversibleMigration, /not recoverable/)
+ expect(connection.columns(table_name).map(&:name)).to include('metadata')
+ end
+
+ it 'rolls back the column shape when the override is set' do
+ consolidate_fixture
+
+ with_rollback_override { migration.down }
+
+ columns = connection.columns(table_name).map(&:name)
+ expect(columns).to include('public_metadata', 'private_metadata')
+ expect(columns).not_to include('metadata')
+ end
+
+ # Rollback reverses only what `up` recorded, so a table the migration never
+ # touched keeps its single `metadata` column even under the override.
+ it 'leaves a table it never consolidated alone on rollback' do
+ consolidate_fixture
+ connection.create_table(:spree_native_metadata_fixtures) do |t|
+ t.respond_to?(:jsonb) ? t.jsonb(:metadata) : t.json(:metadata)
+ end
+
+ with_rollback_override { migration.down }
+
+ expect(connection.columns(:spree_native_metadata_fixtures).map(&:name)).to eq(%w[id metadata])
+ ensure
+ connection.drop_table(:spree_native_metadata_fixtures, if_exists: true)
+ end
+ end
+
+ # The safety net for schemas changed out of band.
+ describe 'the rake task' do
+ def merge
+ task = Rake::Task['spree:upgrade:consolidate_metadata']
+ task.reenable
+ original_stdout = $stdout.dup
+ $stdout.reopen(File::NULL, 'w')
+ task.invoke
+ ensure
+ $stdout.reopen(original_stdout)
+ end
+
+ it_behaves_like 'a metadata merge'
+ end
+end
diff --git a/spree/core/spec/lib/tasks/migrate_returns_spec.rb b/spree/core/spec/lib/tasks/migrate_returns_spec.rb
index 7d20a941c6..c24cfc94b3 100644
--- a/spree/core/spec/lib/tasks/migrate_returns_spec.rb
+++ b/spree/core/spec/lib/tasks/migrate_returns_spec.rb
@@ -169,8 +169,6 @@ RSpec.describe Spree::ReturnsMigrator do
it 'records the legacy id so the row can be recognised again' do
migrate
- # The column, not #metadata — that reader maps to private_metadata,
- # which spree_returns does not have.
stamped = Spree::Return.last.read_attribute(:metadata)
stamped = JSON.parse(stamped) unless stamped.is_a?(Hash)
expect(stamped['legacy_return_authorization_id']).to be_present
diff --git a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
index 712c61b17b..d30aef53b8 100644
--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb
@@ -184,7 +184,7 @@ describe '6.0 data migration tasks' do
expect(fee.kind).to eq('surcharge')
expect(order.reload.attributes.slice('total', 'discount_total', 'additional_tax_total')).to eq(totals_before)
- expect(order.private_metadata['typed_adjustments_frozen']).to be_nil
+ expect(order.metadata['typed_adjustments_frozen']).to be_nil
end
it 'freezes orders whose typed sums do not reconcile' do
@@ -195,7 +195,7 @@ describe '6.0 data migration tasks' do
run_task('spree:migrate_adjustments_to_typed_rows')
- expect(order.reload.private_metadata['typed_adjustments_frozen']).to eq('totals_do_not_reconcile')
+ expect(order.reload.metadata['typed_adjustments_frozen']).to eq('totals_do_not_reconcile')
end
it 'skips orders that already carry typed rows' do
diff --git a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb
index 0c519b88c5..b04b75d59b 100644
--- a/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb
+++ b/spree/core/spec/models/concerns/spree/purchase/addresses_spec.rb
@@ -224,7 +224,7 @@ RSpec.shared_examples 'an addresses host' do
firstname: 'New name',
**address.attributes.except(
'firstname', 'created_at', 'updated_at', 'deleted_at', 'quick_checkout',
- 'public_metadata', 'private_metadata', 'latitude', 'longitude', 'preferences'
+ 'metadata', 'latitude', 'longitude', 'preferences'
)
}
)
diff --git a/spree/core/spec/models/spree/base_spec.rb b/spree/core/spec/models/spree/base_spec.rb
index e9a0e3c4d7..f51abe7f07 100644
--- a/spree/core/spec/models/spree/base_spec.rb
+++ b/spree/core/spec/models/spree/base_spec.rb
@@ -99,11 +99,11 @@ describe Spree::Base do
expect(Spree.customer_class.json_api_columns).to include('email')
end
- it { expect(Spree::Address.json_api_columns).to contain_exactly('address1', 'address2', 'alternative_phone', 'city', 'company', 'created_at', 'deleted_at', 'firstname', 'label', 'lastname', 'phone', 'state_name', 'updated_at', 'zipcode', 'public_metadata', 'private_metadata', 'quick_checkout', 'latitude', 'longitude') }
+ it { expect(Spree::Address.json_api_columns).to contain_exactly('address1', 'address2', 'alternative_phone', 'city', 'company', 'created_at', 'deleted_at', 'firstname', 'label', 'lastname', 'phone', 'state_name', 'updated_at', 'zipcode', 'metadata', 'quick_checkout', 'latitude', 'longitude') }
it { expect(Spree::Address.json_api_columns).not_to include('country_id') }
end
describe '.json_api_permitted_attributes' do
- it { expect(Spree::Address.json_api_permitted_attributes).to contain_exactly('firstname', 'lastname', 'address1', 'address2', 'city', 'zipcode', 'phone', 'state_name', 'alternative_phone', 'company', 'state_id', 'country_id', 'created_at', 'updated_at', 'customer_id', 'deleted_at', 'label', 'public_metadata', 'private_metadata', 'quick_checkout', 'latitude', 'longitude') }
+ it { expect(Spree::Address.json_api_permitted_attributes).to contain_exactly('firstname', 'lastname', 'address1', 'address2', 'city', 'zipcode', 'phone', 'state_name', 'alternative_phone', 'company', 'state_id', 'country_id', 'created_at', 'updated_at', 'customer_id', 'deleted_at', 'label', 'metadata', 'quick_checkout', 'latitude', 'longitude') }
end
end
diff --git a/spree/core/spec/models/spree/concerns/metadata_spec.rb b/spree/core/spec/models/spree/concerns/metadata_spec.rb
index bbf79a48f2..32ca5ae800 100644
--- a/spree/core/spec/models/spree/concerns/metadata_spec.rb
+++ b/spree/core/spec/models/spree/concerns/metadata_spec.rb
@@ -4,16 +4,14 @@ RSpec.describe Spree::Metadata do
let(:product) { build(:product) }
describe '#metadata' do
- it 'reads from private_metadata' do
- product.private_metadata = { 'key' => 'value' }
- expect(product.metadata).to eq('key' => 'value')
+ it 'defaults to an empty hash' do
+ expect(product.metadata).to eq({})
end
- end
- describe '#metadata=' do
- it 'writes to private_metadata' do
+ it 'reads back with indifferent access' do
product.metadata = { 'key' => 'value' }
- expect(product.private_metadata).to eq('key' => 'value')
+ expect(product.metadata[:key]).to eq('value')
+ expect(product.metadata['key']).to eq('value')
end
end
@@ -24,4 +22,26 @@ RSpec.describe Spree::Metadata do
expect(product.metadata).to eq('a' => '1', 'b' => '2')
end
end
+
+ describe 'the private_metadata deprecation bridge' do
+ it 'reads through to metadata with a warning' do
+ product.metadata = { 'key' => 'value' }
+
+ expect(Spree::Deprecation).to receive(:warn).with(/private_metadata is deprecated/)
+ expect(product.private_metadata).to eq('key' => 'value')
+ end
+
+ it 'writes through to metadata with a warning' do
+ expect(Spree::Deprecation).to receive(:warn).with(/private_metadata= is deprecated/)
+ product.private_metadata = { 'key' => 'value' }
+
+ expect(product.metadata).to eq('key' => 'value')
+ end
+ end
+
+ describe 'public_metadata' do
+ it 'is gone' do
+ expect(product).not_to respond_to(:public_metadata)
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/credit_card_spec.rb b/spree/core/spec/models/spree/credit_card_spec.rb
index f5e78e3af4..49826eb3e3 100644
--- a/spree/core/spec/models/spree/credit_card_spec.rb
+++ b/spree/core/spec/models/spree/credit_card_spec.rb
@@ -480,7 +480,7 @@ describe Spree::CreditCard, type: :model do
end
describe '#wallet_type' do
- let(:credit_card) { build(:credit_card, private_metadata: metadata) }
+ let(:credit_card) { build(:credit_card, metadata: metadata) }
let(:metadata) { {} }
context 'when the wallet_type does not exist' do
diff --git a/spree/core/spec/services/spree/carts/upsert_items_spec.rb b/spree/core/spec/services/spree/carts/upsert_items_spec.rb
index f5e41977fd..cf7a21b918 100644
--- a/spree/core/spec/services/spree/carts/upsert_items_spec.rb
+++ b/spree/core/spec/services/spree/carts/upsert_items_spec.rb
@@ -93,7 +93,7 @@ module Spree
end
context 'merging metadata on existing line item' do
- let!(:existing_line_item) { create(:line_item, cart: cart, order: nil, variant: variant, quantity: 1, private_metadata: { 'existing' => 'val' }) }
+ let!(:existing_line_item) { create(:line_item, cart: cart, order: nil, variant: variant, quantity: 1, metadata: { 'existing' => 'val' }) }
let(:items) do
[{ variant_id: variant.prefixed_id, quantity: 2, metadata: { 'new_key' => 'new_val' } }]
diff --git a/spree/core/spec/services/spree/orders/upsert_items_spec.rb b/spree/core/spec/services/spree/orders/upsert_items_spec.rb
index ddf0282ce2..8f6b8e72dc 100644
--- a/spree/core/spec/services/spree/orders/upsert_items_spec.rb
+++ b/spree/core/spec/services/spree/orders/upsert_items_spec.rb
@@ -120,7 +120,7 @@ module Spree
end
context 'merging metadata on existing line item' do
- let!(:existing_line_item) { create(:line_item, order: order, variant: variant, quantity: 1, private_metadata: { 'existing' => 'val' }) }
+ let!(:existing_line_item) { create(:line_item, order: order, variant: variant, quantity: 1, metadata: { 'existing' => 'val' }) }
let(:items) do
[{ variant_id: variant.prefixed_id, quantity: 2, metadata: { 'new_key' => 'new_val' } }]
diff --git a/spree/core/spec/workflows/spree/carts/add_item_spec.rb b/spree/core/spec/workflows/spree/carts/add_item_spec.rb
index 6f0c0271b8..16457da387 100644
--- a/spree/core/spec/workflows/spree/carts/add_item_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/add_item_spec.rb
@@ -255,25 +255,6 @@ module Spree
expect(execute).to be_success
cart.reload
expect(cart.line_items.first.metadata).to eq metadata
- expect(cart.line_items.first.private_metadata).to eq metadata
- end
- end
-
- context 'via legacy public_metadata and private_metadata params' do
- let(:public_metadata) { { 'prop1' => 'value1' } }
- let(:private_metadata) { { 'prop2' => 'value2' } }
- let(:execute) { subject.call(cart: cart, variant: variant, quantity: qty, public_metadata: public_metadata, private_metadata: private_metadata) }
-
- it 'stores private_metadata' do
- expect(execute).to be_success
- cart.reload
- expect(cart.line_items.first.private_metadata).to eq private_metadata
- end
-
- it 'stores public_metadata' do
- expect(execute).to be_success
- cart.reload
- expect(cart.line_items.first.public_metadata).to eq public_metadata
end
end
end