🎢

postgresql から sqlite3に移す作業について (前編)

2025/02/05に公開

動機

  • 特定のDB環境で作ったアプリの可搬性向上を検討した
  • dockerでpostgresqlサーバ同梱しても良いが肥大化したくない。
  • sqlite3 でいわゆる "バッテリ内蔵” にしたい。
  • サンプルにモックデータを入れたまま移行。seedを dumpで作ってもいいが・・・

参考情報の収集

純粋に rails 経由しない方法について

  • こちらを参照: https://gist.github.com/fiftin/18221054c7777e1f1207
    postgresql のディアレクトである、 ”COPY" で止まる。
  • モックなので数レコードだけ INSERT文に書き換えてもいいが、本来の「コンバート」を考えるとその「手を動かしてごまかす」」は悪手

rails の 作法

  • 基本的に Active Record / model に準拠しなければ扱えない。
  • コンバートが可能なのかを見るだけだが、renderer 通る様に model 定義もする必要はある。

実作業 (railsで読めるまで)

  • まずは railsを使い、DBにアクセスできるまでをやってみる。
strnh@pc:~/workdir/r-r/dummy$ rails new dbconv2 --database=postgresql
strnh@pc:~/workdir/r-r/dummy$ cd dbconv2
strnh@pc:~/workdir/r-r/dummy$ vim config/database.yml
  • 接続情報を書き込みます。
development:
  <<: *default
  database: sampledb
  # The specified database role being used to connect to PostgreSQL.
  # To create additional roles in PostgreSQL see `$ createuser --help`.
  # When left blank, PostgreSQL will use the default role. This is
  # the same name as the operating system user running Rails.
  username: postgres

  # The password associated with the PostgreSQL role (username).
  #password:

  # Connect on a TCP socket. Omitted by default since the client uses a
  # domain socket that doesn't need configuration. Windows does not have
  # domain sockets, so uncomment these lines.
  host: 10.0.0.1

  # The TCP port the server listens on. Defaults to 5432.
  # If your server runs on a different port number, change accordingly.
  port: 5432
  • スキーマを拾ってもらいます
$ rake environment -t RAILS_ENV=development db:schema:dump** Invoke environment (first_time)
** Execute environment
** Invoke db:schema:dump (first_time)
** Invoke db:load_config (first_time)
** Invoke environment 
** Execute db:load_config
** Execute db:schema:dump
table_name = 'sample' #ここにDBのテーブル名 
field_names = Array.new  
cols = ActiveRecord::Base.connection.columns(table_name)  #*1
cols.each do |c|  
  field_names << "#{c.name}:#{c.type}"  
end  
puts field_names.join(' ') # この出力結果を copy..
  • scaffold で 簡単に。 table名 カラム1 カラム2... でさっくり。
    rails g scaffold sample "" 出力結果の paste "" --skip-migration

  • 他所から持ってきたものなので app/models/sample.rb を編集して table_name を追加しておく。

class sample < ApplicationRecord
  self.table_name="sample"
end
  • rails server で DBがざっくり読めたら取り敢えず次段階に進む。

Discussion