`

如何让Rails跑在遗留的Oracle数据库上

阅读更多

Just recently I’ve had to do a lot of work getting rails to play with a 15 year old Oracle database. Needless to say this database doesn’t follow the conventions we’ve all grown used to with rails. The table names are all over the place, the primary keys aren’t surrogate keys but actually have business meaning, composite keys which include date columns, crazy methods of generating primary keys instead of sequences….. if there’s a rails convention this thing doesn’t break then I’ve not found it yet!

However rails does provide methods for us to get it working with these legacy systems. Of course, if we were designing an application from scratch, we’d never need these techniques because we’d do it “the rails way” from the start. So I’m going to cover a couple of techniques which I’ve had to use in case you find yourself with the misfortune of having to marry rails to a pig!
Telling rails to use a different table and primary key

If we have a model named Student then rails convention dictates this model will map to a table called students and it will have a primary key called id. Well the real world isn’t always so accommodating. No problem…


class Student < ActiveRecord::Base
  set_table_name :student
  set_primary_key :s_stno
end


Composite keys

In this instance, the composite primary keys gem is your friend. Simply install…



sudo gem install composite_primary_keys


... and require in your environment.rb...



require 'composite_primary_keys'


Now you are ready to start supplying multiple keys in your models…




class CourseFee < ActiveRecord::Base
  set_table_name "course_avail"
  set_primary_keys :course_code, :course_date
end


You may notice that one of those composite keys is a date. This can cause you problems when you try and generate a url for an instance of this class because the date won’t be output in the correct format. So we need to override the to_param method to output the date in database format.



  def to_param
    "#{course_code},#{course_date.to_s(:db)}"
  end

Non standard primary key generation

This one was tricky! Now it wouldn’t be too hard if your legacy system uses a sequence to generate primary keys because you can just tell rails to use this sequence if it’s not named using the rails convention (which is tablename_seq).


class Student < ActiveRecord::Base
  set_sequence_name 'a_non_standard_sequence_name'
end


However you could find yourself in a nasty situation where the database doesn’t use a sequence for primary keys – it uses a value stored in a table instead. No problem you’re thinking to yourself, I’ll just use a before_create hook to populate the primary key? Nope, not going to work. The oracle_enhanced adapter will still go off and try to use a sequence called tablename_seq causing the whole house of cards to come crashing down. So we need to stop oracle_enhanced from looking for this sequence and instead tell it to generate the primary key some other way.

I stole the basis of this hack from the oracle_enhanced website and added my own twist to it to fit my circumstances. I doubt your scenario will exactly match mine (and I hope for your sake it doesn’t!), but you can use this as a starting point.

So…. the primary keys in my evil system are stored in a table called counter. There is only one row in this table and a column for each table you want a primary key for. Nasty. So I started off by generating a model for this table with a method to pull out a primary key…



class Counter < ActiveRecord::Base
  set_table_name :counter

  def self.next_primary_key(col)
    current_value = Counter.first.read_attribute(col)
    new_value = current_value + 1
    Counter.connection.execute("UPDATE counter SET #{col} = #{new_value}")
    new_value
  end
end


Now assuming there is a column in the counter table called student, I can pull a primary key out by calling:


Counter.next_primary_key('student')


This will increment the value in the column and return it. It’s a nasty way to generate primary keys but hey, I didn’t design this!

So now we can access these primary keys in a tidy way we need to get our Student model to use it for its primary keys. And this is where the fun starts – we need to monkey patch the oracle_enhanced adapter to use this table, but only when our table doesn’t have a sequence. To do this we create an initialiser in config/initializers.



# config/initializers/oracle_enhanced.rb

ActiveRecord::ConnectionAdapters::OracleEnhancedAdapter.class_eval do
  alias_method :orig_next_sequence_value, :next_sequence_value

  def next_sequence_value(sequence_name)
    if sequence_name =~ /^counter-/
      # Strip the counter- part out of the string and pass the remainder to next_primary_key
      Counter.next_primary_key(sequence_name.match("counter-(.*$)")[1])
    else
      orig_next_sequence_value(sequence_name)
    end
  end
end


What this code does is check what the name of the model’s sequence is and if it starts with counter- it looks in the counter table for the primary key. So when we specify the following sequence name…

class Student < ActiveRecord::Base
  set_table_name :student
  set_primary_key :s_stno
  set_sequence_name 'counter-student'
end


... our little monkey patch will spot the counter- prefix, strip it out and make its primary key the result of a call to the following:



Counter.next_primary_key('student')


Perfect! It’s a little complicated but we’ve now got a flexible solution to cater for whatever crazy method of primary key generation our predecessors may have dreamt up. And the best part is it gracefully falls back to the default behaviour if the sequence name doesn’t start with counter-.

As I said before, the main guts of this hack (the monkey patching of oracle_enhanced) was written by Raimonds Simanovskis on the oracle_enhanced website. I merely souped it up a little with some regular expressions and adopted it to fit my particular use case.
分享到:
评论

相关推荐

    巧用Ruby配备Oracle数据库

    本文将探讨如何在Ruby on Rails框架中配置Oracle数据库,以及解决相关的验证和性能问题。 首先,连接Oracle数据库需要Ruby的一个特定库——Ruby/Oracle 调用接口 (OCI8),它是基于Ruby/DBI模块的数据库驱动程序。...

    rails连接oracle需要的驱动

    rails连接oracle需要的驱动 执行命令:C:\&gt; ruby 文件名.rb &lt;br&gt;

    rails2.1與Oracle 連結所需gem

    标题“rails2.1与Oracle连接所需gem”指的是在Rails 2.1版本的应用程序中,如何配置和使用Oracle数据库的宝石(gem)扩展。Rails是Ruby on Rails框架的简称,是一个流行的开源Web应用程序框架,而Oracle则是一种企业...

    巧用ruby配备oracle数据库.pdf

    在Rails框架中,连接到Oracle数据库所需的参数存储在`config/database.yml`文件中。例如: ```yaml development: adapter: oci host: xe username: development password: password test: adapter: oci host...

    巧用Ruby配备Oracle数据库.doc

    在Rails中,通过修改`config/database.yml`文件,可以轻松地配置Oracle数据库连接,使得Ruby on Rails应用能够与Oracle数据库进行数据交互。同时,注意保持数据库客户端库和Ruby/OCI8驱动的兼容性,以确保稳定的数据...

    使用ROR编写ORACLE WEB应用

    标题 "使用ROR编写ORACLE WEB应用" 涉及的知识点主要集中在两个核心领域:Ruby on Rails(简称ROR)框架和Oracle数据库的集成。Ruby on Rails是基于Ruby编程语言的一个开源Web开发框架,而Oracle则是一款广泛使用的...

    结合使用 Oracle 和 Ruby on Rails 教程

    【描述】:“结合使用 Oracle 和 Ruby on Rails 教程”这篇博文提供了关于在Ruby on Rails项目中配置和使用Oracle数据库的详细步骤。它涵盖了从安装必要的库和驱动程序到创建数据库连接、迁移以及查询的全过程。通过...

    在RHEL上安裝設置ROR(nginx+passenger+ruby+rails+oracle+netzke)

    在RHEL(Red Hat Enterprise Linux)系统上搭建Ruby on Rails(简称RoR)应用程序环境是一项技术性较强的任务,尤其当涉及到与其他服务如Nginx、Phusion Passenger、Ruby、Rails以及Oracle数据库集成时。以下是对这...

    ruby-oracle相关的数据库操作的gems包

    总结来说,`ruby-oci8`是Ruby编程语言中用于与Oracle数据库交互的关键工具,它提供了一套易于使用的接口,使得开发者能够在多种平台上构建高效、可靠的Oracle数据库应用。通过不同版本的Gem包,开发者可以根据自己的...

    Ruby-Multiverse让Rails支持多数据库

    在这种背景下,“Ruby-Multiverse”应运而生,它为Rails应用程序提供了优雅地支持多数据库的能力。本文将深入探讨Multiverse的核心功能、如何集成以及它为Rails开发带来的优势。 Multiverse是针对ActiveRecord的一...

    rails和mysql数据库连接中出现的问题以及解决办法

    如果你的Rails应用部署在远程服务器上,确保服务器可以访问到MySQL数据库。防火墙设置可能需要允许特定端口(默认为3306)的通信。 最后,Rails和MySQL之间的版本兼容性问题不容忽视。确保Rails版本和MySQL版本之间...

    Ruby on Rails安装及MySQL数据库配置指南

    可以在数据库配置文件中添加 MySQL 的连接信息。 三、解决问题 在安装和配置 Ruby on Rails 和 MySQL 数据库的过程中,可能会遇到一些问题。例如,在创建 POSTS 应用时可能会遇到问题,创建数据后数据库中有数据,...

    Ruby on rails 数据库详细配置

    在Ruby on Rails框架中,数据库配置是至关重要的部分,它允许开发者与各种数据库系统进行交互,如MySQL、Microsoft SQL Server等。以下将详细介绍如何在Windows环境下安装Ruby on Rails以及配置数据库。 首先,我们...

    浅谈Ruby on Rails下的rake与数据库数据迁移操作

    总结来说,Rails的Migration和rake工具在数据库管理和数据迁移中各自扮演着不同的角色。Migration应专注于数据库Schema的演变,而rake任务则更适合处理复杂的数据操作。遵循最佳实践,编写清晰、高效的rake任务,...

    Panorama_Gem:监视Oracle数据库性能问题的工具

    用于分析Oracle数据库性能问题的Web工具。 轻松访问一些内部信息。 旨在解决其他现有工具(例如企业管理器)未充分分析和提出的问题。 在这里,您可以找到有关Panorama的更多信息(包括Java Web应用程序和Docker...

    Ruby-SecondBase为Rails提供双数据库无缝相集成

    在数据库迁移方面,SecondBase扩展了ActiveRecord的迁移命令,使得你可以针对每个数据库运行单独的迁移。这意味着你可以对每个数据库进行定制化的结构更新,而不会影响到其他数据库。在Rails的命令行中,你可以指定...

    Ubuntu 11.04安装Ruby on rails 连接MySQL数据库.pdf

    通过以上步骤,你已经在Ubuntu 11.04上成功搭建了一个基于Ruby on Rails和MySQL数据库的开发环境,并创建了一个基础的Web应用。这不仅为后续的开发工作提供了便利,也加深了对Ruby on Rails框架及MySQL数据库配置的...

Global site tag (gtag.js) - Google Analytics