Postgres with docker-compose + uuid as primary keys

Set up postgresql as the database with local support for docker-compose and enable uuid as primary keys
Icons/chart bar
Used 17 times
Created by
A Arandi Lopez

Usage

Run this command in your Rails app directory in the terminal:

rails app:template LOCATION="https://railsbytes.com/script/xkjs3D"
Template Source

Review the code before running this template on your machine.

unless File.exist? 'docker-compose.yml'
  create_file 'docker-compose.yml' do <<~YAML
    version: "3.1"

    services:
  YAML
  end
end

inject_into_file 'docker-compose.yml' do <<-YAML
  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_USER: #{app_name}
      POSTGRES_PASSWORD: #{app_name}
      POSTGRES_DB: #{app_name}_development
    volumes:
      - ./tmp/postgresql:/var/lib/postgresql
    ports:
      - 5432:5432
  YAML
end

initializer 'generator.rb' do <<~RB
  Rails.application.config.generators do |g|
    g.orm :active_record, primary_key_type: :uuid
  end
  RB
end

remove_file 'config/database.yml'
create_file 'config/database.yml' do <<~EOF
  default: &default
    adapter: postgresql
    encoding: unicode
    pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

  development:
    <<: *default
    database: #{app_name}_development
    username: #{app_name}
    password: #{app_name}
    host: localhost
    port: 5432

  test:
    <<: *default
    database: #{app_name}_test
    username: #{app_name}
    password: #{app_name}
    host: localhost
    port: 5432

  production:
    <<: *default
    url: <%= ENV['DATABASE_URL'] %>
  EOF
end

generate 'migration', 'enable_uuid'
migration = Dir.glob("db/migrate/*").max_by { |f| File.mtime(f) }
inject_into_file migration, after: 'def change' do <<~RB

    enable_extension 'pgcrypto'
  RB
end

`docker-compose up --detach`
sleep 2
system('rake db:drop')
system('rake db:create')
system('rake db:migrate')
Comments

Sign up or Login to leave a comment.