fredwu-sequel-rails 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,83 @@
1
+ # sequel-rails
2
+
3
+ This gem provides the railtie that allows [sequel(https://github.com/jeremyevans/sequel) to hook into [rails3](https://github.com/rails/rails) and thus behave like a rails framework component. Just like activerecord does in rails, [sequel-rails](https://github.com/fredwu/sequel-rails) uses the railtie API to hook into rails. The two are actually hooked into rails almost identically.
4
+
5
+ The code for this gem was initially taken from the excellent [dm-rails](https://github.com/datamapper/dm-rails) project.
6
+
7
+ ## Using sequel-rails
8
+
9
+ Using sequel with rails3 requires a couple minor changes.
10
+
11
+ First, add the following to your Gemfile:
12
+
13
+ gem 'fredwu-sequel-rails'
14
+
15
+ Be sure to run `bundle install` if needed!
16
+
17
+ Secondly, you'll need to require "sequel-rails/railtie" in your `config/application.rb` file, and not require "activerecord". The top of your config/application.rb will probably look something like:
18
+
19
+ # require 'rails/all'
20
+
21
+ # instead of 'rails/all', require these:
22
+ require 'action_controller/railtie'
23
+ require 'sequel-rails/railtie
24
+ require 'action_mailer/railtie
25
+ require 'active_resource/railtie'
26
+
27
+ After those changes, you should be good to go!
28
+
29
+
30
+ ## Available sequel specific rake tasks
31
+
32
+ To get a list of all available rake tasks in your rails3 app, issue the usual
33
+
34
+ rake -T
35
+
36
+ Once you do that, you will see the following rake tasks among others. These are the ones that sequel-rails added for us.
37
+
38
+ rake db:create # Create the database(s) defined in config/database.yml for the current Rails.env - also creates the test database(s) if Rails.env.development?
39
+ rake db:create:all # Create all the local databases defined in config/database.yml
40
+ rake db:drop # Drops the database(s) for the current Rails.env - also drops the test database(s) if Rails.env.development?
41
+ rake db:drop:all # Drop all the local databases defined in config/database.yml
42
+ rake db:migrate # Migrate the database to the latest version
43
+ rake db:migrate:down[version] # Migrate down using migrations
44
+ rake db:migrate:up[version] # Migrate up using migrations
45
+ rake db:seed # Load the seed data from db/seeds.rb
46
+ rake db:sessions:clear # Clear the sessions table for SequelStore
47
+ rake db:sessions:create # Creates the sessions table for SequelStore
48
+ rake db:setup # Create the database, load the schema, and initialize with the seed data
49
+
50
+
51
+ ## TODOs
52
+
53
+ * Add tests
54
+
55
+
56
+ ## Credits
57
+
58
+ The [dm-rails](https://github.com/datamapper/dm-rails) team wrote most of this code, I just sequel-ized it.
59
+
60
+
61
+ ## Note on Patches/Pull Requests
62
+
63
+ * Fork the project.
64
+ * Make your feature addition or bug fix.
65
+ * Add tests for it. This is important so I don't break it in a future version unintentionally.
66
+ * Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
67
+ * Send me a pull request. Bonus points for topic branches.
68
+
69
+
70
+ ## The sequel-rails team
71
+
72
+ * Brasten Sager (brasten)
73
+
74
+
75
+ ## Fork Contributors
76
+
77
+ * [Fred Wu](https://github.com/fredwu)
78
+
79
+
80
+ ## Copyright
81
+
82
+ * Copyright (c) 2009-2011 The sequel-rails team. See [LICENSE](https://github.com/brasten/sequel-rails/blob/master/LICENSE) for details.
83
+ * Copyright (c) 2011 The sequel-rails team. Fork released under the [MIT](http://www.opensource.org/licenses/mit-license.php) license.
@@ -0,0 +1,83 @@
1
+ require 'rails/generators/named_base'
2
+ require 'rails/generators/migration'
3
+ require 'rails/generators/active_model'
4
+
5
+ module Sequel
6
+ module Generators
7
+
8
+ class Base < ::Rails::Generators::NamedBase #:nodoc:
9
+
10
+ include ::Rails::Generators::Migration
11
+
12
+ def self.source_root
13
+ @_sequel_source_root ||=
14
+ File.expand_path("../#{base_name}/#{generator_name}/templates", __FILE__)
15
+ end
16
+
17
+ protected
18
+
19
+ # Sequel does not care if migrations have the same name as long as
20
+ # they have different ids.
21
+ #
22
+ def migration_exists?(dirname, file_name) #:nodoc:
23
+ false
24
+ end
25
+
26
+ # Implement the required interface for Rails::Generators::Migration.
27
+ #
28
+ def self.next_migration_number(dirname) #:nodoc:
29
+ next_migration_number = current_migration_number(dirname) + 1
30
+ [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % next_migration_number].max
31
+ end
32
+
33
+ end
34
+
35
+ class ActiveModel < ::Rails::Generators::ActiveModel #:nodoc:
36
+ def self.all(klass)
37
+ "#{klass}.all"
38
+ end
39
+
40
+ def self.find(klass, params=nil)
41
+ "#{klass}.get(#{params})"
42
+ end
43
+
44
+ def self.build(klass, params=nil)
45
+ if params
46
+ "#{klass}.new(#{params})"
47
+ else
48
+ "#{klass}.new"
49
+ end
50
+ end
51
+
52
+ def save
53
+ "#{name}.save"
54
+ end
55
+
56
+ def update_attributes(params=nil)
57
+ "#{name}.update(#{params})"
58
+ end
59
+
60
+ def errors
61
+ "#{name}.errors"
62
+ end
63
+
64
+ def destroy
65
+ "#{name}.destroy"
66
+ end
67
+ end
68
+
69
+ end
70
+ end
71
+
72
+ module Rails
73
+
74
+ module Generators
75
+ class GeneratedAttribute #:nodoc:
76
+ def type_class
77
+ return 'DateTime' if type.to_s == 'datetime'
78
+ return type.to_s.camelcase
79
+ end
80
+ end
81
+ end
82
+
83
+ end
@@ -0,0 +1,30 @@
1
+ require 'generators/sequel'
2
+
3
+ module Sequel
4
+ module Generators
5
+
6
+ class MigrationGenerator < Base
7
+
8
+ argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
9
+ class_option :id, :type => :numeric, :desc => "The id to be used in this migration"
10
+
11
+ def create_migration_file
12
+ set_local_assigns!
13
+ migration_template "migration.rb", "db/migrate/#{file_name}.rb"
14
+ end
15
+
16
+ protected
17
+
18
+ attr_reader :migration_action
19
+
20
+ def set_local_assigns!
21
+ if file_name =~ /^(add|remove|drop)_.*_(?:to|from)_(.*)/
22
+ @migration_action = $1 == 'add' ? 'add' : 'drop'
23
+ @table_name = $2.pluralize
24
+ end
25
+ end
26
+
27
+ end
28
+
29
+ end
30
+ end
@@ -0,0 +1,16 @@
1
+ class <%= migration_file_name.camelize %>Migration < Sequel::Migration
2
+
3
+ def up
4
+ create_table :<%= table_name %> do
5
+ primary_key :id
6
+ <% attributes.each do |attribute| -%>
7
+ <%= attribute.type_class %> :<%= attribute.name %>
8
+ <% end -%>
9
+ end
10
+ end
11
+
12
+ def down
13
+ drop_table :<%= table_name %>
14
+ end
15
+
16
+ end
@@ -0,0 +1,23 @@
1
+ require 'generators/sequel'
2
+
3
+ module Sequel
4
+ module Generators
5
+
6
+ class ModelGenerator < Base
7
+ argument :attributes, :type => :array, :default => [], :banner => "field:type field:type"
8
+
9
+ check_class_collision
10
+
11
+ class_option :timestamps, :type => :boolean
12
+ class_option :parent, :type => :string, :desc => "The parent class for the generated model"
13
+
14
+ def create_model_file
15
+ template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb")
16
+ end
17
+
18
+ hook_for :test_framework
19
+
20
+ end
21
+
22
+ end
23
+ end
@@ -0,0 +1,3 @@
1
+ class <%= class_name %><%= options[:parent] ? " < #{options[:parent].classify}" : " < Sequel::Model" %>
2
+
3
+ end
@@ -0,0 +1,19 @@
1
+ require 'generators/sequel'
2
+
3
+ module Sequel
4
+ module Generators
5
+
6
+ class ObserverGenerator < Base
7
+
8
+ check_class_collision :suffix => "Observer"
9
+
10
+ def create_observer_file
11
+ template 'observer.rb', File.join('app/models', class_path, "#{file_name}_observer.rb")
12
+ end
13
+
14
+ hook_for :test_framework
15
+
16
+ end
17
+
18
+ end
19
+ end
@@ -0,0 +1,7 @@
1
+ class <%= class_name %>Observer
2
+
3
+ include Sequel::Observer
4
+
5
+ observe <%= class_name %>
6
+
7
+ end
@@ -0,0 +1 @@
1
+ require 'sequel-rails/railtie'
@@ -0,0 +1,61 @@
1
+ require 'active_support/core_ext/hash/except'
2
+ require 'active_support/core_ext/class/attribute_accessors'
3
+
4
+ module Rails
5
+ module Sequel
6
+
7
+ mattr_accessor :configuration
8
+
9
+ class Configuration
10
+
11
+ def self.for(root, database_yml_hash)
12
+ Rails::Sequel.configuration ||= new(root, database_yml_hash)
13
+ end
14
+
15
+ attr_reader :root, :raw
16
+ attr_accessor :logger
17
+ attr_accessor :migration_dir
18
+
19
+ def environment_for(name)
20
+ environments[name.to_s] || environments[name.to_sym]
21
+ end
22
+
23
+ def environments
24
+ @environments ||= @raw.inject({}) do |normalized, environment|
25
+ name, config = environment.first, environment.last
26
+ normalized[name] = normalize_repository_config(config)
27
+ normalized
28
+ end
29
+ end
30
+
31
+ private
32
+
33
+ def initialize(root, database_yml_hash)
34
+ @root, @raw = root, database_yml_hash
35
+ end
36
+
37
+ def normalize_repository_config(hash)
38
+ config = {}
39
+ hash.each do |key, value|
40
+ config[key.to_s] =
41
+ if key.to_s == 'port'
42
+ value.to_i
43
+ elsif key.to_s == 'adapter' && value == 'sqlite3'
44
+ 'sqlite'
45
+ elsif key.to_s == 'database' && (hash['adapter'] == 'sqlite3' ||
46
+ hash['adapter'] == 'sqlite' ||
47
+ hash[:adapter] == 'sqlite3' ||
48
+ hash[:adapter] == 'sqlite')
49
+ value == ':memory:' ? value : File.expand_path((hash['database'] || hash[:database]), root)
50
+ else
51
+ value
52
+ end
53
+ end
54
+
55
+ config
56
+ end
57
+
58
+ end
59
+
60
+ end
61
+ end
@@ -0,0 +1,30 @@
1
+ require 'sequel/extensions/migration'
2
+
3
+ module Rails
4
+ module Sequel
5
+ class Migrations
6
+
7
+ class << self
8
+
9
+ def migrate_up!(version=nil)
10
+ opts = {}
11
+ opts[:target] = version.to_i if version
12
+
13
+
14
+
15
+ ::Sequel::Migrator.run(::Sequel::Model.db, "db/migrate", opts)
16
+ end
17
+
18
+ def migrate_down!(version=nil)
19
+ opts = {}
20
+ opts[:target] = version.to_i if version
21
+
22
+ ::Sequel::Migrator.run(::Sequel::Model.db, "db/migrate", opts)
23
+ end
24
+
25
+ end
26
+
27
+
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,90 @@
1
+ require 'sequel'
2
+
3
+ require 'rails'
4
+ require 'active_model/railtie'
5
+
6
+ # Comment taken from active_record/railtie.rb
7
+ #
8
+ # For now, action_controller must always be present with
9
+ # rails, so let's make sure that it gets required before
10
+ # here. This is needed for correctly setting up the middleware.
11
+ # In the future, this might become an optional require.
12
+ require 'action_controller/railtie'
13
+
14
+ require 'sequel-rails/setup'
15
+ require "sequel-rails/railties/log_subscriber"
16
+ require "sequel-rails/railties/i18n_support"
17
+
18
+
19
+ module Rails
20
+ module Sequel
21
+
22
+ class Railtie < Rails::Railtie
23
+
24
+ ::Sequel::Railties::LogSubscriber.attach_to :sequel
25
+
26
+ config.generators.orm :sequel, :migration => true
27
+ config.rails_fancy_pants_logging = true
28
+
29
+ rake_tasks do
30
+ load 'sequel-rails/railties/database.rake'
31
+ end
32
+
33
+ initializer 'sequel.configuration' do |app|
34
+ configure_sequel(app)
35
+ end
36
+
37
+ initializer 'sequel.logger' do |app|
38
+ setup_logger(app, Rails.logger)
39
+ end
40
+
41
+ initializer 'sequel.i18n_support' do |app|
42
+ setup_i18n_support(app)
43
+ end
44
+
45
+ # Expose database runtime to controller for logging.
46
+ initializer "sequel.log_runtime" do |app|
47
+ setup_controller_runtime(app)
48
+ end
49
+
50
+ initializer "sequel.connect" do |app|
51
+ Rails::Sequel.setup(Rails.env)
52
+ end
53
+
54
+ # Run setup code after_initialize to make sure all config/initializers
55
+ # are in effect once we setup the connection. This is especially necessary
56
+ # for the cascaded adapter wrappers that need to be declared before setup.
57
+
58
+ config.after_initialize do |app|
59
+ ::Sequel::Model.plugin :active_model
60
+ ::Sequel::Model.plugin :validation_helpers
61
+
62
+ ::Sequel::Model.raise_on_save_failure = false
63
+ end
64
+
65
+
66
+ # Support overwriting crucial steps in subclasses
67
+
68
+ def configure_sequel(app)
69
+ app.config.sequel = Rails::Sequel::Configuration.for(
70
+ Rails.root, app.config.database_configuration
71
+ )
72
+ end
73
+
74
+ def setup_i18n_support(app)
75
+ ::Sequel::Model.send :include, Rails::Sequel::I18nSupport
76
+ end
77
+
78
+ def setup_controller_runtime(app)
79
+ require "sequel-rails/railties/controller_runtime"
80
+ ActionController::Base.send :include, Rails::Sequel::Railties::ControllerRuntime
81
+ end
82
+
83
+ def setup_logger(app, logger)
84
+ app.config.sequel.logger=logger
85
+ end
86
+
87
+ end
88
+
89
+ end
90
+ end
@@ -0,0 +1,23 @@
1
+ module Sequel
2
+ module Adapters
3
+ module Benchmarking
4
+
5
+ %w[ create read update delete ].each do |method|
6
+ class_eval <<-RUBY, __FILE__, __LINE__
7
+ def #{method}(*args, &block)
8
+ result = nil
9
+ @runtime ||= 0
10
+ @runtime += Benchmark.ms { result = super(*args, &block) }
11
+ result
12
+ end
13
+ RUBY
14
+ end
15
+
16
+ def reset_runtime
17
+ rt, @runtime = @runtime, 0
18
+ rt.to_f
19
+ end
20
+
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,43 @@
1
+ require 'active_support/core_ext/module/attr_internal'
2
+
3
+ module Rails
4
+ module Sequel
5
+ module Railties
6
+
7
+ module ControllerRuntime
8
+
9
+ extend ActiveSupport::Concern
10
+
11
+ protected
12
+
13
+ attr_internal :db_runtime
14
+
15
+ def cleanup_view_runtime
16
+ db_rt_before_render = ::Rails::Sequel.reset_runtime
17
+ runtime = super
18
+ db_rt_after_render = ::Rails::Sequel.reset_runtime
19
+ self.db_runtime = db_rt_before_render + db_rt_after_render
20
+ runtime - db_rt_after_render
21
+ end
22
+
23
+ def append_info_to_payload(payload)
24
+ super
25
+ payload[:db_runtime] = db_runtime
26
+ end
27
+
28
+
29
+ module ClassMethods
30
+
31
+ def log_process_action(payload)
32
+ messages, db_runtime = super, payload[:db_runtime]
33
+ messages << ("Models: %.1fms" % db_runtime.to_f) if db_runtime
34
+ messages
35
+ end
36
+
37
+ end
38
+
39
+ end
40
+
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,148 @@
1
+ # TODO: DRY these up
2
+ namespace :db do
3
+ namespace :schema do
4
+ desc "Create a db/schema.rb file that can be portably used against any DB supported by Sequel"
5
+ task :dump do
6
+ Sequel.extension :schema_dumper
7
+ db = Sequel.connect(Rails.configuration.database_configuration[Rails.env])
8
+ File.open(ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb", "w") do |file|
9
+ file.write(db.dump_schema_migration)
10
+ end
11
+ Rake::Task["db:schema:dump"].reenable
12
+ end
13
+
14
+ desc "Load a schema.rb file into the database"
15
+ task :load, :needs => :environment do
16
+ require 'sequel-rails/storage'
17
+ Rails::Sequel::Storage.new(Rails.env).create
18
+
19
+ file = ENV['SCHEMA'] || "#{Rails.root}/db/schema.rb"
20
+ if File.exists?(file)
21
+ load(file)
22
+ else
23
+ 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 #{Rails.root}/config/boot.rb to limit the frameworks that will be loaded}
24
+ end
25
+ end
26
+ end
27
+
28
+ namespace :create do
29
+ desc 'Create all the local databases defined in config/database.yml'
30
+ task :all, :needs => :environment do
31
+ require 'sequel-rails/storage'
32
+ Rails::Sequel::Storage.create_all
33
+ end
34
+ end
35
+
36
+ desc "Create the database defined in config/database.yml for the current Rails.env - also creates the test database if Rails.env.development?"
37
+ task :create, :env, :needs => :environment do |t, args|
38
+ args.with_defaults(:env => Rails.env)
39
+
40
+ require 'sequel-rails/storage'
41
+ Rails::Sequel::Storage.new(args.env).create
42
+
43
+ if Rails.env.development? && Rails.configuration.database_configuration['test']
44
+ Rails::Sequel::Storage.new('test').create
45
+ end
46
+ end
47
+
48
+ namespace :drop do
49
+ desc 'Drops all the local databases defined in config/database.yml'
50
+ task :all, :needs => :environment do
51
+ require 'sequel-rails/storage'
52
+ Rails::Sequel::Storage.drop_all
53
+ end
54
+ end
55
+
56
+ desc "Create the database defined in config/database.yml for the current Rails.env - also creates the test database if Rails.env.development?"
57
+ task :drop, :env, :needs => :environment do |t, args|
58
+ args.with_defaults(:env => Rails.env)
59
+
60
+ require 'sequel-rails/storage'
61
+ Rails::Sequel::Storage.new(args.env).drop
62
+
63
+ if Rails.env.development? && Rails.configuration.database_configuration['test']
64
+ Rails::Sequel::Storage.new('test').drop
65
+ end
66
+ end
67
+
68
+ namespace :migrate do
69
+ task :load => :environment do
70
+ require 'sequel-rails/migrations'
71
+ end
72
+
73
+ desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x. Target specific version with VERSION=x.'
74
+ task :redo => :load do
75
+ if ENV["VERSION"]
76
+ Rake::Task["db:migrate:down"].invoke
77
+ Rake::Task["db:migrate:up"].invoke
78
+ else
79
+ Rake::Task["db:rollback"].invoke
80
+ Rake::Task["db:migrate"].invoke
81
+ end
82
+ end
83
+
84
+
85
+ desc 'Resets your database using your migrations for the current environment'
86
+ task :reset => ["db:drop", "db:create", "db:migrate"]
87
+
88
+ desc 'Runs the "up" for a given migration VERSION.'
89
+ task :up => :load do
90
+ version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
91
+ raise "VERSION is required" unless version
92
+ Rails::Sequel::Migrations.migrate_up!(version)
93
+ Rake::Task["db:schema:dump"].invoke if Rails.env != 'test'
94
+ end
95
+
96
+ desc 'Runs the "down" for a given migration VERSION.'
97
+ task :down => :load do
98
+ version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
99
+ raise "VERSION is required" unless version
100
+ Rails::Sequel::Migrations.migrate_down!(version)
101
+ Rake::Task["db:schema:dump"].invoke if Rails.env != 'test'
102
+ end
103
+ end
104
+
105
+ desc 'Migrate the database to the latest version'
106
+ task :migrate => :'migrate:load' do
107
+ Rails::Sequel::Migrations.migrate_up!(ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
108
+ Rake::Task["db:schema:dump"].invoke if Rails.env != 'test'
109
+ end
110
+
111
+ desc 'Rolls the schema back to the previous version. Specify the number of steps with STEP=n'
112
+ task :rollback => :'migrate:load' do
113
+ step = ENV['STEP'] ? ENV['STEP'].to_i : 1
114
+ Sequel::Migrator.rollback('db/migrate/', step)
115
+ Rake::Task["db:schema:dump"].invoke if Rails.env != 'test'
116
+ end
117
+
118
+ desc 'Pushes the schema to the next version. Specify the number of steps with STEP=n'
119
+ task :forward => :'migrate:load' do
120
+ step = ENV['STEP'] ? ENV['STEP'].to_i : 1
121
+ Sequel::Migrator.forward('db/migrate/', step)
122
+ Rake::Task["db:schema:dump"].invoke if Rails.env != 'test'
123
+ end
124
+
125
+ desc 'Load the seed data from db/seeds.rb'
126
+ task :seed => :environment do
127
+ seed_file = File.join(Rails.root, 'db', 'seeds.rb')
128
+ load(seed_file) if File.exist?(seed_file)
129
+ end
130
+
131
+ desc 'Create the database, load the schema, and initialize with the seed data'
132
+ task :setup => [ 'db:create', 'db:migrate', 'db:seed' ]
133
+
134
+ desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.'
135
+ task :reset => [ 'db:drop', 'db:setup' ]
136
+
137
+ namespace :test do
138
+ task :prepare do
139
+ Rails.env = 'test'
140
+ Rake::Task['db:reset'].invoke()
141
+ Sequel::DATABASES.each do |db|
142
+ db.disconnect
143
+ end
144
+ end
145
+ end
146
+ end
147
+
148
+ task 'test:prepare' => 'db:test:prepare'
@@ -0,0 +1,12 @@
1
+ module Rails
2
+ module Sequel
3
+
4
+ module I18nSupport
5
+ # Set the i18n scope to overwrite ActiveModel.
6
+ def i18n_scope #:nodoc:
7
+ :sequel
8
+ end
9
+ end
10
+
11
+ end
12
+ end
@@ -0,0 +1,31 @@
1
+ module Sequel
2
+ module Railties
3
+
4
+ class LogSubscriber < ActiveSupport::LogSubscriber
5
+
6
+ def sql(event)
7
+ name = '%s (%.1fms)' % [event.payload[:name], event.duration]
8
+ sql = event.payload[:sql].squeeze(' ')
9
+
10
+ if odd?
11
+ name = color(name, :cyan, true)
12
+ sql = color(sql, nil, true)
13
+ else
14
+ name = color(name, :magenta, true)
15
+ end
16
+
17
+ debug " #{name} #{sql}"
18
+ end
19
+
20
+ def odd?
21
+ @odd_or_even = !@odd_or_even
22
+ end
23
+
24
+ def logger
25
+ ::Rails::Sequel.configuration.logger
26
+ end
27
+
28
+ end
29
+
30
+ end
31
+ end
@@ -0,0 +1,14 @@
1
+ module Rails
2
+ module Sequel
3
+
4
+ class << self
5
+ def reset_runtime
6
+ @runtime ||= 0
7
+
8
+ rt, @runtime = @runtime, 0
9
+ rt
10
+ end
11
+ end
12
+
13
+ end
14
+ end
@@ -0,0 +1,82 @@
1
+ require 'sequel'
2
+
3
+ # Implements Sequel-specific session store.
4
+
5
+ module Rails
6
+ module Sequel
7
+
8
+ class SessionStore < ActionDispatch::Session::AbstractStore
9
+
10
+ class Session < ::Sequel::Model
11
+
12
+ # property :id, Serial
13
+ # property :session_id, String, :required => true, :unique => true, :unique_index => true
14
+ # property :data, Object, :required => true, :default => ActiveSupport::Base64.encode64(Marshal.dump({}))
15
+ # property :updated_at, DateTime, :required => false, :index => true
16
+
17
+ class << self
18
+
19
+ def auto_migrate!
20
+ self.db.create_table :sessions do
21
+ primary_key :id
22
+ column :session_id, String,
23
+ :null => false,
24
+ :unique => true,
25
+ :index => true
26
+
27
+ column :data, :text,
28
+ :null => false
29
+
30
+ column :updated_at, DateTime,
31
+ :null => true,
32
+ :index => true
33
+ end
34
+ end
35
+
36
+ end
37
+
38
+ def self.name
39
+ 'session'
40
+ end
41
+
42
+ end
43
+
44
+ SESSION_RECORD_KEY = 'rack.session.record'.freeze
45
+
46
+ cattr_accessor :session_class
47
+ self.session_class = Session
48
+
49
+ private
50
+
51
+ def get_session(env, sid)
52
+ sid ||= generate_sid
53
+ session = find_session(sid)
54
+ env[SESSION_RECORD_KEY] = session
55
+ [ sid, session.data ]
56
+ end
57
+
58
+ def set_session(env, sid, session_data)
59
+ session = get_session_resource(env, sid)
60
+ session.data = session_data
61
+ session.updated_at = Time.now if session.dirty?
62
+ session.save
63
+ end
64
+
65
+ def get_session_resource(env, sid)
66
+ if env[ENV_SESSION_OPTIONS_KEY][:id].nil?
67
+ env[SESSION_RECORD_KEY] = find_session(sid)
68
+ else
69
+ env[SESSION_RECORD_KEY] ||= find_session(sid)
70
+ end
71
+ end
72
+
73
+ def find_session(sid)
74
+ klass = self.class.session_class
75
+
76
+ klass.where(:session_id => sid).first || klass.new(:session_id => sid)
77
+ end
78
+
79
+ end
80
+
81
+ end
82
+ end
@@ -0,0 +1,19 @@
1
+ require 'active_support/core_ext/hash/except'
2
+
3
+ require 'sequel/extensions/migration'
4
+
5
+ require 'sequel-rails/configuration'
6
+ require 'sequel-rails/runtime'
7
+ require 'sequel-rails/railties/benchmarking_mixin'
8
+
9
+ module Rails
10
+ module Sequel
11
+
12
+ def self.setup(environment)
13
+ puts "[sequel] Setting up the #{environment.inspect} environment:"
14
+
15
+ ::Sequel.connect({:logger => configuration.logger}.merge(::Rails::Sequel.configuration.environment_for(environment.to_s)))
16
+ end
17
+
18
+ end
19
+ end
@@ -0,0 +1,210 @@
1
+ module Rails
2
+ module Sequel
3
+
4
+ def self.storage
5
+ Storage
6
+ end
7
+
8
+ class Storage
9
+ attr_reader :config
10
+
11
+ def self.create_all
12
+ with_local_repositories { |config| create_environment(config) }
13
+ end
14
+
15
+ def self.drop_all
16
+ with_local_repositories { |config| drop_environment(config) }
17
+ end
18
+
19
+ def self.create_environment(config)
20
+ new(config).create
21
+ end
22
+
23
+ def self.drop_environment(config)
24
+ new(config).drop
25
+ end
26
+
27
+ def self.new(config)
28
+ config = Rails::Sequel.configuration.environments[config.to_s] unless config.kind_of?(Hash)
29
+
30
+ klass = lookup_class(config['adapter'])
31
+ if klass.equal?(self)
32
+ super(config)
33
+ else
34
+ klass.new(config)
35
+ end
36
+ end
37
+
38
+ class << self
39
+ private
40
+
41
+ def with_local_repositories
42
+ Rails::Sequel.configuration.environments.each_value do |config|
43
+ if config['host'].blank? || %w[ 127.0.0.1 localhost ].include?(config['host'])
44
+ yield(config)
45
+ else
46
+ puts "This task only modifies local databases. #{config['database']} is on a remote host."
47
+ end
48
+ end
49
+ end
50
+
51
+ def lookup_class(adapter)
52
+ klass_name = adapter.camelize.to_sym
53
+
54
+ unless Storage.const_defined?(klass_name)
55
+ raise "Adapter #{adapter} not supported (#{klass_name.inspect})"
56
+ end
57
+
58
+ const_get(klass_name)
59
+ end
60
+
61
+ end
62
+
63
+ def initialize(config)
64
+ @config = config
65
+ end
66
+
67
+ def create
68
+ _create
69
+ puts "[sequel] Created database '#{database}'"
70
+ end
71
+
72
+ def drop
73
+ _drop
74
+ puts "[sequel] Dropped database '#{database}'"
75
+ end
76
+
77
+ def database
78
+ @database ||= config['database'] || config['path']
79
+ end
80
+
81
+ def username
82
+ @username ||= config['username'] || ''
83
+ end
84
+
85
+ def password
86
+ @password ||= config['password'] || ''
87
+ end
88
+
89
+ def charset
90
+ @charset ||= config['charset'] || ENV['CHARSET'] || 'utf8'
91
+ end
92
+
93
+ class Sqlite < Storage
94
+ def _create
95
+ return if in_memory?
96
+ ::Sequel.connect(config.merge('database' => path))
97
+ end
98
+
99
+ def _drop
100
+ return if in_memory?
101
+ path.unlink if path.file?
102
+ end
103
+
104
+ private
105
+
106
+ def in_memory?
107
+ database == ':memory:'
108
+ end
109
+
110
+ def path
111
+ @path ||= Pathname(File.expand_path(database, Rails.root))
112
+ end
113
+
114
+ end
115
+
116
+ class Mysql < Storage
117
+ def _create
118
+ execute("CREATE DATABASE IF NOT EXISTS `#{database}` DEFAULT CHARACTER SET #{charset} DEFAULT COLLATE #{collation}")
119
+ end
120
+
121
+ def _drop
122
+ execute("DROP DATABASE IF EXISTS `#{database}`")
123
+ end
124
+
125
+ private
126
+
127
+ def execute(statement)
128
+ system(
129
+ 'mysql',
130
+ (username.blank? ? '' : "--user=#{username}"),
131
+ (password.blank? ? '' : "--password=#{password}"),
132
+ '-e',
133
+ statement
134
+ )
135
+ end
136
+
137
+ def collation
138
+ @collation ||= config['collation'] || ENV['COLLATION'] || 'utf8_unicode_ci'
139
+ end
140
+
141
+ end
142
+
143
+ class Postgres < Storage
144
+ def _create
145
+ system(
146
+ 'createdb',
147
+ '-E',
148
+ charset,
149
+ '-U',
150
+ username,
151
+ database
152
+ )
153
+ end
154
+
155
+ def _drop
156
+ system(
157
+ 'dropdb',
158
+ '-U',
159
+ username,
160
+ database
161
+ )
162
+ end
163
+ end
164
+
165
+ class Jdbc < Storage
166
+
167
+ def _is_mysql?
168
+ database.match(/^jdbc:mysql/)
169
+ end
170
+
171
+ def _root_url
172
+ database.scan /^jdbc:mysql:\/\/\w*:?\d*/
173
+ end
174
+
175
+ def db_name
176
+ database.scan(/^jdbc:mysql:\/\/\w+:?\d*\/(\w+)/).flatten.first
177
+ end
178
+
179
+ def _params
180
+ database.scan /\?.*$/
181
+ end
182
+
183
+ def _create
184
+ if _is_mysql?
185
+ ::Sequel.connect("#{_root_url}#{_params}") do |db|
186
+ db.execute("CREATE DATABASE IF NOT EXISTS `#{db_name}` DEFAULT CHARACTER SET #{charset} DEFAULT COLLATE #{collation}")
187
+ end
188
+ end
189
+ end
190
+
191
+ def _drop
192
+ if _is_mysql?
193
+ ::Sequel.connect("#{_root_url}#{_params}") do |db|
194
+ db.execute("DROP DATABASE IF EXISTS `#{db_name}`")
195
+ end
196
+ end
197
+ end
198
+
199
+ private
200
+
201
+ def collation
202
+ @collation ||= config['collation'] || ENV['COLLATION'] || 'utf8_unicode_ci'
203
+ end
204
+
205
+
206
+ end
207
+
208
+ end
209
+ end
210
+ end
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fredwu-sequel-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Brasten Sager (brasten)
9
+ - Fred Wu
10
+ autorequire:
11
+ bindir: bin
12
+ cert_chain: []
13
+ date: 2011-07-08 00:00:00.000000000 +10:00
14
+ default_executable:
15
+ dependencies:
16
+ - !ruby/object:Gem::Dependency
17
+ name: sequel
18
+ requirement: &2161464960 !ruby/object:Gem::Requirement
19
+ none: false
20
+ requirements:
21
+ - - ~>
22
+ - !ruby/object:Gem::Version
23
+ version: '3.13'
24
+ type: :runtime
25
+ prerelease: false
26
+ version_requirements: *2161464960
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: &2161464460 !ruby/object:Gem::Requirement
30
+ none: false
31
+ requirements:
32
+ - - ~>
33
+ - !ruby/object:Gem::Version
34
+ version: '3.0'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: *2161464460
38
+ - !ruby/object:Gem::Dependency
39
+ name: actionpack
40
+ requirement: &2161463980 !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ~>
44
+ - !ruby/object:Gem::Version
45
+ version: '3.0'
46
+ type: :runtime
47
+ prerelease: false
48
+ version_requirements: *2161463980
49
+ - !ruby/object:Gem::Dependency
50
+ name: railties
51
+ requirement: &2161463500 !ruby/object:Gem::Requirement
52
+ none: false
53
+ requirements:
54
+ - - ~>
55
+ - !ruby/object:Gem::Version
56
+ version: '3.0'
57
+ type: :runtime
58
+ prerelease: false
59
+ version_requirements: *2161463500
60
+ - !ruby/object:Gem::Dependency
61
+ name: yard
62
+ requirement: &2161463020 !ruby/object:Gem::Requirement
63
+ none: false
64
+ requirements:
65
+ - - ~>
66
+ - !ruby/object:Gem::Version
67
+ version: '0.5'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: *2161463020
71
+ - !ruby/object:Gem::Dependency
72
+ name: rspec
73
+ requirement: &2161462540 !ruby/object:Gem::Requirement
74
+ none: false
75
+ requirements:
76
+ - - ~>
77
+ - !ruby/object:Gem::Version
78
+ version: '2.6'
79
+ type: :development
80
+ prerelease: false
81
+ version_requirements: *2161462540
82
+ - !ruby/object:Gem::Dependency
83
+ name: autotest
84
+ requirement: &2161462160 !ruby/object:Gem::Requirement
85
+ none: false
86
+ requirements:
87
+ - - ! '>='
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: *2161462160
93
+ - !ruby/object:Gem::Dependency
94
+ name: simplecov
95
+ requirement: &2161461700 !ruby/object:Gem::Requirement
96
+ none: false
97
+ requirements:
98
+ - - ! '>='
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ type: :development
102
+ prerelease: false
103
+ version_requirements: *2161461700
104
+ description: Integrate Sequel with Rails 3
105
+ email: brasten@gmail.com, ifredwu@gmail.com
106
+ executables: []
107
+ extensions: []
108
+ extra_rdoc_files: []
109
+ files:
110
+ - README.md
111
+ - lib/generators/sequel.rb
112
+ - lib/generators/sequel/migration/migration_generator.rb
113
+ - lib/generators/sequel/migration/templates/migration.rb
114
+ - lib/generators/sequel/model/model_generator.rb
115
+ - lib/generators/sequel/model/templates/model.rb
116
+ - lib/generators/sequel/observer/observer_generator.rb
117
+ - lib/generators/sequel/observer/templates/observer.rb
118
+ - lib/sequel-rails.rb
119
+ - lib/sequel-rails/configuration.rb
120
+ - lib/sequel-rails/migrations.rb
121
+ - lib/sequel-rails/railtie.rb
122
+ - lib/sequel-rails/railties/benchmarking_mixin.rb
123
+ - lib/sequel-rails/railties/controller_runtime.rb
124
+ - lib/sequel-rails/railties/database.rake
125
+ - lib/sequel-rails/railties/i18n_support.rb
126
+ - lib/sequel-rails/railties/log_subscriber.rb
127
+ - lib/sequel-rails/runtime.rb
128
+ - lib/sequel-rails/session_store.rb
129
+ - lib/sequel-rails/setup.rb
130
+ - lib/sequel-rails/storage.rb
131
+ has_rdoc: true
132
+ homepage: http://github.com/fredwu/sequel-rails
133
+ licenses: []
134
+ post_install_message:
135
+ rdoc_options:
136
+ - --charset=UTF-8
137
+ require_paths:
138
+ - lib
139
+ required_ruby_version: !ruby/object:Gem::Requirement
140
+ none: false
141
+ requirements:
142
+ - - ! '>='
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ required_rubygems_version: !ruby/object:Gem::Requirement
146
+ none: false
147
+ requirements:
148
+ - - ! '>='
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ requirements: []
152
+ rubyforge_project:
153
+ rubygems_version: 1.6.2
154
+ signing_key:
155
+ specification_version: 3
156
+ summary: Integrate Sequel with Rails 3
157
+ test_files: []