ORM library for automatically displaying foreign keys in Python or Ruby

A common task that I encounter at work is to write scripts against pre-existing databases. Sometimes I connect to Oracle, sometimes it can be MySql or even a sql server.

What I would like is a tool that reconstructs database tables and foreign keys and allows me to write OO-style scripts in a database. It can be in any language, but it is preferable to use python or ruby.

For example, this is my ideal ruby ​​script: (assuming the manager and employee tables already exist with foreign keys)

DB = Database.connect(connect_string)
DB.managers.each do |manager|
  puts manager.name
  manager.employees.each do |employee|
    puts employee.name
  end
end

Does this type of library exist? If so, it will save me so much time!

- , , - . ActiveRecord, SQLAlchemy, Sequel DataMapper, , , .

+3
4
+4

ORM Ruby - : , .

, Ruby. 5 ActiveRecord:

require 'active_record'

class ActiveRecord::Base
  def self.magic!
    connection.tables.map { |table|
      klass = Class.new(self)
      Object.send(:const_set, table.singularize.camelize, klass)
    }.each { |model|
      model.column_names.grep(/_id$/).each { |foreign_key|
        name = foreign_key.sub(/_id$/, '')
        model.belongs_to(name)
        name.camelize.constantize.has_many(model.name.tableize)
      }
    }
  end
end

magic!:

ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')

ActiveRecord::Schema.define do
  create_table "managers" do |t|
    t.string "name"
  end
  create_table "employees" do |t|
    t.string "name"
    t.belongs_to "manager"
  end
end

# it happens!
ActiveRecord::Base.magic!

, :

mislav = Manager.create :name => "Mislav"
mislav.employees.create(:name => "Josh")
mislav.employees.create(:name => "Mike")

Manager.all.each do |manager|
  puts manager.name
  manager.employees.each do |employee|
    puts employee.name
  end
end

, Gist.

belongs_to has_many. , , Dr Nic Magic Models.

+3

sqlautocode SQLAlchemy. ORM, .

0

Ruby ORM, ActiveRecord, DataMapper Sequel.

For example, using ActiveRecord, you should:

##################################
#mysql conection
##################################
begin
  ActiveRecord::Base.establish_connection(
    :adapter  => DBAdapter,
    :host     => DBHost,
    :username => DBUserName,
    :password => DBPass,
    :database => DBDatabase,
    :encoding=> DBEncoding,
    :socket=> DBSocket #drop this option for windows machines 
  )
rescue Exception => ex
  fout.puts "Error connecting to mysql : #{ex}"
  puts "Migration was terminated due to connection error , check out the log file"
  break
end

######################
# Define models
######################

class Employee < ActiveRecord::Base
 belongs_to :manager
end 

class Manager < ActiveRecord::Base
 has_many :employees
end 
-2
source

Source: https://habr.com/ru/post/1725558/


All Articles