From 4f9a9a7f4ee65f3c5c895a282afdb5b02cbffd0c Mon Sep 17 00:00:00 2001 From: Pierre Merlin Date: Mon, 23 Nov 2026 17:46:04 +0100 Subject: [PATCH 1/2] ci: test against Couchbase Server 8.0 with couchstore buckets Couchbase Server 8.0 defaults new buckets to the Magma storage backend, which does not support Views. Pin couchstore in the CI bucket setup so the Views specs keep running, and add an 8.0.4 entry to the matrix. Refs BC-3548 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/test.yml | 3 +++ ci/run_couchbase.sh | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f3636ef..128db5a 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,6 +11,9 @@ jobs: strategy: matrix: include: + - ruby: '4.0' + active-model: '8.1.4' + couchbase: '8.0.4' - ruby: '4.0' active-model: '8.1.4' couchbase: '7.6.13' diff --git a/ci/run_couchbase.sh b/ci/run_couchbase.sh index c336bb4..55f2b82 100755 --- a/ci/run_couchbase.sh +++ b/ci/run_couchbase.sh @@ -27,7 +27,10 @@ sudo service couchbase-server status /opt/couchbase/bin/couchbase-cli cluster-init -c 127.0.0.1:8091 --cluster-username=admin --cluster-password=password --cluster-ramsize=320 --cluster-index-ramsize=256 --cluster-fts-ramsize=256 --services=data,index,query,fts sleep 5 /opt/couchbase/bin/couchbase-cli server-info -c 127.0.0.1:8091 -u admin -p password -/opt/couchbase/bin/couchbase-cli bucket-create -c 127.0.0.1:8091 -u admin -p password --bucket=$BUCKET --bucket-type=couchbase --bucket-ramsize=160 --bucket-replica=0 --wait +# Couchbase Server 8.0 made Magma the default storage backend, but Magma does +# not support Views (still exposed by CouchbaseOrm). Pin couchstore explicitly, +# which is also the pre-8.0 default. +/opt/couchbase/bin/couchbase-cli bucket-create -c 127.0.0.1:8091 -u admin -p password --bucket=$BUCKET --bucket-type=couchbase --storage-backend=couchstore --bucket-ramsize=160 --bucket-replica=0 --wait sleep 1 /opt/couchbase/bin/couchbase-cli user-manage -c 127.0.0.1:8091 -u admin -p password --set --rbac-username $USER --rbac-password $PASSWORD --rbac-name "Auto Tester" --roles admin --auth-domain local curl http://admin:password@localhost:8093/query/service -d "statement=CREATE INDEX \`default_type\` ON \`$BUCKET\`(\`type\`)" From 7804fc550c69fb61806d6171ead5ff7c108bf5ac Mon Sep 17 00:00:00 2001 From: Pierre Merlin Date: Mon, 23 Nov 2026 18:24:40 +0100 Subject: [PATCH 2/2] feat!: remove Couchbase Views support Couchbase Server 8.0 uses Magma as the default storage backend, and Magma buckets do not support Views (map/reduce design documents). BREAKING CHANGE: - remove CouchbaseOrm::Views (view, index_view, ensure_design_document!, include_docs) and the Rails ensure_design_documents initializer - remove BucketProxy#view - has_many now defaults to type: :n1ql; type: :view raises ArgumentError - join builds its by__id lookups with N1QL instead of Views The CI bucket keeps the server default storage backend (Magma on 8.0). Refs BC-3548 Co-Authored-By: Claude Opus 5.5 --- README.md | 64 +------ ci/run_couchbase.sh | 5 +- .../01-introduction.md | 6 +- .../tutorial-ruby-couchbase-orm/08-views.md | 158 ----------------- lib/couchbase-orm/base.rb | 2 - lib/couchbase-orm/proxies/bucket_proxy.rb | 9 - lib/couchbase-orm/railtie.rb | 14 -- lib/couchbase-orm/utilities/has_many.rb | 34 +--- lib/couchbase-orm/utilities/join.rb | 6 +- lib/couchbase-orm/views.rb | 161 ------------------ spec/has_many_spec.rb | 32 +--- spec/n1ql_spec.rb | 2 +- spec/proxies/bucket_proxy_spec.rb | 25 --- spec/type_spec.rb | 3 - spec/views_spec.rb | 94 ---------- 15 files changed, 24 insertions(+), 591 deletions(-) delete mode 100644 docusaurus/docs/tutorial-ruby-couchbase-orm/08-views.md delete mode 100644 lib/couchbase-orm/views.rb delete mode 100644 spec/views_spec.rb diff --git a/README.md b/README.md index 3a346b3..3a639d1 100644 --- a/README.md +++ b/README.md @@ -52,12 +52,6 @@ CouchbaseOrm::Connection.config = { } ``` -Views are generated on application load if they don't exist or mismatch. -This works fine in production however by default in development models are lazy loaded. - - # config/environments/development.rb - config.eager_load = true - ## Examples ```ruby @@ -148,51 +142,7 @@ context of rails application. You can also enforce types using ruby end ``` -## Views (aka Map/Reduce indexes) - -Views are defined in the model and typically just emit an attribute that -can then be used for filtering results or ordering. - -```ruby - class Comment < CouchbaseOrm::Base - attribute :author :string - attribute :body, :string - view :all # => emits :id and will return all comments - view :by_author, emit_key: :author - - # Generates two functions: - # * the by_author view above - # * def find_by_author(author); end - index_view :author - - # You can make compound keys by passing an array to :emit_key - # this allow to query by read/unread comments - view :by_read, emit_key: [:user_id, :read] - # this allow to query by view_count - view :by_view_count, emit_key: [:user_id, :view_count] - - validates_presence_of :author, :body - end -``` - -You can use `Comment.find_by_author('name')` to obtain all the comments by -a particular author. The same thing, using the view directly would be: -`Comment.by_author(key: 'name')` - -When using a compound key, the usage is the same, you just give the full key : - -```ruby - Comment.by_read(key: '["'+user_id+'",false]') # gives all unread comments for one particular user - - # or even a range ! - - Comment.by_view_count(startkey: '["'+user_id+'",10]', endkey: '["'+user_id+'",20]') - - # gives all comments that have been seen more than 10 times but less than 20 -``` -Check this couchbase help page to learn more on what's possible with compound keys : - -Ex : Compound keys allows to decide the order of the results, and you can reverse it by passing `descending: true` +## Ignored properties ```ruby class Comment < CouchbaseOrm::Base @@ -233,7 +183,10 @@ WARNING: If a document exists without a property, the query will failed! So you ## N1ql -Like views, it's possible to use N1QL to process some requests used for filtering results or ordering. +N1QL queries can be defined in the model to filter or order results. + +> Couchbase Views (map/reduce, `view` / `index_view` / `ensure_design_document!`) are no longer supported: +> Couchbase Server 8.0 uses the Magma storage backend by default, which does not support Views. Use N1QL instead. ```ruby class Comment < CouchbaseOrm::Base @@ -242,7 +195,7 @@ Like views, it's possible to use N1QL to process some requests used for filterin n1ql :by_author, emit_key: :author # Generates two functions: - # * the by_author view above + # * a by_author N1QL query # * def find_by_author(author); end index_n1ql :author @@ -346,8 +299,7 @@ There are common active record helpers available for use `belongs_to` and `has_m end ``` -By default, `has_many` uses a view for association, -but you can define a `type` option to specify an association using N1QL instead: +`has_many` associations are resolved with N1QL queries: ```ruby class Comment < CouchbaseOrm::Base @@ -355,7 +307,7 @@ but you can define a `type` option to specify an association using N1QL instead: end class Author < CouchbaseOrm::Base - has_many :comments, type: :n1ql, dependent: :destroy + has_many :comments, dependent: :destroy end ``` diff --git a/ci/run_couchbase.sh b/ci/run_couchbase.sh index 55f2b82..c336bb4 100755 --- a/ci/run_couchbase.sh +++ b/ci/run_couchbase.sh @@ -27,10 +27,7 @@ sudo service couchbase-server status /opt/couchbase/bin/couchbase-cli cluster-init -c 127.0.0.1:8091 --cluster-username=admin --cluster-password=password --cluster-ramsize=320 --cluster-index-ramsize=256 --cluster-fts-ramsize=256 --services=data,index,query,fts sleep 5 /opt/couchbase/bin/couchbase-cli server-info -c 127.0.0.1:8091 -u admin -p password -# Couchbase Server 8.0 made Magma the default storage backend, but Magma does -# not support Views (still exposed by CouchbaseOrm). Pin couchstore explicitly, -# which is also the pre-8.0 default. -/opt/couchbase/bin/couchbase-cli bucket-create -c 127.0.0.1:8091 -u admin -p password --bucket=$BUCKET --bucket-type=couchbase --storage-backend=couchstore --bucket-ramsize=160 --bucket-replica=0 --wait +/opt/couchbase/bin/couchbase-cli bucket-create -c 127.0.0.1:8091 -u admin -p password --bucket=$BUCKET --bucket-type=couchbase --bucket-ramsize=160 --bucket-replica=0 --wait sleep 1 /opt/couchbase/bin/couchbase-cli user-manage -c 127.0.0.1:8091 -u admin -p password --set --rbac-username $USER --rbac-password $PASSWORD --rbac-name "Auto Tester" --roles admin --auth-domain local curl http://admin:password@localhost:8093/query/service -d "statement=CREATE INDEX \`default_type\` ON \`$BUCKET\`(\`type\`)" diff --git a/docusaurus/docs/tutorial-ruby-couchbase-orm/01-introduction.md b/docusaurus/docs/tutorial-ruby-couchbase-orm/01-introduction.md index 1dd44bc..822a4c7 100644 --- a/docusaurus/docs/tutorial-ruby-couchbase-orm/01-introduction.md +++ b/docusaurus/docs/tutorial-ruby-couchbase-orm/01-introduction.md @@ -11,7 +11,7 @@ With Couchbase ORM, you can: - Define your data models and their relationships - Perform CRUD (Create, Read, Update, Delete) operations on your models - Query your data using a flexible and expressive query language -- Use Couchbase-specific features like N1QL queries and views +- Use Couchbase-specific features like N1QL queries - Implement advanced features such as data validation, callbacks, and associations Couchbase ORM abstracts away the low-level details of interacting with Couchbase Server, enabling you to focus on writing business logic and building great applications. @@ -36,9 +36,7 @@ Couchbase ORM offers a wide range of features to make working with Couchbase Ser 8. **N1QL Queries**: Execute N1QL queries directly from your Ruby code and map the results to your models. -9. **Views**: Create and query Couchbase views to efficiently retrieve data based on specific criteria. - -10. **Nested Documents**: Embed related documents within a parent document for denormalized data modeling. +9. **Nested Documents**: Embed related documents within a parent document for denormalized data modeling. These are just a few of the many features offered by Couchbase ORM. Throughout this documentation, we'll explore these features in-depth and provide examples of how to use them in your Ruby applications. diff --git a/docusaurus/docs/tutorial-ruby-couchbase-orm/08-views.md b/docusaurus/docs/tutorial-ruby-couchbase-orm/08-views.md deleted file mode 100644 index 14a913e..0000000 --- a/docusaurus/docs/tutorial-ruby-couchbase-orm/08-views.md +++ /dev/null @@ -1,158 +0,0 @@ -# Views (aka Map/Reduce indexes) - -Views are a powerful feature in Couchbase that allow you to define map functions to extract and emit specific data from your documents. The Ruby Couchbase ORM provides a convenient way to define and query views within your Ruby application. - -## 8.1 Defining Views - -To define a view in your Ruby Couchbase ORM model, you can use the `view` method followed by the view name and options. Here's an example: - -```ruby -class Factory < CouchbaseOrm::Base - attribute :name, type: String - attribute :location, type: String - attribute :established_year, type: Integer - attribute :active, type: Boolean - - view :by_name, emit_key: :name - view :by_location, emit_key: :location - view :by_established_year, emit_key: :established_year - view :by_active, emit_key: :active -end -``` - -In this example, we define four views for the `Factory` model: -- `by_name`: Emits the `name` attribute as the key. -- `by_location`: Emits the `location` attribute as the key. -- `by_established_year`: Emits the `established_year` attribute as the key. -- `by_active`: Emits the `active` attribute as the key. - -The `emit_key` option specifies the attribute to use as the key for the view. - -## 8.2 Custom Map Functions - -You can also define custom map functions for your views using the `map` option. This allows you to emit custom keys and values based on your specific requirements. Here's an example: - -```ruby -view :by_name_and_location, - map: %{ - function(doc) { - if (doc.type === "factory") { - emit([doc.name, doc.location], null); - } - } - } -``` - -In this example, we define a view named `by_name_and_location` that emits a composite key consisting of the `name` and `location` attributes. - -## 8.3 Querying Views - -Once you have defined your views, you can query them using the corresponding view methods. The view methods are automatically generated based on the view names. Here are some examples: - -```ruby -# Query factories by name -Factory.by_name(key: 'Factory A').each do |factory| - puts "- #{factory.name}" -end - -# Query factories by location -Factory.by_location(key: 'City X').each do |factory| - puts "- #{factory.name}" -end - -# Query factories by established year -Factory.by_established_year(key: 2010).each do |factory| - puts "- #{factory.name}" -end - -# Query active factories -Factory.by_active(key: true).each do |factory| - puts "- #{factory.name}" -end -``` - -These examples demonstrate how to query views based on specific keys using the generated view methods. - -## 8.4 Indexing Views - -In this section, let's explore the `index_view` function and the methods it generates for the `location` attribute. - -Here's an updated version of the `Factory` model using `index_view` for the `location` attribute: - -```ruby -class Factory < CouchbaseOrm::Base - attribute :name, type: String - attribute :location, type: String - attribute :established_year, type: Integer - attribute :active, type: Boolean - - view :by_name, emit_key: :name - index_view :location - view :by_established_year, emit_key: :established_year - view :by_active, emit_key: :active - - view :by_name_and_location, - map: %{ - function(doc) { - if (doc.type === "factory") { - emit([doc.name, doc.location], null); - } - } - } - - view :by_established_year_range, - map: %{ - function(doc) { - if (doc.type === "factory" && doc.established_year) { - emit(doc.established_year, null); - } - } - } -end -``` - -In this updated code, we replaced `view :by_location, emit_key: :location` with `index_view :location`. The `index_view` function generates two methods for querying based on the `location` attribute: - -1. `find_by_location(location)`: This method allows you to find factories by a specific location. It returns an array of factories that match the given location. - -2. `by_location(key: location)`: This method is similar to `find_by_location` but returns a `CouchbaseOrm::ResultsProxy` object, which provides an enumerable interface to access the view results. - -Now, let's see how we can use these generated methods to query factories by location: - -```ruby -# Find factories by location using find_by_location -factories = Factory.find_by_location('City X') -factories.each do |factory| - puts "- #{factory.name} (#{factory.location})" -end - -# Find factories by location using by_location -Factory.by_location(key: 'City X').each do |factory| - puts "- #{factory.name} (#{factory.location})" -end -``` - -Both `find_by_location` and `by_location` achieve the same result of finding factories by a specific location. The difference is that `find_by_location` returns an array of factories directly, while `by_location` returns a `CouchbaseOrm::ResultsProxy` object that you can further chain or iterate over. - -Using `index_view` provides a convenient way to generate commonly used query methods for a specific attribute. It simplifies the process of querying based on that attribute and enhances the readability of your code. - - - -## 8.5 Conclusion - -Views in the Ruby Couchbase ORM provide a powerful way to define and query data based on specific attributes and custom map functions. By defining views, you can easily retrieve subsets of your data and perform efficient queries based on your application's requirements. - -Remember to ensure that your design documents are up to date by calling `ensure_design_document!` on your models before running queries. - -With the flexibility and ease of use provided by the Ruby Couchbase ORM's view functionality, you can efficiently query and retrieve data from your Couchbase database. \ No newline at end of file diff --git a/lib/couchbase-orm/base.rb b/lib/couchbase-orm/base.rb index f2a148f..810ccd2 100644 --- a/lib/couchbase-orm/base.rb +++ b/lib/couchbase-orm/base.rb @@ -8,7 +8,6 @@ require 'couchbase-orm/changeable' require 'couchbase-orm/inspectable' require 'couchbase-orm/error' -require 'couchbase-orm/views' require 'couchbase-orm/n1ql' require 'couchbase-orm/persistence' require 'couchbase-orm/associations' @@ -126,7 +125,6 @@ class Base < Document include Persistence include Associations - include Views include QueryHelper include N1ql include Relation diff --git a/lib/couchbase-orm/proxies/bucket_proxy.rb b/lib/couchbase-orm/proxies/bucket_proxy.rb index df6cc64..05cb309 100644 --- a/lib/couchbase-orm/proxies/bucket_proxy.rb +++ b/lib/couchbase-orm/proxies/bucket_proxy.rb @@ -12,15 +12,6 @@ def initialize(proxyfied) self.class.define_method(:n1ql) do N1qlProxy.new(@proxyfied.n1ql) end - - self.class.define_method(:view) do |design, view, **opts, &block| - @results = nil if @current_query != "#{design}_#{view}" - @current_query = "#{design}_#{view}" - return @results if @results - - CouchbaseOrm.logger.debug "View - #{design} #{view}" - @results = ResultsProxy.new(@proxyfied.send(:view, design, view, **opts, &block)) - end end def method_missing(name, *args, **options, &block) diff --git a/lib/couchbase-orm/railtie.rb b/lib/couchbase-orm/railtie.rb index 4d6d570..81649da 100644 --- a/lib/couchbase-orm/railtie.rb +++ b/lib/couchbase-orm/railtie.rb @@ -24,7 +24,6 @@ module Rails #:nodoc: module Couchbase #:nodoc: class Railtie < Rails::Railtie #:nodoc: config.couchbase_orm = ActiveSupport::OrderedOptions.new - config.couchbase_orm.ensure_design_documents = true # Maping of rescued exceptions to HTTP responses # @@ -69,19 +68,6 @@ def self.rescue_responses end end end - - # Check (and upgrade if needed) all design documents - config.after_initialize do |app| - if config.couchbase_orm.ensure_design_documents - begin - ::CouchbaseOrm::Base.descendants.each do |model| - model.ensure_design_document! - end - rescue ::MTLibcouchbase::Error::Timedout, ::MTLibcouchbase::Error::ConnectError, ::MTLibcouchbase::Error::NetworkError - # skip connection errors for now - end - end - end end end end diff --git a/lib/couchbase-orm/utilities/has_many.rb b/lib/couchbase-orm/utilities/has_many.rb index 8777d8e..dbdaddc 100644 --- a/lib/couchbase-orm/utilities/has_many.rb +++ b/lib/couchbase-orm/utilities/has_many.rb @@ -1,7 +1,8 @@ module CouchbaseOrm module HasMany # :foreign_key, :class_name, :through - def has_many(model, class_name: nil, foreign_key: nil, through: nil, through_class: nil, through_key: nil, type: :view, **options) + def has_many(model, class_name: nil, foreign_key: nil, through: nil, through_class: nil, through_key: nil, type: :n1ql, **options) + raise ArgumentError, "has_many type: :view is no longer supported (Couchbase Views were removed), use type: :n1ql" if type == :view class_name = (class_name || model.to_s.singularize.camelcase).to_s foreign_key = (foreign_key || ActiveSupport::Inflector.foreign_key(self.name)).to_sym if through || through_class @@ -38,16 +39,7 @@ class #{class_name} < CouchbaseOrm::Base remote_klass = remote_class.constantize raise ArgumentError, "Can't find #{remote_method} without an id" unless self.id.present? - enum = klass.__send__(remote_method, key: self.id) { |row| - case type - when :n1ql - remote_klass.find(row) - when :view - remote_klass.find(row[through_key]) - else - raise 'type is unknown' - end - } + enum = klass.__send__(remote_method, key: self.id) { |row| remote_klass.find(row) } self.instance_variable_set(instance_var, enum) end @@ -66,31 +58,11 @@ def build_index(type, klass, remote_class, remote_method, through_key, foreign_k case type when :n1ql build_index_n1ql(klass, remote_class, remote_method, through_key, foreign_key) - when :view - build_index_view(klass, remote_class, remote_method, through_key, foreign_key) else raise 'type is unknown' end end - def build_index_view(klass, remote_class, remote_method, through_key, foreign_key) - if remote_class - klass.class_eval do - view remote_method, map: <<-EMAP - function(doc) { - if (doc.type === "{{design_document}}" && doc.#{through_key}) { - emit(doc.#{foreign_key}, null); - } - } - EMAP - end - else - klass.class_eval do - index_view foreign_key, validate: false - end - end - end - def build_index_n1ql(klass, remote_class, remote_method, through_key, foreign_key) if remote_class klass.class_eval do diff --git a/lib/couchbase-orm/utilities/join.rb b/lib/couchbase-orm/utilities/join.rb index 3dc74ec..559872b 100644 --- a/lib/couchbase-orm/utilities/join.rb +++ b/lib/couchbase-orm/utilities/join.rb @@ -23,7 +23,7 @@ def join(model_a, model_b, options={}) add_joint_lookups(model_b, model_a, true) # use Index to allow lookups of joint records more efficiently than - # with a view or search + # with a N1QL query index ["#{model_a}_id".to_sym, "#{model_b}_id".to_sym], :join end @@ -31,8 +31,8 @@ def add_single_sided_features(model) # belongs_to :group belongs_to model - # view :by_group_id - view "by_#{model}_id" + # n1ql :by_group_id, emit_key: :group_id + n1ql :"by_#{model}_id", emit_key: :"#{model}_id" # find_by_group_id instance_eval " diff --git a/lib/couchbase-orm/views.rb b/lib/couchbase-orm/views.rb deleted file mode 100644 index 2013508..0000000 --- a/lib/couchbase-orm/views.rb +++ /dev/null @@ -1,161 +0,0 @@ -# frozen_string_literal: true, encoding: ASCII-8BIT - -require 'active_model' - -module CouchbaseOrm - module Views - extend ActiveSupport::Concern - - - module ClassMethods - # Defines a view for the model - # - # @param [Symbol, String, Array] names names of the views - # @param [Hash] options options passed to the {Couchbase::View} - # - # @example Define some views for a model - # class Post < CouchbaseOrm::Base - # view :all - # view :by_rating, emit_key: :rating - # end - # - # Post.by_rating do |response| - # # ... - # end - def view(name, map: nil, emit_key: nil, reduce: nil, **options) - raise ArgumentError, "#{self} already respond_to? #{name}" if self.respond_to?(name) - - if emit_key.class == Array - emit_key.each do |key| - raise "unknown emit_key attribute for view :#{name}, emit_key: :#{key}" if key && !attribute_names.include?(key.to_s) - end - else - raise "unknown emit_key attribute for view :#{name}, emit_key: :#{emit_key}" if emit_key && !attribute_names.include?(emit_key.to_s) - end - - options = ViewDefaults.merge(options) - - method_opts = {} - method_opts[:map] = map if map - method_opts[:reduce] = reduce if reduce - - unless method_opts.has_key? :map - if emit_key.class == Array - method_opts[:map] = <<-EMAP -function(doc) { - if (doc.type === "{{design_document}}") { - emit([#{emit_key.map{|key| "doc."+key.to_s}.join(',')}], null); - } -} -EMAP - else - emit_key = emit_key || :created_at - method_opts[:map] = <<-EMAP -function(doc) { - if (doc.type === "{{design_document}}") { - emit(doc.#{emit_key}, null); - } -} -EMAP - end - end - - @views ||= {} - - name = name.to_sym - @views[name] = method_opts - - singleton_class.__send__(:define_method, name) do |**opts, &result_modifier| - opts = options.merge(opts).reverse_merge(scan_consistency: CouchbaseOrm::N1ql.config[:scan_consistency]) - CouchbaseOrm.logger.debug("View [#{@design_document}, #{name.inspect}] options: #{opts.inspect}") - if result_modifier - include_docs(bucket.view_query(@design_document, name.to_s, Couchbase::Options::View.new(**opts.except(:include_docs)))).map(&result_modifier) - elsif opts[:include_docs] - include_docs(bucket.view_query(@design_document, name.to_s, Couchbase::Options::View.new(**opts.except(:include_docs)))) - else - bucket.view_query(@design_document, name.to_s, Couchbase::Options::View.new(**opts.except(:include_docs))) - end - end - end - ViewDefaults = {include_docs: true} - - # add a view and lookup method to the model for finding all records - # using a value in the supplied attr. - def index_view(attr, validate: true, find_method: nil, view_method: nil) - view_method ||= "by_#{attr}" - find_method ||= "find_#{view_method}" - - validates(attr, presence: true) if validate - view view_method, emit_key: attr - - instance_eval " - def self.#{find_method}(#{attr}) - #{view_method}(key: #{attr}) - end - " - end - - def ensure_design_document! - return false unless @views && !@views.empty? - existing = {} - update_required = false - - # Grab the existing view details - begin - ddoc = bucket.view_indexes.get_design_document(@design_document, :production) - rescue Couchbase::Error::DesignDocumentNotFound - end - existing = ddoc.views if ddoc - views_actual = {} - # Fill in the design documents - @views.each do |name, document| - views_actual[name.to_s] = Couchbase::Management::View.new( - document[:map]&.gsub('{{design_document}}', @design_document), - document[:reduce]&.gsub('{{design_document}}', @design_document) - ) - end - - # Check there are no changes we need to apply - views_actual.each do |name, desired| - check = existing[name] - if check - cmap = (check.map || '').gsub(/\s+/, '') - creduce = (check.reduce || '').gsub(/\s+/, '') - dmap = (desired.map || '').gsub(/\s+/, '') - dreduce = (desired.reduce || '').gsub(/\s+/, '') - - unless cmap == dmap && creduce == dreduce - update_required = true - break - end - else - update_required = true - break - end - end - - # Updated the design document - if update_required - document = Couchbase::Management::DesignDocument.new - document.views = views_actual - document.name = @design_document - bucket.view_indexes.upsert_design_document(document, :production) - - true - else - false - end - end - - def include_docs(view_result) - if view_result.rows.length > 1 - self.find(view_result.rows.map(&:id)) - elsif view_result.rows.length == 1 - [self.find(view_result.rows.first.id)] - else - [] - end - end - end - end -end diff --git a/spec/has_many_spec.rb b/spec/has_many_spec.rb index 68dbc41..6c08232 100644 --- a/spec/has_many_spec.rb +++ b/spec/has_many_spec.rb @@ -9,10 +9,6 @@ @object_test_class = Kernel.const_get("Object#{@context.camelize}Test".classify) @object_rating_test_class = Kernel.const_get("ObjectRating#{@context.camelize}Test".classify) - @rating_test_class.ensure_design_document! - @object_test_class.ensure_design_document! - @object_rating_test_class.ensure_design_document! - @rating_test_class.delete_all @object_test_class.delete_all @object_rating_test_class.delete_all @@ -76,28 +72,12 @@ end describe CouchbaseOrm::HasMany do - context 'with view' do - class ObjectRatingViewTest < CouchbaseOrm::Base - join :object_view_test, :rating_view_test - view :view_all - end - - class RatingViewTest < CouchbaseOrm::Base - enum rating: [:awesome, :good, :okay, :bad], default: :okay - belongs_to :object_view_test - - has_many :object_view_tests, through: :object_rating_view_test - view :view_all - end - - class ObjectViewTest < CouchbaseOrm::Base - attribute :name, type: String - has_many :rating_view_tests, dependent: :destroy - - view :view_all - end - - include_examples("has_many example", context: :view) + it 'rejects the removed :view type' do + expect { + class HasManyRemovedViewTypeTest < CouchbaseOrm::Base + has_many :object_n1ql_tests, type: :view + end + }.to raise_error(ArgumentError, /no longer supported/) end context 'with n1ql' do diff --git a/spec/n1ql_spec.rb b/spec/n1ql_spec.rb index ca42599..7f182db 100644 --- a/spec/n1ql_spec.rb +++ b/spec/n1ql_spec.rb @@ -21,7 +21,7 @@ class N1QLTest < CouchbaseOrm::Base n1ql :by_rating_without_docs, emit_key: :rating, include_docs: false # This generates both: - # view :by_rating, emit_key: :rating + # n1ql :by_rating, emit_key: :rating # def self.find_by_rating(rating); end # also provide this helper function index_n1ql :rating end diff --git a/spec/proxies/bucket_proxy_spec.rb b/spec/proxies/bucket_proxy_spec.rb index a86f7fc..5080643 100644 --- a/spec/proxies/bucket_proxy_spec.rb +++ b/spec/proxies/bucket_proxy_spec.rb @@ -25,29 +25,4 @@ allow(proxyfied).to receive(:n1ql).and_return(:the_n1ql) expect(CouchbaseOrm::BucketProxy.new(proxyfied).n1ql).to be_a(CouchbaseOrm::N1qlProxy) end - - describe '#view' do - it 'wraps the result in a ResultsProxy and caches it for the same design/view' do - allow(proxyfied).to receive(:view).with('design', 'view').and_return([:row1, :row2]) - proxy = CouchbaseOrm::BucketProxy.new(proxyfied) - - first = proxy.view('design', 'view') - second = proxy.view('design', 'view') - - expect(first).to be_a(CouchbaseOrm::ResultsProxy) - expect(second).to be(first) - expect(proxyfied).to have_received(:view).once - end - - it 'requeries when the design/view pair changes' do - allow(proxyfied).to receive(:view).with('design', 'view').and_return([:row1]) - allow(proxyfied).to receive(:view).with('design', 'other').and_return([:row2]) - proxy = CouchbaseOrm::BucketProxy.new(proxyfied) - - proxy.view('design', 'view') - proxy.view('design', 'other') - - expect(proxyfied).to have_received(:view).twice - end - end end diff --git a/spec/type_spec.rb b/spec/type_spec.rb index e74cba2..668852b 100644 --- a/spec/type_spec.rb +++ b/spec/type_spec.rb @@ -58,9 +58,6 @@ class N1qlTypeTest < CouchbaseOrm::Base n1ql :by_both_dates, emit_key: [:renewal_date, :subscribed_at], presence: false end -TypeTest.ensure_design_document! -N1qlTypeTest.ensure_design_document! - describe CouchbaseOrm::Types::Timestamp do it "should cast an integer to time" do t = Time.at(Time.now.to_i) diff --git a/spec/views_spec.rb b/spec/views_spec.rb deleted file mode 100644 index 3ae3f86..0000000 --- a/spec/views_spec.rb +++ /dev/null @@ -1,94 +0,0 @@ -# frozen_string_literal: true, encoding: ASCII-8BIT - -require File.expand_path("../support", __FILE__) -require 'set' - -class ViewTest < CouchbaseOrm::Base - attribute :name, type: String - enum rating: [:awesome, :good, :okay, :bad], default: :okay - - view :vall - - # This generates both: - # view :by_rating, emit_key: :rating - # def self.find_by_rating(rating); end # also provide this helper function - index_view :rating -end - - -describe CouchbaseOrm::Views do - before(:each) do - ViewTest.delete_all - rescue Couchbase::Error::DesignDocumentNotFound - # ignore (FIXME: check before merge) mainly because if there is nothing in all we should not have an error - end - - after(:each) do - ViewTest.delete_all - rescue Couchbase::Error::InternalServerFailure - # ignore (FIXME: check before merge) - rescue Couchbase::Error::DesignDocumentNotFound - # ignore (FIXME: check before merge) (7.1) - end - - it "should not allow n1ql to override existing methods" do - expect { ViewTest.view :all }.to raise_error(ArgumentError) - end - - it "should save a new design document" do - begin - ViewTest.bucket.view_indexes.drop_design_document(ViewTest.design_document, :production) - rescue Couchbase::Error::InternalServerFailure - # ignore if design document does not exist - rescue Couchbase::Error::DesignDocumentNotFound - # ignore if design document does not exist (7.1) - end - expect(ViewTest.ensure_design_document!).to be(true) - end - - it "should not re-save a design doc if nothing has changed" do - expect(ViewTest.ensure_design_document!).to be(false) - end - - it "should return an empty array when there is no objects" do - expect(ViewTest.vall).to eq([]) - end - - it "should perform a map-reduce and return the view" do - ViewTest.ensure_design_document! - ViewTest.create! name: :bob, rating: :good - - docs = ViewTest.vall.collect { |ob| - ob.destroy - ob.name - } - expect(docs).to eq(['bob']) - end - - it "should work with other keys" do - ViewTest.ensure_design_document! - ViewTest.create! name: :bob, rating: :good - ViewTest.create! name: :jane, rating: :awesome - ViewTest.create! name: :greg, rating: :bad - - docs = ViewTest.by_rating(order: :descending).collect { |ob| - ob.destroy - ob.name - } - expect(docs).to eq(['greg', 'bob', 'jane']) - end - - it "should return matching results" do - ViewTest.ensure_design_document! - ViewTest.create! name: :bob, rating: :awesome - ViewTest.create! name: :jane, rating: :awesome - ViewTest.create! name: :greg, rating: :bad - ViewTest.create! name: :mel, rating: :good - - docs = ViewTest.find_by_rating(1).collect { |ob| - ob.name - } - - expect(Set.new(docs)).to eq(Set.new(['bob', 'jane'])) - end -end