Sha256: 19ce68dee51113b129e87e1a48d21bf6037de11963e571a67ad22c9e58c20713

Contents?: true

Size: 1.39 KB

Versions: 4

Compression:

Stored size: 1.39 KB

Contents

module Coupler
  module Models
    class Connection < Sequel::Model
      include CommonModel

      ADAPTERS = [%w{mysql MySQL h2 H2}]

      one_to_many :resources

      def database(&block)
        Sequel.connect(connection_string, {
          :loggers => [Coupler::Logger.instance],
          :max_connections => 20
        }, &block)
      end

      def deletable?
        resources_dataset.count == 0
      end

      private
        def connection_string
          case adapter
          when 'mysql'
            misc = '&zeroDateTimeBehavior=convertToNull'
            "jdbc:mysql://%s:%d/%s?user=%s&password=%s%s" % [
              host, port, database_name, username, password, misc
            ]
          when 'h2'
            "jdbc:h2:#{path}"
          end
        end

        def before_validation
          super
          self.slug ||= name.downcase.gsub(/\s+/, "_") if name
        end

        def validate
          super
          validates_presence :name
          validates_unique :name, :slug

          begin
            database { |db| db.test_connection }
          rescue Sequel::DatabaseConnectionError, Sequel::DatabaseError => e
            errors.add(:base, "Couldn't connect to the database")
          end
        end

        def before_destroy
          super

          # Prevent destruction of connections in use by resources.
          deletable?
        end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
coupler-0.0.4-java lib/coupler/models/connection.rb
coupler-0.0.3-java lib/coupler/models/connection.rb
coupler-0.0.2-java lib/coupler/models/connection.rb
coupler-0.0.1-java lib/coupler/models/connection.rb