split all adapter gems into their own repos.

This commit is contained in:
Micah Geisel 2020-01-30 16:19:26 -08:00 committed by Micah Geisel
parent bf0abcc146
commit 557cfb8660
269 changed files with 2 additions and 7541 deletions

13
Gemfile
View file

@ -1,15 +1,2 @@
gemspec
path "./adapters" do
gem "database_cleaner-active_record"
gem "database_cleaner-couch_potato"
gem "database_cleaner-data_mapper"
gem "database_cleaner-mongo"
gem "database_cleaner-mongoid"
gem "database_cleaner-mongo_mapper"
gem "database_cleaner-moped"
gem "database_cleaner-neo4j"
gem "database_cleaner-ohm"
gem "database_cleaner-redis"
gem "database_cleaner-sequel"
end

View file

@ -1,47 +1,7 @@
PATH
remote: .
specs:
database_cleaner (1.8.2)
PATH
remote: adapters
specs:
database_cleaner-active_record (1.8.0)
activerecord
database_cleaner (~> 1.8.0)
database_cleaner-couch_potato (1.8.0)
couch_potato
database_cleaner (~> 1.8.0)
database_cleaner-data_mapper (1.8.0)
database_cleaner (~> 1.8.0)
datamapper
dm-transactions
database_cleaner-mongo (1.8.0)
database_cleaner (~> 1.8.0)
mongo
database_cleaner-mongo_mapper (1.8.1)
database_cleaner (~> 1.8.0)
mongo_mapper
database_cleaner-mongoid (1.8.1)
database_cleaner (~> 1.8.0)
database_cleaner-mongo (~> 1.8.0)
mongoid
database_cleaner-moped (1.8.0)
database_cleaner (~> 1.8.0)
moped
database_cleaner-neo4j (1.8.0)
database_cleaner (~> 1.8.0)
neo4j-core
database_cleaner-ohm (1.8.1)
database_cleaner (~> 1.8.0)
database_cleaner-redis (~> 1.8.0)
ohm
database_cleaner-redis (1.8.0)
database_cleaner (~> 1.8.0)
redis
database_cleaner-sequel (1.8.0)
database_cleaner (~> 1.8.0)
sequel
database_cleaner (2.0.0.beta)
GEM
remote: https://rubygems.org/
@ -287,17 +247,6 @@ DEPENDENCIES
couch_potato
cucumber
database_cleaner!
database_cleaner-active_record!
database_cleaner-couch_potato!
database_cleaner-data_mapper!
database_cleaner-mongo!
database_cleaner-mongo_mapper!
database_cleaner-mongoid!
database_cleaner-moped!
database_cleaner-neo4j!
database_cleaner-ohm!
database_cleaner-redis!
database_cleaner-sequel!
datamapper
dm-migrations
dm-sqlite-adapter

View file

@ -18,16 +18,7 @@ end
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features)
desc "Run adapter test suites"
task :adapters do
Dir["adapters/*"].each do |adapter_dir|
Dir.chdir adapter_dir do
sh "bundle exec rake"
end
end
end
task :default => [:spec, :features, :adapters]
task :default => [:spec, :features]
desc "Cleans the project of any tmp file that should not be included in the gemspec."
task :clean do

View file

@ -1,13 +0,0 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/spec/support/config.yml
/tmp/
!/tmp/.keep
# rspec failure tracking
.rspec_status

View file

@ -1,3 +0,0 @@
--format documentation
--color
--require spec_helper

View file

@ -1,4 +0,0 @@
language: ruby
rvm:
- 2.2.9
before_install: gem install bundler -v 1.17.2

View file

@ -1,8 +0,0 @@
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# Specify your gem's dependencies in database_cleaner-active_record.gemspec
gemspec
gem "database_cleaner", path: "../.."

View file

@ -1,73 +0,0 @@
PATH
remote: ../..
specs:
database_cleaner (1.8.2)
PATH
remote: .
specs:
database_cleaner-active_record (1.8.0)
activerecord
database_cleaner (~> 1.8.0)
GEM
remote: https://rubygems.org/
specs:
activemodel (5.2.4.1)
activesupport (= 5.2.4.1)
activerecord (5.2.4.1)
activemodel (= 5.2.4.1)
activesupport (= 5.2.4.1)
arel (>= 9.0)
activerecord-mysql2-adapter (0.0.3)
mysql2
activesupport (5.2.4.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
arel (9.0.0)
concurrent-ruby (1.1.5)
diff-lcs (1.3)
i18n (1.5.1)
concurrent-ruby (~> 1.0)
minitest (5.14.0)
mysql (2.9.1)
mysql2 (0.3.18)
pg (0.18.2)
rake (10.4.2)
rspec (3.7.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-core (3.7.1)
rspec-support (~> 3.7.0)
rspec-expectations (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-mocks (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-support (3.7.1)
sqlite3 (1.3.10)
thread_safe (0.3.6)
tzinfo (1.2.6)
thread_safe (~> 0.1)
PLATFORMS
ruby
DEPENDENCIES
activerecord-mysql2-adapter
bundler (~> 1.16)
database_cleaner!
database_cleaner-active_record!
mysql (~> 2.9.1)
mysql2
pg
rake (~> 10.0)
rspec (~> 3.0)
sqlite3
BUNDLED WITH
1.17.3

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2009 Ben Mabey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,110 +0,0 @@
# Database Cleaner Adapter for ActiveRecord
[![Build Status](https://travis-ci.org/DatabaseCleaner/database_cleaner-active_record.svg?branch=master)](https://travis-ci.org/DatabaseCleaner/database_cleaner-active_record)
[![Code Climate](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-active_record/badges/gpa.svg)](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-active_record)
Clean your ActiveRecord databases with Database Cleaner.
See https://github.com/DatabaseCleaner/database_cleaner for more information.
## Installation
```ruby
# Gemfile
group :test do
gem 'database_cleaner-active_record'
end
```
## Supported Strategies
Here is an overview of the supported strategies:
<table>
<tbody>
<tr>
<th>Truncation</th>
<th>Transaction</th>
<th>Deletion</th>
</tr>
<tr>
<td> Yes</td>
<td> <b>Yes</b></td>
<td> Yes</td>
</tr>
</tbody>
</table>
(Default strategy is denoted in bold)
For support or to discuss development please use the [Google Group](https://groups.google.com/group/database_cleaner).
## What strategy is fastest?
For the SQL libraries the fastest option will be to use `:transaction` as transactions are simply rolled back. If you can use this strategy you should. However, if you wind up needing to use multiple database connections in your tests (i.e. your tests run in a different process than your application) then using this strategy becomes a bit more difficult. You can get around the problem a number of ways.
One common approach is to force all processes to use the same database connection ([common ActiveRecord hack](http://blog.plataformatec.com.br/2011/12/three-tips-to-improve-the-performance-of-your-test-suite/)) however this approach has been reported to result in non-deterministic failures.
Another approach is to have the transactions rolled back in the application's process and relax the isolation level of the database (so the tests can read the uncommitted transactions).
An easier, but slower, solution is to use the `:truncation` or `:deletion` strategy.
So what is fastest out of `:deletion` and `:truncation`? Well, it depends on your table structure and what percentage of tables you populate in an average test. The reasoning is out of the scope of this README but here is a [good SO answer on this topic for Postgres](https://stackoverflow.com/questions/11419536/postgresql-truncation-speed/11423886#11423886).
Some people report much faster speeds with `:deletion` while others say `:truncation` is faster for them. The best approach therefore is it try all options on your test suite and see what is faster.
If you are using ActiveRecord then take a look at the [additional options](#additional-activerecord-options-for-truncation) available for `:truncation`.
## Configuration options
<table>
<tbody>
<tr>
<th>ORM</th>
<th>How to access</th>
<th>Notes</th>
</tr>
<tr>
<td> Active Record </td>
<td> <code>DatabaseCleaner[:active_record]</code></td>
<td> Connection specified as <code>:symbol</code> keys, loaded from <code>config/database.yml</code>. You may also pass in the ActiveRecord model under the <code>:model</code> key.</td>
</tr>
</tbody>
</table>
### Additional ActiveRecord options for Truncation
The following options are available for ActiveRecord's `:truncation` strategy _only_ for MySQL and Postgres.
* `:pre_count` - When set to `true` this will check each table for existing rows before truncating it. This can speed up test suites when many of the tables to be truncated are never populated. Defaults to `:false`. (Also, see the section on [What strategy is fastest?](#what-strategy-is-fastest))
* `:reset_ids` - This only matters when `:pre_count` is used, and it will make sure that a tables auto-incrementing id is reset even if there are no rows in the table (e.g. records were created in the test but also removed before DatabaseCleaner gets to it). Defaults to `true`.
The following option is available for ActiveRecord's `:truncation` and `:deletion` strategy for any DB.
* `:cache_tables` - When set to `true` the list of tables to truncate or delete from will only be read from the DB once, otherwise it will be read before each cleanup run. Set this to `false` if (1) you create and drop tables in your tests, or (2) you change Postgres schemas (`ActiveRecord::Base.connection.schema_search_path`) in your tests (for example, in a multitenancy setup with each tenant in a different Postgres schema). Defaults to `true`.
## Common Errors
### STDERR is being flooded when using Postgres
If you are using Postgres and have foreign key constraints, the truncation strategy will cause a lot of extra noise to appear on STDERR (in the form of "NOTICE truncate cascades" messages).
To silence these warnings set the following log level in your `postgresql.conf` file:
```ruby
client_min_messages = warning
```
For ActiveRecord, you add the following parameter in your database.yml file:
<pre>
test:
adapter: postgresql
# ...
min_messages: WARNING
</pre>
## COPYRIGHT
See [LICENSE] for details.

View file

@ -1,6 +0,0 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
task :default => :spec

View file

@ -1,14 +0,0 @@
#!/usr/bin/env ruby
require "bundler/setup"
require "database_cleaner/active_record"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start
require "irb"
IRB.start(__FILE__)

View file

@ -1,8 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle check || bundle install
cp spec/support/sample.config.yml spec/support/config.yml

View file

@ -1,40 +0,0 @@
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "database_cleaner/active_record/version"
Gem::Specification.new do |spec|
spec.name = "database_cleaner-active_record"
spec.version = DatabaseCleaner::ActiveRecord::VERSION
spec.authors = ["Ernesto Tagwerker"]
spec.email = ["ernesto@ombulabs.com"]
spec.summary = "Strategies for cleaning databases using ActiveRecord. Can be used to ensure a clean state for testing."
spec.description = "Strategies for cleaning databases using ActiveRecord. Can be used to ensure a clean state for testing."
spec.homepage = "https://github.com/DatabaseCleaner/database_cleaner-active_record"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "database_cleaner", "~> 1.8.0"
spec.add_dependency "activerecord"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rspec", "~> 3.0"
unless RUBY_PLATFORM =~ /java/
spec.add_development_dependency 'mysql', '~> 2.9.1'
spec.add_development_dependency 'mysql2'
spec.add_development_dependency "activerecord-mysql2-adapter"
spec.add_development_dependency 'pg'
spec.add_development_dependency "sqlite3"
else
spec.add_development_dependency "activerecord-jdbc-adapter"
end
end

View file

@ -1 +0,0 @@
require "database_cleaner/active_record"

View file

@ -1,6 +0,0 @@
require 'database_cleaner/active_record/version'
require 'database_cleaner'
require 'database_cleaner/active_record/deletion'
require 'database_cleaner/active_record/transaction'
require 'database_cleaner/active_record/truncation'

View file

@ -1,101 +0,0 @@
require 'active_record'
require 'database_cleaner/generic/base'
require 'erb'
require 'yaml'
module DatabaseCleaner
module ActiveRecord
def self.available_strategies
%w[truncation transaction deletion]
end
def self.default_strategy
:transaction
end
def self.config_file_location=(path)
@config_file_location = path
end
def self.config_file_location
@config_file_location ||= begin
# Has DC.app_root been set? Check in this intrusive way to avoid triggering deprecation warnings if it hasn't.
app_root = DatabaseCleaner.send(:configuration).instance_variable_get(:@app_root)
root = app_root || Dir.pwd
"#{root}/config/database.yml"
end
end
module Base
include ::DatabaseCleaner::Generic::Base
attr_accessor :connection_hash
def db=(desired_db)
@db = desired_db
load_config
end
def db
@db ||= super
end
def load_config
if self.db != :default && self.db.is_a?(Symbol) && File.file?(ActiveRecord.config_file_location)
connection_details = YAML::load(ERB.new(IO.read(ActiveRecord.config_file_location)).result)
@connection_hash = valid_config(connection_details)[self.db.to_s]
end
end
def valid_config(connection_file)
if !::ActiveRecord::Base.configurations.nil? && !::ActiveRecord::Base.configurations.empty?
if connection_file != ::ActiveRecord::Base.configurations
return ::ActiveRecord::Base.configurations
end
end
connection_file
end
def connection_class
@connection_class ||= if db && !db.is_a?(Symbol)
db
elsif connection_hash
lookup_from_connection_pool || establish_connection
else
::ActiveRecord::Base
end
end
def self.migration_table_name
if ::ActiveRecord::VERSION::MAJOR < 5
::ActiveRecord::Migrator.schema_migrations_table_name
else
::ActiveRecord::SchemaMigration.table_name
end
end
def self.exclusion_condition(column_name)
result = " #{column_name} <> '#{::DatabaseCleaner::ActiveRecord::Base.migration_table_name}' "
if ::ActiveRecord::VERSION::MAJOR >= 5
result += " AND #{column_name} <> '#{::ActiveRecord::Base.internal_metadata_table_name}' "
end
result
end
private
def lookup_from_connection_pool
if ::ActiveRecord::Base.respond_to?(:descendants)
database_name = connection_hash["database"] || connection_hash[:database]
models = ::ActiveRecord::Base.descendants
models.select(&:connection_pool).detect { |m| m.connection_pool.spec.config[:database] == database_name }
end
end
def establish_connection
::ActiveRecord::Base.establish_connection(connection_hash)
::ActiveRecord::Base
end
end
end
end

View file

@ -1,108 +0,0 @@
require 'active_record'
require 'active_record/connection_adapters/abstract_adapter'
require "database_cleaner/generic/truncation"
require 'database_cleaner/active_record/truncation'
module DatabaseCleaner
module ConnectionAdapters
module AbstractDeleteAdapter
def delete_table(table_name)
raise NotImplementedError
end
end
module GenericDeleteAdapter
def delete_table(table_name)
execute("DELETE FROM #{quote_table_name(table_name)};")
end
end
module OracleDeleteAdapter
def delete_table(table_name)
execute("DELETE FROM #{quote_table_name(table_name)}")
end
end
end
end
module ActiveRecord
module ConnectionAdapters
AbstractAdapter.class_eval { include DatabaseCleaner::ConnectionAdapters::AbstractDeleteAdapter }
JdbcAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(JdbcAdapter)
AbstractMysqlAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(AbstractMysqlAdapter)
Mysql2Adapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(Mysql2Adapter)
SQLiteAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(SQLiteAdapter)
SQLite3Adapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(SQLite3Adapter)
PostgreSQLAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(PostgreSQLAdapter)
IBM_DBAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(IBM_DBAdapter)
SQLServerAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::GenericDeleteAdapter } if defined?(SQLServerAdapter)
OracleEnhancedAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::OracleDeleteAdapter } if defined?(OracleEnhancedAdapter)
end
end
module DatabaseCleaner::ActiveRecord
module SelectiveTruncation
def tables_to_truncate(connection)
if information_schema_exists?(connection)
(@only || tables_with_new_rows(connection)) - @tables_to_exclude
else
super
end
end
def tables_with_new_rows(connection)
stats = table_stats_query(connection)
if stats != ''
connection.select_values(stats)
else
[]
end
end
def table_stats_query(connection)
@table_stats_query ||= build_table_stats_query(connection)
ensure
@table_stats_query = nil unless @cache_tables
end
def build_table_stats_query(connection)
tables = connection.select_values(<<-SQL)
SELECT table_name
FROM information_schema.tables
WHERE table_schema = database()
AND #{::DatabaseCleaner::ActiveRecord::Base.exclusion_condition('table_name')};
SQL
queries = tables.map do |table|
"(SELECT #{connection.quote(table)} FROM #{connection.quote_table_name(table)} LIMIT 1)"
end
queries.join(' UNION ALL ')
end
def information_schema_exists? connection
return false unless connection.is_a? ActiveRecord::ConnectionAdapters::Mysql2Adapter
@information_schema_exists ||=
begin
connection.execute("SELECT 1 FROM information_schema.tables")
true
rescue
false
end
end
end
class Deletion < Truncation
if defined?(ActiveRecord::ConnectionAdapters::Mysql2Adapter)
include SelectiveTruncation
end
def clean
connection = connection_class.connection
connection.disable_referential_integrity do
tables_to_truncate(connection).each do |table_name|
connection.delete_table table_name
end
end
end
end
end

View file

@ -1,59 +0,0 @@
require 'database_cleaner/active_record/base'
require 'database_cleaner/generic/transaction'
module DatabaseCleaner::ActiveRecord
class Transaction
include ::DatabaseCleaner::ActiveRecord::Base
include ::DatabaseCleaner::Generic::Transaction
def start
# Hack to make sure that the connection is properly setup for
# the clean code.
connection_class.connection.transaction{ }
if connection_maintains_transaction_count?
if connection_class.connection.respond_to?(:increment_open_transactions)
connection_class.connection.increment_open_transactions
else
connection_class.__send__(:increment_open_transactions)
end
end
if connection_class.connection.respond_to?(:begin_transaction)
connection_class.connection.begin_transaction :joinable => false
else
connection_class.connection.begin_db_transaction
end
end
def clean
connection_class.connection_pool.connections.each do |connection|
next unless connection.open_transactions > 0
if connection.respond_to?(:rollback_transaction)
connection.rollback_transaction
else
connection.rollback_db_transaction
end
# The below is for handling after_commit hooks.. see https://github.com/bmabey/database_cleaner/issues/99
if connection.respond_to?(:rollback_transaction_records, true)
connection.send(:rollback_transaction_records, true)
end
if connection_maintains_transaction_count?
if connection.respond_to?(:decrement_open_transactions)
connection.decrement_open_transactions
else
connection_class.__send__(:decrement_open_transactions)
end
end
end
end
def connection_maintains_transaction_count?
ActiveRecord::VERSION::MAJOR < 4
end
end
end

View file

@ -1,280 +0,0 @@
require 'active_record/base'
require 'database_cleaner/active_record/base'
require 'active_record/connection_adapters/abstract_adapter'
#Load available connection adapters
%w(
abstract_mysql_adapter postgresql_adapter sqlite3_adapter mysql_adapter mysql2_adapter oracle_enhanced_adapter
).each do |known_adapter|
begin
require "active_record/connection_adapters/#{known_adapter}"
rescue LoadError
end
end
require "database_cleaner/generic/truncation"
require 'database_cleaner/active_record/base'
module DatabaseCleaner
module ConnectionAdapters
module AbstractAdapter
# used to be called views but that can clash with gems like schema_plus
# this gem is not meant to be exposing such an extra interface any way
def database_cleaner_view_cache
@views ||= select_values("select table_name from information_schema.views where table_schema = '#{current_database}'") rescue []
end
def database_cleaner_table_cache
# the adapters don't do caching (#130) but we make the assumption that the list stays the same in tests
@database_cleaner_tables ||= database_tables
end
def database_tables
::ActiveRecord::VERSION::MAJOR >= 5 ? data_sources : tables
end
def truncate_table(table_name)
raise NotImplementedError
end
def truncate_tables(tables)
tables.each do |table_name|
self.truncate_table(table_name)
end
end
end
module AbstractMysqlAdapter
def truncate_table(table_name)
execute("TRUNCATE TABLE #{quote_table_name(table_name)};")
end
def truncate_tables(tables)
tables.each { |t| truncate_table(t) }
end
def pre_count_truncate_tables(tables, options = {:reset_ids => true})
filter = options[:reset_ids] ? method(:has_been_used?) : method(:has_rows?)
truncate_tables(tables.select(&filter))
end
private
def row_count(table)
# Patch for MysqlAdapter with ActiveRecord 3.2.7 later
# select_value("SELECT 1") #=> "1"
select_value("SELECT EXISTS (SELECT 1 FROM #{quote_table_name(table)} LIMIT 1)").to_i
end
def auto_increment_value(table)
select_value(<<-SQL).to_i
SELECT auto_increment
FROM information_schema.tables
WHERE table_name = '#{table}'
AND table_schema = database()
SQL
end
# This method tells us if the given table has been inserted into since its
# last truncation. Note that the table might have been populated, which
# increased the auto-increment counter, but then cleaned again such that
# it appears empty now.
def has_been_used?(table)
has_rows?(table) || auto_increment_value(table) > 1
end
def has_rows?(table)
row_count(table) > 0
end
end
module IBM_DBAdapter
def truncate_table(table_name)
execute("TRUNCATE #{quote_table_name(table_name)} IMMEDIATE")
end
end
module SQLiteAdapter
def delete_table(table_name)
execute("DELETE FROM #{quote_table_name(table_name)};")
if uses_sequence
execute("DELETE FROM sqlite_sequence where name = '#{table_name}';")
end
end
alias truncate_table delete_table
def truncate_tables(tables)
tables.each { |t| truncate_table(t) }
end
private
# Returns a boolean indicating if the SQLite database is using the sqlite_sequence table.
def uses_sequence
select_value("SELECT name FROM sqlite_master WHERE type='table' AND name='sqlite_sequence';")
end
end
module TruncateOrDelete
def truncate_table(table_name)
begin
execute("TRUNCATE TABLE #{quote_table_name(table_name)};")
rescue ::ActiveRecord::StatementInvalid
execute("DELETE FROM #{quote_table_name(table_name)};")
end
end
end
module OracleAdapter
def truncate_table(table_name)
execute("TRUNCATE TABLE #{quote_table_name(table_name)}")
end
end
module PostgreSQLAdapter
def db_version
@db_version ||= postgresql_version
end
def cascade
@cascade ||= db_version >= 80200 ? 'CASCADE' : ''
end
def restart_identity
@restart_identity ||= db_version >= 80400 ? 'RESTART IDENTITY' : ''
end
def truncate_table(table_name)
truncate_tables([table_name])
end
def truncate_tables(table_names)
return if table_names.nil? || table_names.empty?
execute("TRUNCATE TABLE #{table_names.map{|name| quote_table_name(name)}.join(', ')} #{restart_identity} #{cascade};")
end
def pre_count_truncate_tables(tables, options = {:reset_ids => true})
filter = options[:reset_ids] ? method(:has_been_used?) : method(:has_rows?)
truncate_tables(tables.select(&filter))
end
def database_cleaner_table_cache
# AR returns a list of tables without schema but then returns a
# migrations table with the schema. There are other problems, too,
# with using the base list. If a table exists in multiple schemas
# within the search path, truncation without the schema name could
# result in confusing, if not unexpected results.
@database_cleaner_tables ||= tables_with_schema
end
private
# Returns a boolean indicating if the given table has an auto-inc number higher than 0.
# Note, this is different than an empty table since an table may populated, the index increased,
# but then the table is cleaned. In other words, this function tells us if the given table
# was ever inserted into.
def has_been_used?(table)
return has_rows?(table) unless has_sequence?(table)
cur_val = select_value("SELECT currval('#{table}_id_seq');").to_i rescue 0
cur_val > 0
end
def has_sequence?(table)
select_value("SELECT true FROM pg_class WHERE relname = '#{table}_id_seq';")
end
def has_rows?(table)
select_value("SELECT true FROM #{table} LIMIT 1;")
end
def tables_with_schema
rows = select_rows <<-_SQL
SELECT schemaname || '.' || tablename
FROM pg_tables
WHERE
tablename !~ '_prt_' AND
#{::DatabaseCleaner::ActiveRecord::Base.exclusion_condition('tablename')} AND
schemaname = ANY (current_schemas(false))
_SQL
rows.collect { |result| result.first }
end
end
end
end
module ActiveRecord
module ConnectionAdapters
#Apply adapter decoraters where applicable (adapter should be loaded)
AbstractAdapter.class_eval { include DatabaseCleaner::ConnectionAdapters::AbstractAdapter }
if defined?(JdbcAdapter)
if defined?(OracleJdbcConnection)
JdbcAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::OracleAdapter }
else
JdbcAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::TruncateOrDelete }
end
end
AbstractMysqlAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::AbstractMysqlAdapter } if defined?(AbstractMysqlAdapter)
Mysql2Adapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::AbstractMysqlAdapter } if defined?(Mysql2Adapter)
MysqlAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::AbstractMysqlAdapter } if defined?(MysqlAdapter)
SQLiteAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::SQLiteAdapter } if defined?(SQLiteAdapter)
SQLite3Adapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::SQLiteAdapter } if defined?(SQLite3Adapter)
PostgreSQLAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::PostgreSQLAdapter } if defined?(PostgreSQLAdapter)
IBM_DBAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::IBM_DBAdapter } if defined?(IBM_DBAdapter)
SQLServerAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::TruncateOrDelete } if defined?(SQLServerAdapter)
OracleEnhancedAdapter.class_eval { include ::DatabaseCleaner::ConnectionAdapters::OracleAdapter } if defined?(OracleEnhancedAdapter)
end
end
module DatabaseCleaner::ActiveRecord
class Truncation
include ::DatabaseCleaner::ActiveRecord::Base
include ::DatabaseCleaner::Generic::Truncation
def clean
connection = connection_class.connection
connection.disable_referential_integrity do
if pre_count? && connection.respond_to?(:pre_count_truncate_tables)
connection.pre_count_truncate_tables(tables_to_truncate(connection), {:reset_ids => reset_ids?})
else
connection.truncate_tables(tables_to_truncate(connection))
end
end
end
private
def tables_to_truncate(connection)
tables_in_db = cache_tables? ? connection.database_cleaner_table_cache : connection.database_tables
to_reject = (@tables_to_exclude + connection.database_cleaner_view_cache)
(@only || tables_in_db).reject do |table|
if ( m = table.match(/([^.]+)$/) )
to_reject.include?(m[1])
else
false
end
end
end
# overwritten
def migration_storage_names
result = [::DatabaseCleaner::ActiveRecord::Base.migration_table_name]
result << ::ActiveRecord::Base.internal_metadata_table_name if ::ActiveRecord::VERSION::MAJOR >= 5
result
end
def cache_tables?
!!@cache_tables
end
def pre_count?
@pre_count == true
end
def reset_ids?
@reset_ids != false
end
end
end

View file

@ -1,5 +0,0 @@
module DatabaseCleaner
module ActiveRecord
VERSION = "1.8.0"
end
end

View file

@ -1,170 +0,0 @@
require 'active_record'
require 'database_cleaner/active_record/base'
require 'database_cleaner/spec'
class FakeModel
def self.connection
:fake_connection
end
end
RSpec.describe DatabaseCleaner::ActiveRecord do
it { is_expected.to respond_to(:available_strategies) }
it "has a default_strategy of transaction" do
expect(described_class.default_strategy).to eq(:transaction)
end
describe "config_file_location" do
after do
# prevent global state leakage
DatabaseCleaner::ActiveRecord.config_file_location=nil
DatabaseCleaner.app_root = nil
end
it "should default to \#{DatabaseCleaner.app_root}/config/database.yml" do
DatabaseCleaner::ActiveRecord.config_file_location = nil
DatabaseCleaner.app_root = "/path/to"
expect(DatabaseCleaner::ActiveRecord.config_file_location).to eq '/path/to/config/database.yml'
end
end
end
module DatabaseCleaner
module ActiveRecord
class ExampleStrategy
include DatabaseCleaner::ActiveRecord::Base
end
RSpec.describe ExampleStrategy do
let(:config_location) { '/path/to/config/database.yml' }
around do |example|
DatabaseCleaner::ActiveRecord.config_file_location = config_location
example.run
DatabaseCleaner::ActiveRecord.config_file_location = nil
end
it_should_behave_like "a generic strategy"
describe "db" do
it "should store my desired db" do
subject.db = :my_db
expect(subject.db).to eq :my_db
end
it "should default to :default" do
expect(subject.db).to eq :default
end
end
describe "db=" do
let(:config_location) { "spec/support/example.database.yml" }
it "should process erb in the config" do
subject.db = :my_db
expect(subject.connection_hash).to eq({ "database" => "one" })
end
context 'when config file differs from established ActiveRecord configuration' do
before do
allow(::ActiveRecord::Base).to receive(:configurations).and_return({ "my_db" => { "database" => "two"} })
end
it 'uses the ActiveRecord configuration' do
subject.db = :my_db
expect(subject.connection_hash).to eq({ "database" => "two"})
end
end
context 'when config file agrees with ActiveRecord configuration' do
before do
allow(::ActiveRecord::Base).to receive(:configurations).and_return({ "my_db" => { "database" => "one"} })
end
it 'uses the config file' do
subject.db = :my_db
expect(subject.connection_hash).to eq({ "database" => "one"})
end
end
context 'when ::ActiveRecord::Base.configurations nil' do
before do
allow(::ActiveRecord::Base).to receive(:configurations).and_return(nil)
end
it 'uses the config file' do
subject.db = :my_db
expect(subject.connection_hash).to eq({ "database" => "one"})
end
end
context 'when ::ActiveRecord::Base.configurations empty' do
before do
allow(::ActiveRecord::Base).to receive(:configurations).and_return({})
end
it 'uses the config file' do
subject.db = :my_db
expect(subject.connection_hash).to eq({ "database" => "one"})
end
end
context 'when config file is not available' do
before do
allow(File).to receive(:file?).with(config_location).and_return(false)
end
it "should skip config" do
subject.db = :my_db
expect(subject.connection_hash).not_to be
end
end
it "skips the file when the model is set" do
subject.db = FakeModel
expect(subject.connection_hash).not_to be
end
it "skips the file when the db is set to :default" do
# to avoid https://github.com/bmabey/database_cleaner/issues/72
subject.db = :default
expect(subject.connection_hash).not_to be
end
end
describe "connection_class" do
it "should default to ActiveRecord::Base" do
expect(subject.connection_class).to eq ::ActiveRecord::Base
end
context "with database models" do
context "connection_hash is set" do
it "reuses the model's connection" do
subject.connection_hash = {}
subject.db = FakeModel
expect(subject.connection_class).to eq FakeModel
end
end
context "connection_hash is not set" do
it "reuses the model's connection" do
subject.db = FakeModel
expect(subject.connection_class).to eq FakeModel
end
end
end
context "when connection_hash is set" do
let(:hash) { {} }
before { subject.connection_hash = hash }
it "establishes a connection with it" do
expect(::ActiveRecord::Base).to receive(:establish_connection).with(hash)
expect(subject.connection_class).to eq ::ActiveRecord::Base
end
end
end
end
end
end

View file

@ -1,155 +0,0 @@
require 'database_cleaner/active_record/transaction'
require 'active_record'
module DatabaseCleaner
module ActiveRecord
RSpec.describe Transaction do
let(:connection) { double("connection") }
let(:connection_2) { double("connection_2") }
let(:connection_pool) { double("connection_pool") }
before do
allow(::ActiveRecord::Base).to receive(:connection_pool).and_return(connection_pool)
allow(connection_pool).to receive(:connections).and_return([connection])
allow(::ActiveRecord::Base).to receive(:connection).and_return(connection)
end
describe "#start" do
[:begin_transaction, :begin_db_transaction].each do |begin_transaction_method|
context "using #{begin_transaction_method}" do
before do
allow(connection).to receive(:transaction)
allow(connection).to receive(begin_transaction_method)
end
it "should increment open transactions if possible" do
expect(connection).to receive(:increment_open_transactions)
subject.start
end
it "should tell ActiveRecord to increment connection if its not possible to increment current connection" do
expect(::ActiveRecord::Base).to receive(:increment_open_transactions)
subject.start
end
it "should start a transaction" do
allow(connection).to receive(:increment_open_transactions)
expect(connection).to receive(begin_transaction_method)
expect(connection).to receive(:transaction)
subject.start
end
end
end
end
describe "#clean" do
context "manual accounting of transaction count" do
it "should start a transaction" do
expect(connection).to receive(:open_transactions).and_return(1)
allow(connection).to receive(:decrement_open_transactions)
expect(connection).to receive(:rollback_db_transaction)
subject.clean
end
it "should decrement open transactions if possible" do
expect(connection).to receive(:open_transactions).and_return(1)
allow(connection).to receive(:rollback_db_transaction)
expect(connection).to receive(:decrement_open_transactions)
subject.clean
end
it "should not try to decrement or rollback if open_transactions is 0 for whatever reason" do
expect(connection).to receive(:open_transactions).and_return(0)
subject.clean
end
it "should decrement connection via ActiveRecord::Base if connection won't" do
expect(connection).to receive(:open_transactions).and_return(1)
allow(connection).to receive(:rollback_db_transaction)
expect(::ActiveRecord::Base).to receive(:decrement_open_transactions)
subject.clean
end
it "should rollback open transactions in all connections" do
allow(connection_pool).to receive(:connections).and_return([connection, connection_2])
expect(connection).to receive(:open_transactions).and_return(1)
allow(connection).to receive(:rollback_db_transaction)
expect(connection_2).to receive(:open_transactions).and_return(1)
allow(connection_2).to receive(:rollback_db_transaction)
expect(::ActiveRecord::Base).to receive(:decrement_open_transactions).twice
subject.clean
end
it "should rollback open transactions in all connections with an open transaction" do
allow(connection_pool).to receive(:connections).and_return([connection, connection_2])
expect(connection).to receive(:open_transactions).and_return(1)
allow(connection).to receive(:rollback_db_transaction)
expect(connection_2).to receive(:open_transactions).and_return(0)
expect(::ActiveRecord::Base).to receive(:decrement_open_transactions).exactly(1).times
subject.clean
end
end
context "automatic accounting of transaction count (AR 4)" do
before { stub_const("ActiveRecord::VERSION::MAJOR", 4) }
it "should start a transaction" do
allow(connection).to receive(:rollback_db_transaction)
expect(connection).to receive(:open_transactions).and_return(1)
expect(connection).not_to receive(:decrement_open_transactions)
expect(connection).to receive(:rollback_transaction)
subject.clean
end
it "should decrement open transactions if possible" do
allow(connection).to receive(:rollback_transaction)
expect(connection).to receive(:open_transactions).and_return(1)
expect(connection).not_to receive(:decrement_open_transactions)
subject.clean
end
it "should not try to decrement or rollback if open_transactions is 0 for whatever reason" do
expect(connection).to receive(:open_transactions).and_return(0)
subject.clean
end
it "should decrement connection via ActiveRecord::Base if connection won't" do
expect(connection).to receive(:open_transactions).and_return(1)
allow(connection).to receive(:rollback_transaction)
expect(::ActiveRecord::Base).not_to receive(:decrement_open_transactions)
subject.clean
end
end
end
describe "#connection_maintains_transaction_count?" do
it "should return true if the major active record version is < 4" do
stub_const("ActiveRecord::VERSION::MAJOR", 3)
expect(subject.connection_maintains_transaction_count?).to be_truthy
end
it "should return false if the major active record version is > 3" do
stub_const("ActiveRecord::VERSION::MAJOR", 4)
expect(subject.connection_maintains_transaction_count?).to be_falsey
end
end
end
end
end

View file

@ -1,120 +0,0 @@
require 'support/active_record_helper'
require 'database_cleaner/active_record/truncation'
RSpec.describe DatabaseCleaner::ActiveRecord::Truncation do
ActiveRecordHelper.with_all_dbs do |helper|
context "using a #{helper.db} connection" do
around do |example|
helper.setup
example.run
helper.teardown
end
let(:connection) { helper.connection }
before do
allow(connection).to receive(:disable_referential_integrity).and_yield
allow(connection).to receive(:database_cleaner_view_cache).and_return([])
end
describe '#clean' do
context "with records" do
before do
2.times { User.create! }
2.times { Agent.create! }
end
it "should truncate all tables" do
expect { subject.clean }
.to change { [User.count, Agent.count] }
.from([2,2])
.to([0,0])
end
it "should reset AUTO_INCREMENT index of table" do
subject.clean
expect(User.create.id).to eq 1
end
xit "should not reset AUTO_INCREMENT index of table if :reset_ids is false" do
described_class.new(reset_ids: false).clean
expect(User.create.id).to eq 3
end
it "should truncate all tables except for schema_migrations" do
subject.clean
count = connection.select_value("select count(*) from schema_migrations;").to_i
expect(count).to eq 2
end
it "should only truncate the tables specified in the :only option when provided" do
expect { described_class.new(only: ['agents']).clean }
.to change { [User.count, Agent.count] }
.from([2,2])
.to([2,0])
end
it "should not truncate the tables specified in the :except option" do
expect { described_class.new(except: ['users']).clean }
.to change { [User.count, Agent.count] }
.from([2,2])
.to([2,0])
end
it "should raise an error when :only and :except options are used" do
expect {
described_class.new(except: ['widgets'], only: ['widgets'])
}.to raise_error(ArgumentError)
end
it "should raise an error when invalid options are provided" do
expect { described_class.new(foo: 'bar') }.to raise_error(ArgumentError)
end
it "should not truncate views" do
allow(connection).to receive(:database_cleaner_table_cache).and_return(%w[widgets dogs])
allow(connection).to receive(:database_cleaner_view_cache).and_return(["widgets"])
expect(connection).to receive(:truncate_tables).with(['dogs'])
subject.clean
end
end
describe "with pre_count optimization option" do
subject { described_class.new(pre_count: true) }
it "only truncates non-empty tables" do
pending if helper.db == :sqlite3
pending if helper.db == :postgres
User.create!
expect(connection).to receive(:truncate_tables).with(['users'])
subject.clean
end
end
context 'when :cache_tables is set to true' do
it 'caches the list of tables to be truncated' do
expect(connection).to receive(:database_cleaner_table_cache).and_return([])
expect(connection).not_to receive(:tables)
allow(connection).to receive(:truncate_tables)
described_class.new(cache_tables: true).clean
end
end
context 'when :cache_tables is set to false' do
it 'does not cache the list of tables to be truncated' do
expect(connection).not_to receive(:database_cleaner_table_cache)
expect(connection).to receive(:tables).and_return([])
allow(connection).to receive(:truncate_tables)
described_class.new(cache_tables: false).clean
end
end
end
end
end
end

View file

@ -1,14 +0,0 @@
require "bundler/setup"
require 'database_cleaner'
RSpec.configure do |config|
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
end

View file

@ -1,40 +0,0 @@
require 'active_record'
require 'database_cleaner/spec/database_helper'
class ActiveRecordHelper < DatabaseCleaner::Spec::DatabaseHelper
def setup
patch_mysql_adapters
Kernel.const_set "User", Class.new(ActiveRecord::Base)
Kernel.const_set "Agent", Class.new(ActiveRecord::Base)
super
connection.execute "CREATE TABLE IF NOT EXISTS schema_migrations (version VARCHAR(255));"
connection.execute "INSERT INTO schema_migrations VALUES (1), (2);"
end
def teardown
connection.execute "DROP TABLE schema_migrations;"
super
Kernel.send :remove_const, "User" if defined?(User)
Kernel.send :remove_const, "Agent" if defined?(Agent)
end
private
def establish_connection(config = default_config)
ActiveRecord::Base.establish_connection(config)
@connection = ActiveRecord::Base.connection
end
def patch_mysql_adapters
# remove DEFAULT NULL from column definition, which is an error on primary keys in MySQL 5.7.3+
primary_key_sql = "int(11) auto_increment PRIMARY KEY"
ActiveRecord::ConnectionAdapters::MysqlAdapter::NATIVE_DATABASE_TYPES[:primary_key] = primary_key_sql
ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES[:primary_key] = primary_key_sql
end
end

View file

@ -1,3 +0,0 @@
my_db:
database: <%= "ONE".downcase %>

View file

@ -1,34 +0,0 @@
mysql:
adapter: mysql
database: database_cleaner_test
username: root
password:
host: 127.0.0.1
port: 3306
encoding: utf8
mysql2:
adapter: mysql2
database: database_cleaner_test
username: root
password:
host: 127.0.0.1
port: 3306
encoding: utf8
postgres:
adapter: postgresql
database: database_cleaner_test
username: postgres
password:
host: 127.0.0.1
encoding: unicode
template: template0
sqlite3:
adapter: sqlite3
database: tmp/database_cleaner_test.sqlite3
pool: 5
timeout: 5000
encoding: utf8

View file

@ -1,11 +0,0 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
# rspec failure tracking
.rspec_status

View file

@ -1,3 +0,0 @@
--format documentation
--color
--require spec_helper

View file

@ -1,4 +0,0 @@
language: ruby
rvm:
- 2.2.9
before_install: gem install bundler -v 1.17.2

View file

@ -1,8 +0,0 @@
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# Specify your gem's dependencies in database_cleaner-couch_potato.gemspec
gemspec
gem "database_cleaner", path: "../.."

View file

@ -1,80 +0,0 @@
PATH
remote: ../..
specs:
database_cleaner (1.8.2)
PATH
remote: .
specs:
database_cleaner-couch_potato (1.8.0)
couch_potato
database_cleaner (~> 1.8.0)
GEM
remote: https://rubygems.org/
specs:
activemodel (5.2.4.1)
activesupport (= 5.2.4.1)
activesupport (5.2.4.1)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (>= 0.7, < 2)
minitest (~> 5.1)
tzinfo (~> 1.1)
concurrent-ruby (1.1.5)
couch_potato (1.3.0)
activemodel
couchrest (~> 1.2.0)
json (~> 1.6)
couchrest (1.2.1)
mime-types (>= 1.15)
multi_json (~> 1.7, ~> 1.0)
rest-client (~> 1.8.0)
diff-lcs (1.3)
domain_name (0.5.20180417)
unf (>= 0.0.5, < 1.0.0)
http-cookie (1.0.3)
domain_name (~> 0.5)
i18n (1.5.1)
concurrent-ruby (~> 1.0)
json (1.8.6)
mime-types (2.99.3)
minitest (5.14.0)
multi_json (1.14.1)
netrc (0.11.0)
rake (10.4.2)
rest-client (1.8.0)
http-cookie (>= 1.0.2, < 2.0)
mime-types (>= 1.16, < 3.0)
netrc (~> 0.7)
rspec (3.7.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-core (3.7.1)
rspec-support (~> 3.7.0)
rspec-expectations (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-mocks (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-support (3.7.1)
thread_safe (0.3.6)
tzinfo (1.2.6)
thread_safe (~> 0.1)
unf (0.1.4)
unf_ext
unf_ext (0.0.7.5)
PLATFORMS
ruby
DEPENDENCIES
bundler (~> 1.16)
database_cleaner!
database_cleaner-couch_potato!
rake (~> 10.0)
rspec (~> 3.0)
BUNDLED WITH
1.17.3

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2009 Ben Mabey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,59 +0,0 @@
# Database Cleaner Adapter for CouchPotato
[![Build Status](https://travis-ci.org/DatabaseCleaner/database_cleaner-couch_potato.svg?branch=master)](https://travis-ci.org/DatabaseCleaner/database_cleaner-couch_potato)
[![Code Climate](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-couch_potato/badges/gpa.svg)](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-couch_potato)
Clean your CouchPotato databases with Database Cleaner.
See https://github.com/DatabaseCleaner/database_cleaner for more information.
## Installation
```ruby
# Gemfile
group :test do
gem 'database_cleaner-couch_potato'
end
```
## Supported Strategies
Here is an overview of the supported strategies:
<table>
<tbody>
<tr>
<th>Truncation</th>
<th>Transaction</th>
<th>Deletion</th>
</tr>
<tr>
<td> <b>Yes</b></td>
<td> No</td>
<td> No</td>
</tr>
</tbody>
</table>
(Default strategy is denoted in bold)
## Configuration options
<table>
<tbody>
<tr>
<th>ORM</th>
<th>How to access</th>
<th>Notes</th>
</tr>
<tr>
<td> Couch Potato</td>
<td> <code>DatabaseCleaner[:couch_potato]</code></td>
<td> Multiple connections not yet supported</td>
</tr>
</tbody>
</table>
## COPYRIGHT
See [LICENSE] for details.

View file

@ -1,6 +0,0 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
task :default => :spec

View file

@ -1,14 +0,0 @@
#!/usr/bin/env ruby
require "bundler/setup"
require "database_cleaner/couch_potato"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start
require "irb"
IRB.start(__FILE__)

View file

@ -1,6 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle check || bundle install

View file

@ -1,30 +0,0 @@
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "database_cleaner/couch_potato/version"
Gem::Specification.new do |spec|
spec.name = "database_cleaner-couch_potato"
spec.version = DatabaseCleaner::CouchPotato::VERSION
spec.authors = ["Ernesto Tagwerker"]
spec.email = ["ernesto@ombulabs.com"]
spec.summary = "Strategies for cleaning databases using CouchPotato. Can be used to ensure a clean state for testing."
spec.description = "Strategies for cleaning databases using CouchPotato. Can be used to ensure a clean state for testing."
spec.homepage = "https://github.com/DatabaseCleaner/database_cleaner-couch_potato"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "database_cleaner", "~> 1.8.0"
spec.add_dependency "couch_potato"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rspec", "~> 3.0"
end

View file

@ -1 +0,0 @@
require "database_cleaner/couch_potato"

View file

@ -1,11 +0,0 @@
require "database_cleaner/couch_potato/version"
require "database_cleaner"
require "database_cleaner/couch_potato/base"
require "database_cleaner/couch_potato/truncation"
module DatabaseCleaner::CouchPotato
def self.default_strategy
:truncation
end
end

View file

@ -1,7 +0,0 @@
module DatabaseCleaner
module CouchPotato
def self.available_strategies
%w[truncation]
end
end
end

View file

@ -1,28 +0,0 @@
require 'database_cleaner/generic/truncation'
module DatabaseCleaner
module CouchPotato
class Truncation
include ::DatabaseCleaner::Generic::Truncation
def initialize(options = {})
if options.has_key?(:only) || options.has_key?(:except)
raise ArgumentError, "The :only and :except options are not available for use with CouchPotato/CouchDB."
elsif !options.empty?
raise ArgumentError, "Unsupported option. You specified #{options.keys.join(',')}."
end
super
end
def clean
database.recreate!
end
private
def database
::CouchPotato.couchrest_database
end
end
end
end

View file

@ -1,5 +0,0 @@
module DatabaseCleaner
module CouchPotato
VERSION = "1.8.0"
end
end

View file

@ -1,8 +0,0 @@
require 'database_cleaner/couch_potato'
RSpec.describe DatabaseCleaner::CouchPotato do
it "has a default_strategy of truncation" do
expect(described_class.default_strategy).to eq(:truncation)
end
end

View file

@ -1,40 +0,0 @@
require 'database_cleaner/couch_potato/truncation'
require 'couch_potato'
module DatabaseCleaner
module CouchPotato
RSpec.describe Truncation do
let(:database) { double('database') }
before(:each) do
allow(::CouchPotato).to receive(:couchrest_database).and_return(database)
end
it "should re-create the database" do
expect(database).to receive(:recreate!)
Truncation.new.clean
end
it "should raise an error when the :only option is used" do
expect {
Truncation.new(:only => ['document-type'])
}.to raise_error(ArgumentError)
end
it "should raise an error when the :except option is used" do
expect {
Truncation.new(:except => ['document-type'])
}.to raise_error(ArgumentError)
end
it "should raise an error when invalid options are provided" do
expect {
Truncation.new(:foo => 'bar')
}.to raise_error(ArgumentError)
end
end
end
end

View file

@ -1,14 +0,0 @@
require "bundler/setup"
require "database_cleaner/couch_potato"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end

View file

@ -1,13 +0,0 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/spec/support/config.yml
/tmp/
!/tmp/.keep
# rspec failure tracking
.rspec_status

View file

@ -1,3 +0,0 @@
--format documentation
--color
--require spec_helper

View file

@ -1,4 +0,0 @@
language: ruby
rvm:
- 2.2.9
before_install: gem install bundler -v 1.17.2

View file

@ -1,8 +0,0 @@
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# Specify your gem's dependencies in database_cleaner-data_mapper.gemspec
gemspec
gem "database_cleaner", path: "../.."

View file

@ -1,103 +0,0 @@
PATH
remote: ../..
specs:
database_cleaner (1.8.2)
PATH
remote: .
specs:
database_cleaner-data_mapper (1.8.0)
database_cleaner (~> 1.8.0)
datamapper
dm-transactions
GEM
remote: https://rubygems.org/
specs:
addressable (2.3.6)
bcrypt (3.1.13)
bcrypt-ruby (3.1.5)
bcrypt (>= 3.1.3)
data_objects (0.10.14)
addressable (~> 2.1)
datamapper (1.2.0)
dm-aggregates (~> 1.2.0)
dm-constraints (~> 1.2.0)
dm-core (~> 1.2.0)
dm-migrations (~> 1.2.0)
dm-serializer (~> 1.2.0)
dm-timestamps (~> 1.2.0)
dm-transactions (~> 1.2.0)
dm-types (~> 1.2.0)
dm-validations (~> 1.2.0)
diff-lcs (1.3)
dm-aggregates (1.2.0)
dm-core (~> 1.2.0)
dm-constraints (1.2.0)
dm-core (~> 1.2.0)
dm-core (1.2.1)
addressable (~> 2.3)
dm-do-adapter (1.2.0)
data_objects (~> 0.10.6)
dm-core (~> 1.2.0)
dm-migrations (1.2.0)
dm-core (~> 1.2.0)
dm-serializer (1.2.2)
dm-core (~> 1.2.0)
fastercsv (~> 1.5)
json (~> 1.6)
json_pure (~> 1.6)
multi_json (~> 1.0)
dm-sqlite-adapter (1.2.0)
dm-do-adapter (~> 1.2.0)
do_sqlite3 (~> 0.10.6)
dm-timestamps (1.2.0)
dm-core (~> 1.2.0)
dm-transactions (1.2.0)
dm-core (~> 1.2.0)
dm-types (1.2.2)
bcrypt-ruby (~> 3.0)
dm-core (~> 1.2.0)
fastercsv (~> 1.5)
json (~> 1.6)
multi_json (~> 1.0)
stringex (~> 1.4)
uuidtools (~> 2.1)
dm-validations (1.2.0)
dm-core (~> 1.2.0)
do_sqlite3 (0.10.14)
data_objects (= 0.10.14)
fastercsv (1.5.5)
json (1.8.6)
json_pure (1.8.6)
multi_json (1.14.1)
rake (10.4.2)
rspec (3.7.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-core (3.7.1)
rspec-support (~> 3.7.0)
rspec-expectations (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-mocks (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-support (3.7.1)
stringex (1.5.1)
uuidtools (2.1.5)
PLATFORMS
ruby
DEPENDENCIES
bundler (~> 1.16)
database_cleaner!
database_cleaner-data_mapper!
dm-sqlite-adapter
rake (~> 10.0)
rspec (~> 3.0)
BUNDLED WITH
1.17.3

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2009 Ben Mabey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,59 +0,0 @@
# Database Cleaner Adapter for DataMapper
[![Build Status](https://travis-ci.org/DatabaseCleaner/database_cleaner-data_mapper.svg?branch=master)](https://travis-ci.org/DatabaseCleaner/database_cleaner-data_mapper)
[![Code Climate](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-data_mapper/badges/gpa.svg)](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-data_mapper)
Clean your DataMapper databases with Database Cleaner.
See https://github.com/DatabaseCleaner/database_cleaner for more information.
## Installation
```ruby
# Gemfile
group :test do
gem 'database_cleaner-data_mapper'
end
```
## Supported Strategies
Here is an overview of the supported strategies:
<table>
<tbody>
<tr>
<th>Truncation</th>
<th>Transaction</th>
<th>Deletion</th>
</tr>
<tr>
<td> Yes</td>
<td> <b>Yes</b></td>
<td> No</td>
</tr>
</tbody>
</table>
(Default strategy is denoted in bold)
## Configuration options
<table>
<tbody>
<tr>
<th>ORM</th>
<th>How to access</th>
<th>Notes</th>
</tr>
<tr>
<td> Data Mapper</td>
<td> <code>DatabaseCleaner[:data_mapper]</code></td>
<td> Connection specified as <code>:symbol</code> keys, loaded via Datamapper repositories </td>
</tr>
</tbody>
</table>
## COPYRIGHT
See [LICENSE] for details.

View file

@ -1,6 +0,0 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
task :default => :spec

View file

@ -1,14 +0,0 @@
#!/usr/bin/env ruby
require "bundler/setup"
require "database_cleaner/data_mapper"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start
require "irb"
IRB.start(__FILE__)

View file

@ -1,8 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle check || bundle install
cp spec/support/sample.config.yml spec/support/config.yml

View file

@ -1,34 +0,0 @@
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "database_cleaner/data_mapper/version"
Gem::Specification.new do |spec|
spec.name = "database_cleaner-data_mapper"
spec.version = DatabaseCleaner::DataMapper::VERSION
spec.authors = ["Ernesto Tagwerker"]
spec.email = ["ernesto@ombulabs.com"]
spec.summary = "Strategies for cleaning databases using DataMapper. Can be used to ensure a clean state for testing."
spec.description = "Strategies for cleaning databases using DataMapper. Can be used to ensure a clean state for testing."
spec.homepage = "https://github.com/DatabaseCleaner/database_cleaner-data_mapper"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "database_cleaner", "~> 1.8.0"
spec.add_dependency "datamapper"
spec.add_dependency "dm-transactions"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "dm-sqlite-adapter"
# spec.add_development_dependency "dm-migrations"
end

View file

@ -1 +0,0 @@
require "database_cleaner/data_mapper"

View file

@ -1,4 +0,0 @@
require "database_cleaner/data_mapper/version"
require "database_cleaner"
require "database_cleaner/data_mapper/transaction"
require "database_cleaner/data_mapper/truncation"

View file

@ -1,25 +0,0 @@
require 'database_cleaner/generic/base'
module DatabaseCleaner
module DataMapper
def self.available_strategies
%w[truncation transaction]
end
def self.default_strategy
:transaction
end
module Base
include ::DatabaseCleaner::Generic::Base
def db=(desired_db)
@db = desired_db
end
def db
@db ||= :default
end
end
end
end

View file

@ -1,28 +0,0 @@
require 'database_cleaner/data_mapper/base'
require 'database_cleaner/generic/transaction'
module DatabaseCleaner::DataMapper
class Transaction
include ::DatabaseCleaner::DataMapper::Base
include ::DatabaseCleaner::Generic::Transaction
def start(repository = self.db)
::DataMapper.repository(repository) do |r|
transaction = DataMapper::Transaction.new(r)
transaction.begin
r.adapter.push_transaction(transaction)
end
end
def clean(repository = self.db)
::DataMapper.repository(repository) do |r|
adapter = r.adapter
while adapter.current_transaction
adapter.current_transaction.rollback
adapter.pop_transaction
end
end
end
end
end

View file

@ -1,173 +0,0 @@
require "database_cleaner/generic/truncation"
require 'database_cleaner/data_mapper/base'
require 'data_mapper'
module DataMapper
module Adapters
class DataObjectsAdapter
def storage_names(repository = :default)
raise NotImplementedError
end
def truncate_tables(table_names)
table_names.each do |table_name|
truncate_table table_name
end
end
end
class MysqlAdapter < DataObjectsAdapter
# taken from https://github.com/godfat/dm-mapping/tree/master
def storage_names(repository = :default)
select 'SHOW TABLES'
end
def truncate_table(table_name)
execute("TRUNCATE TABLE #{quote_name(table_name)};")
end
# copied from activerecord
def disable_referential_integrity
old = select("SELECT @@FOREIGN_KEY_CHECKS;")
begin
execute("SET FOREIGN_KEY_CHECKS = 0;")
yield
ensure
execute("SET FOREIGN_KEY_CHECKS = ?", *old)
end
end
end
module SqliteAdapterMethods
# taken from https://github.com/godfat/dm-mapping/tree/master
def storage_names(repository = :default)
# activerecord-2.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb: 177
sql = <<-SQL
SELECT name
FROM sqlite_master
WHERE type = 'table' AND NOT name = 'sqlite_sequence'
SQL
# activerecord-2.1.0/lib/active_record/connection_adapters/sqlite_adapter.rb: 181
select(sql)
end
def truncate_table(table_name)
execute("DELETE FROM #{quote_name(table_name)};")
if uses_sequence?
execute("DELETE FROM sqlite_sequence where name = '#{table_name}';")
end
end
# this is a no-op copied from activerecord
# i didn't find out if/how this is possible
# activerecord also doesn't do more here
def disable_referential_integrity
yield
end
private
# Returns a boolean indicating if the SQLite database is using the sqlite_sequence table.
def uses_sequence?
sql = <<-SQL
SELECT name FROM sqlite_master
WHERE type='table' AND name='sqlite_sequence'
SQL
select(sql).first
end
end
class SqliteAdapter; include SqliteAdapterMethods; end
class Sqlite3Adapter; include SqliteAdapterMethods; end
# FIXME
# i don't know if this works
# i basically just copied activerecord code to get a rough idea what they do.
# i don't have postgres available, so i won't be the one to write this.
# maybe codes below gets some postgres/datamapper user going, though.
class PostgresAdapter < DataObjectsAdapter
# taken from https://github.com/godfat/dm-mapping/tree/master
def storage_names(repository = :default)
sql = <<-SQL
SELECT table_name FROM "information_schema"."tables"
WHERE table_schema = current_schema() and table_type = 'BASE TABLE'
SQL
select(sql)
end
def truncate_table(table_name)
execute("TRUNCATE TABLE #{quote_name(table_name)} RESTART IDENTITY CASCADE;")
end
# override to use a single statement
def truncate_tables(table_names)
quoted_names = table_names.collect { |n| quote_name(n) }.join(', ')
execute("TRUNCATE TABLE #{quoted_names} RESTART IDENTITY;")
end
# FIXME
# copied from activerecord
def supports_disable_referential_integrity?
version = select("SHOW server_version")[0][0].split('.')
(version[0].to_i >= 8 && version[1].to_i >= 1) ? true : false
rescue
return false
end
# FIXME
# copied unchanged from activerecord
def disable_referential_integrity(repository = :default)
if supports_disable_referential_integrity? then
execute(storage_names(repository).collect do |name|
"ALTER TABLE #{quote_name(name)} DISABLE TRIGGER ALL"
end.join(";"))
end
yield
ensure
if supports_disable_referential_integrity? then
execute(storage_names(repository).collect do |name|
"ALTER TABLE #{quote_name(name)} ENABLE TRIGGER ALL"
end.join(";"))
end
end
end
end
end
module DatabaseCleaner
module DataMapper
class Truncation
include ::DatabaseCleaner::DataMapper::Base
include ::DatabaseCleaner::Generic::Truncation
def clean(repository = self.db)
adapter = ::DataMapper.repository(repository).adapter
adapter.disable_referential_integrity do
adapter.truncate_tables(tables_to_truncate(repository))
end
end
private
def tables_to_truncate(repository = self.db)
(@only || ::DataMapper.repository(repository).adapter.storage_names(repository)) - @tables_to_exclude
end
# overwritten
def migration_storage_names
%w[migration_info]
end
end
end
end

View file

@ -1,5 +0,0 @@
module DatabaseCleaner
module DataMapper
VERSION = "1.8.0"
end
end

View file

@ -1,33 +0,0 @@
require 'database_cleaner/data_mapper/base'
require 'database_cleaner/spec'
module DatabaseCleaner
RSpec.describe DataMapper do
it { is_expected.to respond_to(:available_strategies) }
it "has a default_strategy of transaction" do
expect(described_class.default_strategy).to eq(:transaction)
end
end
module DataMapper
class ExampleStrategy
include ::DatabaseCleaner::DataMapper::Base
end
RSpec.describe ExampleStrategy do
it_should_behave_like "a generic strategy"
it { is_expected.to respond_to(:db) }
it { is_expected.to respond_to(:db=) }
it "should store my desired db" do
subject.db = :my_db
expect(subject.db).to eq :my_db
end
it "should default to :default" do
expect(subject.db).to eq :default
end
end
end
end

View file

@ -1,22 +0,0 @@
require 'database_cleaner/data_mapper/transaction'
require 'database_cleaner/spec'
#require 'data_mapper'
module DatabaseCleaner
module DataMapper
RSpec.describe Transaction do
it_should_behave_like "a generic strategy"
it_should_behave_like "a generic transaction strategy"
describe "start" do
it "should start a transaction"
end
describe "clean" do
it "should finish a transaction"
end
end
end
end

View file

@ -1,25 +0,0 @@
require 'database_cleaner/data_mapper/truncation'
RSpec.describe DatabaseCleaner::DataMapper::Truncation do
let(:helper) { DataMapperHelper.new(:sqlite3) }
let(:connection) { helper.connection }
around do |example|
helper.setup
example.run
helper.teardown
end
describe "DM connection adapter monkeypatches" do
before { 2.times { User.create } }
describe "#truncate_table" do
it "truncates the table and resets AUTO_INCREMENT index of table" do
connection.truncate_table(User.storage_names[:default])
expect(User.count).to eq 0
expect(User.create.id).to eq 1
end
end
end
end

View file

@ -1,11 +0,0 @@
require 'database_cleaner/data_mapper/truncation'
require 'database_cleaner/spec'
module DatabaseCleaner
module DataMapper
RSpec.describe Truncation do
it_should_behave_like "a generic strategy"
it_should_behave_like "a generic truncation strategy"
end
end
end

View file

@ -1,15 +0,0 @@
require "bundler/setup"
require 'support/data_mapper_helper'
require "database_cleaner/data_mapper"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end

View file

@ -1,36 +0,0 @@
require 'database_cleaner/spec/database_helper'
require "data_mapper"
require "dm-sqlite-adapter"
class DataMapperHelper < DatabaseCleaner::Spec::DatabaseHelper
def setup
super
Kernel.const_set "User", Class.new
User.instance_eval do
include DataMapper::Resource
storage_names[:default] = 'users'
property :id, User::Serial
property :name, String
end
end
def teardown
Kernel.send :remove_const, "User" if defined?(User)
super
end
def connection
DataMapper.repository.adapter
end
private
def establish_connection(config = default_config)
DataMapper.setup(:default, config)
end
end

View file

@ -1,34 +0,0 @@
mysql:
adapter: mysql
database: database_cleaner_test
username: root
password:
host: 127.0.0.1
port: 3306
encoding: utf8
mysql2:
adapter: mysql2
database: database_cleaner_test
username: root
password:
host: 127.0.0.1
port: 3306
encoding: utf8
postgres:
adapter: postgresql
database: database_cleaner_test
username: postgres
password:
host: 127.0.0.1
encoding: unicode
template: template0
sqlite3:
adapter: sqlite3
database: tmp/database_cleaner_test.sqlite3
pool: 5
timeout: 5000
encoding: utf8

View file

@ -1,11 +0,0 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
# rspec failure tracking
.rspec_status

View file

@ -1,3 +0,0 @@
--format documentation
--color
--require spec_helper

View file

@ -1,4 +0,0 @@
language: ruby
rvm:
- 2.2.9
before_install: gem install bundler -v 1.17.2

View file

@ -1,8 +0,0 @@
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# Specify your gem's dependencies in database_cleaner-mongo.gemspec
gemspec
gem "database_cleaner", path: "../.."

View file

@ -1,46 +0,0 @@
PATH
remote: ../..
specs:
database_cleaner (1.8.2)
PATH
remote: .
specs:
database_cleaner-mongo (1.8.0)
database_cleaner (~> 1.8.0)
mongo
GEM
remote: https://rubygems.org/
specs:
bson (1.12.5)
diff-lcs (1.3)
mongo (1.12.5)
bson (= 1.12.5)
rake (10.4.2)
rspec (3.7.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-core (3.7.1)
rspec-support (~> 3.7.0)
rspec-expectations (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-mocks (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-support (3.7.1)
PLATFORMS
ruby
DEPENDENCIES
bundler (~> 1.16)
database_cleaner!
database_cleaner-mongo!
rake (~> 10.0)
rspec (~> 3.0)
BUNDLED WITH
1.17.3

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2009 Ben Mabey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,57 +0,0 @@
# Database Cleaner Adapter for Mongo
[![Build Status](https://travis-ci.org/DatabaseCleaner/database_cleaner-mongo.svg?branch=master)](https://travis-ci.org/DatabaseCleaner/database_cleaner-mongo)
[![Code Climate](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-mongo/badges/gpa.svg)](https://codeclimate.com/github/DatabaseCleaner/database_cleaner-mongo)
Clean your Mongo databases with Database Cleaner.
See https://github.com/DatabaseCleaner/database_cleaner for more information.
## Installation
```ruby
# Gemfile
group :test do
gem 'database_cleaner-mongo'
end
```
## Supported Strategies
<table>
<tbody>
<tr>
<th>Truncation</th>
<th>Transaction</th>
<th>Deletion</th>
</tr>
<tr>
<td> <b>Yes</b></td>
<td> No</td>
<td> No</td>
</tr>
</tbody>
</table>
(Default strategy is denoted in bold)
## Configuration options
<table>
<tbody>
<tr>
<th>ORM</th>
<th>How to access</th>
<th>Notes</th>
</tr>
<tr>
<td> Mongo</td>
<td> <code>DatabaseCleaner[:mongo]</code></td>
<td> </td>
</tr>
</tbody>
</table>
## COPYRIGHT
See [LICENSE] for details.

View file

@ -1,6 +0,0 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
task :default => :spec

View file

@ -1,14 +0,0 @@
#!/usr/bin/env ruby
require "bundler/setup"
require "database_cleaner/mongo"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start
require "irb"
IRB.start(__FILE__)

View file

@ -1,6 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle check || bundle install

View file

@ -1,30 +0,0 @@
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "database_cleaner/mongo/version"
Gem::Specification.new do |spec|
spec.name = "database_cleaner-mongo"
spec.version = DatabaseCleaner::Mongo::VERSION
spec.authors = ["Ernesto Tagwerker"]
spec.email = ["ernesto@ombulabs.com"]
spec.summary = "Strategies for cleaning databases using Mongo. Can be used to ensure a clean state for testing."
spec.description = "Strategies for cleaning databases using Mongo. Can be used to ensure a clean state for testing."
spec.homepage = "https://github.com/DatabaseCleaner/database_cleaner-mongo"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "database_cleaner", "~> 1.8.0"
spec.add_dependency "mongo"
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
end

View file

@ -1 +0,0 @@
require "database_cleaner/mongo"

View file

@ -1,10 +0,0 @@
require 'database_cleaner/mongo/version'
require 'database_cleaner'
require 'database_cleaner/mongo/truncation'
module DatabaseCleaner::Mongo
def self.default_strategy
:truncation
end
end

View file

@ -1,16 +0,0 @@
module DatabaseCleaner
module Mongo
def self.available_strategies
%w[truncation]
end
module Base
def db=(desired_db)
@db = desired_db
end
def db
@db || raise("You have not specified a database. (see Mongo::Database)")
end
end
end
end

View file

@ -1,62 +0,0 @@
require 'database_cleaner/mongo/base'
require 'database_cleaner/generic/truncation'
require 'database_cleaner/mongo/truncation_mixin'
module DatabaseCleaner
module Mongo
class Truncation
include ::DatabaseCleaner::Generic::Truncation
include TruncationMixin
include Base
private
def database
db
end
def collections_cache
@@collections_cache ||= {}
end
def mongoid_collection_names
@@mongoid_collection_names ||= Hash.new{|h,k| h[k]=[]}.tap do |names|
ObjectSpace.each_object(Class) do |klass|
(names[klass.db.name] << klass.collection_name) if valid_collection_name?(klass)
end
end
end
def not_caching(db_name, list)
@@not_caching ||= {}
unless @@not_caching.has_key?(db_name)
@@not_caching[db_name] = true
puts "Not caching collection names for db #{db_name}. Missing these from models: #{list}"
end
end
def collections
return collections_cache[database.name] if collections_cache.has_key?(database.name)
db_collections = database.collections.select { |c| c.name !~ /^system\./ }
missing_collections = mongoid_collection_names[database.name] - db_collections.map(&:name)
if missing_collections.empty?
collections_cache[database.name] = db_collections
else
not_caching(database.name, missing_collections)
end
db_collections
end
private
def valid_collection_name?(klass)
klass.ancestors.map(&:to_s).include?('Mongoid::Document') &&
!klass.embedded &&
!klass.collection_name.empty?
end
end
end
end

View file

@ -1,26 +0,0 @@
module DatabaseCleaner
module Mongo
module TruncationMixin
def clean
if @only
collections.each { |c| c.send(truncate_method_name) if @only.include?(c.name) }
else
collections.each { |c| c.send(truncate_method_name) unless @tables_to_exclude.include?(c.name) }
end
true
end
private
def collections
database.collections.select { |c| c.name !~ /^system\./ }
end
def truncate_method_name
# This constant only exists in the 2.x series.
defined?(::Mongo::VERSION) ? :delete_many : :remove
end
end
end
end

View file

@ -1,5 +0,0 @@
module DatabaseCleaner
module Mongo
VERSION = "1.8.0"
end
end

View file

@ -1,8 +0,0 @@
require 'database_cleaner/mongo'
RSpec.describe DatabaseCleaner::Mongo do
it "has a default_strategy of truncation" do
expect(described_class.default_strategy).to eq(:truncation)
end
end

View file

@ -1,26 +0,0 @@
module MongoTest
class Base
def self.collection
@connection ||= Mongo::Connection.new('127.0.0.1')
@db ||= @connection.db('database_cleaner_specs')
@collection ||= @db.collection(name) || @db.create_collection(name)
end
def self.count
@collection.count
end
def initialize(attrs={})
@attrs = attrs
end
def save!
self.class.collection.insert(@attrs)
end
end
class Widget < Base
end
class Gadget < Base
end
end

View file

@ -1,50 +0,0 @@
require 'mongo'
require 'database_cleaner/mongo/truncation'
require File.dirname(__FILE__) + '/mongo_examples'
RSpec.describe DatabaseCleaner::Mongo::Truncation do
around do |example|
connection = Mongo::Connection.new('127.0.0.1')
db_name = 'database_cleaner_specs'
db = connection.db(db_name)
subject.db = db
example.run
connection.drop_database(db_name)
end
before do
MongoTest::Widget.new(name: 'some widget').save!
MongoTest::Gadget.new(name: 'some gadget').save!
end
context "by default" do
it "truncates all collections" do
expect { subject.clean }.to change {
[MongoTest::Widget.count, MongoTest::Gadget.count]
}.from([1,1]).to([0,0])
end
end
context "when collections are provided to the :only option" do
subject { described_class.new(only: ['MongoTest::Widget']) }
it "only truncates the specified collections" do
expect { subject.clean }.to change {
[MongoTest::Widget.count, MongoTest::Gadget.count]
}.from([1,1]).to([0,1])
end
end
context "when collections are provided to the :except option" do
subject { described_class.new(except: ['MongoTest::Widget']) }
it "truncates all but the specified collections" do
expect { subject.clean }.to change {
[MongoTest::Widget.count, MongoTest::Gadget.count]
}.from([1,1]).to([1,0])
end
end
end

View file

@ -1,14 +0,0 @@
require "bundler/setup"
require "database_cleaner/mongo"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end

View file

@ -1,11 +0,0 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
# rspec failure tracking
.rspec_status

View file

@ -1,3 +0,0 @@
--format documentation
--color
--require spec_helper

View file

@ -1,4 +0,0 @@
language: ruby
rvm:
- 2.2.9
before_install: gem install bundler -v 1.17.2

View file

@ -1,8 +0,0 @@
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
# Specify your gem's dependencies in database_cleaner-mongo_mapper.gemspec
gemspec
gem "database_cleaner", path: "../.."

View file

@ -1,59 +0,0 @@
PATH
remote: ../..
specs:
database_cleaner (1.8.2)
PATH
remote: .
specs:
database_cleaner-mongo_mapper (1.8.1)
database_cleaner (~> 1.8.0)
mongo_mapper
GEM
remote: https://rubygems.org/
specs:
activemodel (3.0.20)
activesupport (= 3.0.20)
builder (~> 2.1.2)
i18n (~> 0.5.0)
activesupport (3.0.20)
bson (1.12.5)
builder (2.1.2)
diff-lcs (1.3)
i18n (0.5.4)
mongo (1.12.5)
bson (= 1.12.5)
mongo_mapper (0.12.0)
activemodel (~> 3.0)
activesupport (~> 3.0)
plucky (~> 0.5.2)
plucky (0.5.2)
mongo (~> 1.5)
rake (10.4.2)
rspec (3.7.0)
rspec-core (~> 3.7.0)
rspec-expectations (~> 3.7.0)
rspec-mocks (~> 3.7.0)
rspec-core (3.7.1)
rspec-support (~> 3.7.0)
rspec-expectations (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-mocks (3.7.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.7.0)
rspec-support (3.7.1)
PLATFORMS
ruby
DEPENDENCIES
bundler (~> 1.16)
database_cleaner!
database_cleaner-mongo_mapper!
rake (~> 10.0)
rspec (~> 3.0)
BUNDLED WITH
1.17.3

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2009 Ben Mabey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Some files were not shown because too many files have changed in this diff Show more