wd_sinatra_sequel 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 6a11c4dd4ad6e090b7e973a75aed1b3291ee5f4c
4
+ data.tar.gz: f2fbd979e35b83085d760ab34d06421212444261
5
+ SHA512:
6
+ metadata.gz: 53f9af3faa63a46792624b7020268e206759022330893dbc4d072d6ee7f89f909931c89eb3b3b4914f32581a282c2398c29b30bd52ad867da2cdc78e8fc01bad
7
+ data.tar.gz: 05d1475184bed030bb6279c221689862bc74a6b2ab36133c61dc0a65edab02328ed315ee503a8001236f03dffa959390dab9f89e2fdc7fe2597ec666945cc238
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in wd_sinatra_sequel.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Jack Chu
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # WdSinatraSequel
2
+
3
+ A Ruby gem to avoid reinventing the wheel every time you want to use
4
+ [Sequel](https://github.com/jeremyevans/sequel) in a
5
+ [WeaselDiesel](https://github.com/mattetti/Weasel-Diesel) app backed by
6
+ Sinatra ([wd_sinatra](https://github.com/mattetti/wd-sinatra)).
7
+
8
+ Use this gem to easily get connected to one or multiple databases and to
9
+ enjoy some of the common Sequel Rake tasks similar to those in Rails.
10
+
11
+
12
+ ## Installation
13
+
14
+ Add this line to your application's Gemfile:
15
+
16
+ gem 'wd_sinatra_sequel'
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install wd_sinatra_sequel
25
+
26
+
27
+ Don't forget to set a gem dependency for the DB adapter you need.
28
+ For instance:
29
+
30
+ mysql2
31
+
32
+
33
+ ## Usage
34
+
35
+ Add an Sequel `database.yml` file in your config folder and then require this
36
+ gem in your `app.rb` file and connect to the DB:
37
+
38
+ require 'wd_sinatra_sequel'
39
+ DB = WdSinatraSequel::DBConnector.set_db_connection
40
+
41
+
42
+ The DB settings can be accessed via:
43
+
44
+ DBConnector::DB_CONFIG[RACK_ENV]
45
+
46
+ ## Rake tasks
47
+
48
+ A Rake task file is also provided so you can load Sequel specific
49
+ tasks. To do that, create a new rake file in your `lib/tasks` folder, load
50
+ `WDSinatra` and the rake task file:
51
+
52
+ ```
53
+ $ echo "require 'wd_sinatra_sequel'
54
+ load WdSinatraSequel.task_path" > lib/tasks/db.rake
55
+ ```
56
+
57
+ The tasks are very basic, feel free to send patches and improvements.
58
+
59
+ ## Contributing
60
+
61
+ 1. Fork it
62
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
63
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
64
+ 4. Push to the branch (`git push origin my-new-feature`)
65
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,260 @@
1
+ require 'wd_sinatra_sequel'
2
+ require 'pry'
3
+
4
+ db_namespace = namespace :db do
5
+
6
+ task :load_config => :setup_app do
7
+ require 'sequel'
8
+ @config = WdSinatraSequel::DBConnector.db_configuration
9
+ if @config['uri']
10
+ opts = Sequel.connect(@config['uri'], @config).opts
11
+ %w{adapter host port user password database}.each do |k|
12
+ @config[k] = opts[k.to_sym]
13
+ end
14
+ end
15
+ @migrations_path = File.join(WDSinatra::AppLoader.root_path, 'db/migrate')
16
+ end
17
+
18
+ desc 'Create the database from config/database.yml for the current RACK_ENV (use db:create:all to create all dbs in the config)'
19
+ task :create do
20
+ old_connect_env = ENV['DONT_CONNECT'] ? 'true' : nil
21
+ ENV['DONT_CONNECT'] = 'true'
22
+ Rake::Task["db:load_config"].invoke
23
+ create_database(@config)
24
+ ENV['DONT_CONNECT'] = old_connect_env
25
+ end
26
+
27
+ def create_database(config)
28
+ begin
29
+ if config['adapter'] =~ /sqlite/
30
+ if File.exist?(config['database'])
31
+ $stderr.puts "#{config['database']} already exists"
32
+ else
33
+ begin
34
+ # Create the SQLite database
35
+ Sequel.connect(config)
36
+ rescue Exception => e
37
+ $stderr.puts e, *(e.backtrace)
38
+ $stderr.puts "Couldn't create database for #{config.inspect}"
39
+ end
40
+ end
41
+ return # Skip the else clause of begin/rescue
42
+ else
43
+ Sequel.connect(config, test: true)
44
+
45
+ end
46
+ rescue
47
+ case config['adapter']
48
+ when /mysql/
49
+ if config['adapter'] =~ /jdbc/
50
+ error_class = Sequel::DatabaseConnectionError
51
+ else
52
+ error_class = config['adapter'] =~ /mysql2/ ? Mysql2::Error : Mysql::Error
53
+ end
54
+ access_denied_error = 1045
55
+
56
+ charset = ENV['CHARSET'] || 'utf8'
57
+ collation = ENV['COLLATION'] || 'utf8_unicode_ci'
58
+
59
+ begin
60
+ arguments = mysql_cli_args(config)
61
+ arguments << '-e'
62
+ arguments << "CREATE DATABASE #{config['database']} DEFAULT CHARACTER SET #{charset} DEFAULT COLLATE #{collation}"
63
+
64
+ system('mysql',*arguments)
65
+ Sequel.connect(config)
66
+ rescue error_class => sqlerr
67
+ if sqlerr.errno == access_denied_error
68
+ print "#{sqlerr.error}. \nPlease provide the root password for your mysql installation\n>"
69
+ root_password = $stdin.gets.strip
70
+ grant_statement = "GRANT ALL PRIVILEGES ON #{config['database']}.* " \
71
+ "TO '#{config['user']}'@'localhost' " \
72
+ "IDENTIFIED BY '#{config['password']}' WITH GRANT OPTION;"
73
+ system('mysql', '-u', 'root', '--password', root_password, '-h', config['host'], '-e', grant_statement)
74
+ system('mysql',*arguments)
75
+ Sequel.connect(config)
76
+ else
77
+ $stderr.puts sqlerr.error
78
+ $stderr.puts "Couldn't create database for #{config.inspect}, charset: #{config['charset'] || charset}, collation: #{config['collation'] || collation}"
79
+ $stderr.puts "(if you set the charset manually, make sure you have a matching collation)" if config['charset']
80
+ end
81
+ end
82
+ when /postgres/
83
+ encoding = config['encoding'] || ENV['CHARSET'] || 'utf8'
84
+ begin
85
+ system("createdb", "-E", encoding, "-h", config['host'], "-U", config['user'], config['database'])
86
+ Sequel.connect(config)
87
+ rescue Exception => e
88
+ $stderr.puts e, *(e.backtrace)
89
+ $stderr.puts "Couldn't create database for #{config.inspect}"
90
+ end
91
+ end
92
+ else
93
+ # Bug with 1.9.2 Calling return within begin still executes else
94
+ $stderr.puts "#{config['database']} already exists" unless config['adapter'] =~ /sqlite/
95
+ end
96
+ end
97
+
98
+ desc 'Drops the database for the current RACK_ENV (use db:drop:all to drop all databases)'
99
+ task :drop do
100
+ Rake::Task["db:load_config"].invoke
101
+ begin
102
+ drop_database(@config)
103
+ rescue Exception => e
104
+ $stderr.puts "Couldn't drop #{@config['database']} : #{e.inspect}"
105
+ end
106
+ end
107
+
108
+ def local_database?(config, &block)
109
+ if config['host'].in?(['127.0.0.1', 'localhost']) || config['host'].blank?
110
+ yield
111
+ else
112
+ $stderr.puts "This task only modifies local databases. #{config['database']} is on a remote host."
113
+ end
114
+ end
115
+
116
+ desc "Migrate the database"
117
+ task :migrate do
118
+ Rake::Task[:environment].invoke
119
+ Rake::Task["db:load_config"].invoke
120
+ Sequel.extension :migration
121
+ db = Sequel.connect(@config)
122
+ Sequel::Migrator.run(db, @migrations_path)
123
+ db_namespace["schema:dump"].invoke
124
+ end
125
+
126
+ namespace :migrate do
127
+ # desc 'Rollbacks the database one migration and re migrate up (options: VERSION=x).'
128
+ task :redo => [:environment, :load_config] do
129
+ if ENV['VERSION']
130
+ db_namespace['migrate:to'].invoke
131
+ else
132
+ db_namespace['rollback'].invoke
133
+ end
134
+ db_namespace['migrate'].invoke
135
+ end
136
+
137
+ # desc 'Resets your database using your migrations for the current environment'
138
+ task :reset => ['db:drop', 'db:create', 'db:migrate']
139
+
140
+ # desc 'Runs the "to" for a given migration VERSION.'
141
+ task :to, [:version] => [:environment, :load_config] do |t, args|
142
+ version = (args[:version] || ENV['VERSION']).to_s.strip
143
+ raise 'VERSION is required' unless version
144
+ Sequel.extension :migration
145
+ db = Sequel.connect(@config)
146
+ Sequel::Migrator.run(db, @migrations_path, :target => version)
147
+ db_namespace['schema:dump'].invoke
148
+ end
149
+ end
150
+
151
+ desc 'Rolls the schema back (erase all data).'
152
+ task :rollback => [:environment, :load_config] do
153
+ Sequel.extension :migration
154
+ db = Sequel.connect(@config)
155
+ Sequel::Migrator.run(db, @migrations_path, :target => 0)
156
+ db_namespace['schema:dump'].invoke
157
+ end
158
+
159
+ # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
160
+ task :reset => [ 'db:drop', 'db:setup' ]
161
+
162
+ # desc "Raises an error if there are pending migrations"
163
+ task :abort_if_pending_migrations => [:environment, :setup_app, :load_config] do
164
+ if defined? Sequel
165
+ Sequel.extension :migration
166
+ db = Sequel.connect(@config)
167
+
168
+ if Sequel::Migrator.is_current?(db, @migrations_path)
169
+ puts "You have pending migrations."
170
+ abort %{Run "rake db:migrate" to update your database then try again.}
171
+ end
172
+ end
173
+ end
174
+
175
+ desc 'Create the database, and initialize with the seed data (use db:reset to also drop the db first)'
176
+ task :setup => [ 'db:create', 'db:seed' ]
177
+
178
+ desc 'Load the seed data from db/seeds.rb'
179
+ task :seed do
180
+ old_no_redis = ENV['NO_REDIS'] ? 'true' : nil
181
+ ENV['NO_REDIS'] = 'true'
182
+ Rake::Task[:environment].invoke
183
+ Rake::Task["db:abort_if_pending_migrations"].invoke
184
+ seed = File.join(WDSinatra::AppLoader.root_path, "db", "seed.rb")
185
+ if File.exist?(seed)
186
+ puts "seeding #{seed}"
187
+ load seed
188
+ else
189
+ puts "Seed file: #{seed} is missing"
190
+ end
191
+ ENV['NO_REDIS'] = old_no_redis
192
+ end
193
+
194
+ namespace :schema do
195
+ desc 'Create a db/schema.rb file that can be portably used against any DB supported by AR'
196
+ task :dump => :load_config do
197
+ Sequel.extension :schema_dumper
198
+ db = Sequel.connect(@config)
199
+ filename = ENV['SCHEMA'] || "#{WDSinatra::AppLoader.root_path}/db/schema.rb"
200
+ File.open(filename, "w:utf-8") do |file|
201
+ file.write(db.dump_schema_migration)
202
+ end
203
+ db_namespace['schema:dump'].reenable
204
+ end
205
+
206
+ desc 'Load a schema.rb file into the database'
207
+ task :load => [:environment, :load_config] do
208
+ Sequel.extension :schema_dumper
209
+ Sequel.extension :migration
210
+ db = Sequel.connect(@config)
211
+ file = ENV['SCHEMA'] || "#{WDSinatra::AppLoader.root_path}/db/schema.rb"
212
+ if File.exists?(file)
213
+ load(file)
214
+ else
215
+ abort %{#{file} doesn't exist yet. Run "rake db:migrate" to create it then try again. If you do not intend to use a database, you should instead alter #{WDSinatra::AppLoader.root_path}/config/application.rb to limit the frameworks that will be loaded}
216
+ end
217
+ end
218
+ end
219
+
220
+ namespace :test do
221
+ # desc "Empty the test database"
222
+ task :purge => :setup_app do
223
+ ENV['RACK_ENV'] = 'test'
224
+ Rake::Task["db:load_config"].invoke
225
+ drop_database(@config)
226
+ create_database(@config)
227
+ end
228
+ end
229
+ end
230
+
231
+ def mysql_cli_args(config)
232
+ arguments = ["--user=#{config['user']}"]
233
+ arguments << "--password=#{config['password']}" if config['password']
234
+
235
+ unless %w[127.0.0.1 localhost].include?(config['host'])
236
+ arguments << "--host=#{config['host']}"
237
+ end
238
+ arguments
239
+ end
240
+
241
+ def drop_database(config)
242
+ case config['adapter']
243
+ when /mysql/
244
+ arguments = mysql_cli_args(config)
245
+ arguments << '-e'
246
+ arguments << "DROP DATABASE IF EXISTS #{config['database']}"
247
+
248
+ system('mysql',*arguments)
249
+ when /sqlite/
250
+ require 'pathname'
251
+ path = Pathname.new(config['database'])
252
+ file = path.absolute? ? path.to_s : File.join(WDSinatra::AppLoader.root_path, path)
253
+
254
+ FileUtils.rm(file) if File.exist?(file)
255
+ when /postgres/
256
+ system("dropdb", "-h", config['host'], "-U", config['user'], config['database'])
257
+ else
258
+ raise "Task not supported by '#{config['adapter']}'"
259
+ end
260
+ end
@@ -0,0 +1,3 @@
1
+ module WdSinatraSequel
2
+ VERSION = "0.0.1"
3
+ end
@@ -0,0 +1,85 @@
1
+ require "wd_sinatra_sequel/version"
2
+ require 'sequel'
3
+
4
+ # Set the default value, feel free to overwrite
5
+ Sequel.default_timezone = :utc
6
+
7
+
8
+ module WdSinatraSequel
9
+
10
+ # Path to the rake task file so it can be loaded as such:
11
+ # load WdSinatraSequel.task_path
12
+ # (Note that the app loaded should have been started using something like:
13
+ # WDSinatra::AppLoader.console(RAKE_APP_ROOT)
14
+ # before loading this rake task.)
15
+ def self.task_path
16
+ File.join(File.expand_path(File.dirname(__FILE__), ".."), "wd_sinatra_sequel", "db.rake")
17
+ end
18
+
19
+ ##### DB Connection ########
20
+ module DBConnector
21
+ DB_CONFIG = YAML.load_file(File.join(WDSinatra::AppLoader.root_path, "config", "database.yml"))
22
+
23
+ module_function
24
+
25
+ def set_db_connection(env=RACK_ENV)
26
+ # Set the Sequel logger
27
+ loggers = []
28
+ if Object.const_defined?(:LOGGER)
29
+ loggers << LOGGER
30
+ else
31
+ loggers << Logger.new($stdout)
32
+ end
33
+
34
+ # Establish the DB connection
35
+ db_file = File.join(WDSinatra::AppLoader.root_path, "config", "database.yml")
36
+ if File.exist?(db_file)
37
+ hash_settings = YAML.load_file(db_file)
38
+ if hash_settings && hash_settings[env]
39
+ @db_configurations = hash_settings
40
+ @db_configuration = @db_configurations[env]
41
+ # add loggers
42
+ @db_configuration['loggers'] ||= []
43
+ @db_configuration['loggers'].concat(loggers)
44
+ # overwrite DB name by using an ENV variable
45
+ if ENV['FORCED_DB_NAME']
46
+ print "Database name overwritten to be #{ENV['FORCED_DB_NAME']}\n"
47
+ @db_configurations[env]['database'] = @db_configuration['database'] = ENV['FORCED_DB_NAME']
48
+ end
49
+ connect_to_db unless ENV['DONT_CONNECT']
50
+ else
51
+ raise "#{db_file} doesn't have an entry for the #{env} environment"
52
+ end
53
+ else
54
+ raise "#{db_file} file missing, can't connect to the DB"
55
+ end
56
+ end
57
+
58
+ def db_configuration(env=RACK_ENV)
59
+ old_connect_status = ENV['DONT_CONNECT']
60
+ set_db_connection(env)
61
+ ENV['DONT_CONNECT'] = old_connect_status
62
+ @db_configuration
63
+ end
64
+
65
+ def db_configurations
66
+ db_configuration unless @db_configurations
67
+ @db_configurations
68
+ end
69
+
70
+ def connect_to_db
71
+ if @db_configuration
72
+ if @db_configuration.has_key?('uri')
73
+ uri = @db_configuration['uri']
74
+ config_without_uri = @db_configuration.clone
75
+ config_without_uri.delete('uri')
76
+ connection = Sequel.connect(uri, config_without_uri)
77
+ else
78
+ connection = Sequel.connect(@db_configuration)
79
+ end
80
+ else
81
+ raise "Can't connect without the config previously set"
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,23 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'wd_sinatra_sequel/version'
5
+
6
+ Gem::Specification.new do |gem|
7
+ gem.name = "wd_sinatra_sequel"
8
+ gem.version = WdSinatraSequel::VERSION
9
+ gem.authors = ["Jack Chu"]
10
+ gem.email = ["kamuigt@gmail.com"]
11
+ gem.description = %q{Basics to use Sequel with WD Sinatra.}
12
+ gem.summary = %q{Provides a way to get started with Sequel and WeaselDiesel on Sinatra.}
13
+ gem.homepage = ""
14
+
15
+ gem.files = `git ls-files`.split($/)
16
+ gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17
+ gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18
+ gem.require_paths = ["lib"]
19
+
20
+ gem.add_development_dependency "pry"
21
+
22
+ gem.add_dependency "sequel"
23
+ end
metadata ADDED
@@ -0,0 +1,81 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: wd_sinatra_sequel
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Jack Chu
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2013-04-26 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: pry
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - '>='
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - '>='
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: sequel
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Basics to use Sequel with WD Sinatra.
42
+ email:
43
+ - kamuigt@gmail.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - .gitignore
49
+ - Gemfile
50
+ - LICENSE.txt
51
+ - README.md
52
+ - Rakefile
53
+ - lib/wd_sinatra_sequel.rb
54
+ - lib/wd_sinatra_sequel/db.rake
55
+ - lib/wd_sinatra_sequel/version.rb
56
+ - wd_sinatra_sequel.gemspec
57
+ homepage: ''
58
+ licenses: []
59
+ metadata: {}
60
+ post_install_message:
61
+ rdoc_options: []
62
+ require_paths:
63
+ - lib
64
+ required_ruby_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - '>='
72
+ - !ruby/object:Gem::Version
73
+ version: '0'
74
+ requirements: []
75
+ rubyforge_project:
76
+ rubygems_version: 2.0.3
77
+ signing_key:
78
+ specification_version: 4
79
+ summary: Provides a way to get started with Sequel and WeaselDiesel on Sinatra.
80
+ test_files: []
81
+ has_rdoc: