├── .ruby-version ├── .rspec ├── lib ├── planetscale_rails │ ├── version.rb │ ├── railtie.rb │ ├── migration.rb │ └── tasks │ │ └── psdb.rake ├── Rakefile └── planetscale_rails.rb ├── bin ├── setup └── console ├── .gitignore ├── Gemfile ├── Rakefile ├── .github └── workflows │ ├── main.yml │ └── licensing.yml ├── .rubocop.yml ├── doc └── dependency_decisions.yml ├── planetscale_rails.gemspec ├── test ├── test_helper.rb └── migration_test.rb ├── CODE_OF_CONDUCT.md ├── actions-example.md ├── Gemfile.lock ├── README.md └── LICENSE.txt /.ruby-version: -------------------------------------------------------------------------------- 1 | 3.3.6 2 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | --require spec_helper 4 | -------------------------------------------------------------------------------- /lib/planetscale_rails/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module PlanetscaleRails 4 | VERSION = "0.2.11" 5 | end 6 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /pkg/ 6 | /spec/reports/ 7 | /tmp/ 8 | *.gem 9 | 10 | # rspec failure tracking 11 | .rspec_status 12 | -------------------------------------------------------------------------------- /lib/Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "planetscale_rails" 4 | 5 | path = File.expand_path(__dir__) 6 | Dir.glob("#{path}/tasks/*.rake").each { |f| import f } 7 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source "https://rubygems.org" 4 | 5 | # Specify your gem's dependencies in planetscale_rails.gemspec 6 | gemspec 7 | 8 | gem "rake", "~> 13.0" 9 | 10 | gem "minitest", "~> 5.0" 11 | 12 | gem "rubocop", "~> 1.7" 13 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "bundler/gem_tasks" 4 | require "rake/testtask" 5 | 6 | Rake::TestTask.new(:test) do |t| 7 | t.libs << "test" 8 | t.libs << "lib" 9 | t.test_files = FileList["test/**/*_test.rb"] 10 | end 11 | 12 | require "rubocop/rake_task" 13 | 14 | RuboCop::RakeTask.new 15 | 16 | task default: %i[test rubocop] 17 | -------------------------------------------------------------------------------- /lib/planetscale_rails/railtie.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | # lib/railtie.rb 4 | require "planetscale_rails" 5 | require "rails" 6 | 7 | module PlanetscaleRails 8 | class Railtie < Rails::Railtie 9 | railtie_name :planetscale_rails 10 | 11 | rake_tasks do 12 | path = File.expand_path(__dir__) 13 | Dir.glob("#{path}/tasks/*.rake").each { |f| load f } 14 | end 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Ruby 2 | 3 | on: [push,pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v4 10 | - name: Set up Ruby 11 | uses: ruby/setup-ruby@v1 12 | with: 13 | ruby-version: 3.3.6 14 | bundler-cache: false 15 | - run: bundle install 16 | - name: Run the default task 17 | run: bundle exec rake 18 | -------------------------------------------------------------------------------- /lib/planetscale_rails.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "active_support" 4 | 5 | require_relative "planetscale_rails/version" 6 | require_relative "planetscale_rails/migration" 7 | 8 | module PlanetscaleRails 9 | require "planetscale_rails/railtie" if defined?(Rails) 10 | end 11 | 12 | ActiveSupport.on_load(:active_record) do 13 | ActiveRecord::Migration::Current.prepend(PlanetscaleRails::Migration::Current) 14 | end 15 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require "bundler/setup" 5 | require "planetscale_rails" 6 | 7 | # You can add fixtures and/or initialization code here to make experimenting 8 | # with your gem easier. You can also use a different console, if you like. 9 | 10 | # (If you use this, don't forget to add pry to your Gemfile!) 11 | # require "pry" 12 | # Pry.start 13 | 14 | require "irb" 15 | IRB.start(__FILE__) 16 | -------------------------------------------------------------------------------- /.github/workflows/licensing.yml: -------------------------------------------------------------------------------- 1 | name: Verify dependency licenses 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: 9 | - opened 10 | - reopened 11 | - synchronize 12 | 13 | jobs: 14 | licensing: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | with: 19 | fetch-depth: 0 20 | - name: Set up Ruby 21 | uses: ruby/setup-ruby@v1 22 | with: 23 | ruby-version: 3.3.6 24 | bundler-cache: false 25 | - run: bundle install 26 | - run: gem install license_finder 27 | - run: license_finder 28 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | TargetRubyVersion: 3 3 | 4 | Metrics/CyclomaticComplexity: 5 | Enabled: false 6 | 7 | Metrics/PerceivedComplexity: 8 | Enabled: false 9 | 10 | Style/StringLiterals: 11 | Enabled: true 12 | EnforcedStyle: double_quotes 13 | 14 | Style/StringLiteralsInInterpolation: 15 | Enabled: true 16 | EnforcedStyle: double_quotes 17 | 18 | Layout/LineLength: 19 | Enabled: false 20 | 21 | Metrics/MethodLength: 22 | Enabled: false 23 | 24 | Metrics/AbcSize: 25 | Enabled: false 26 | 27 | Metrics/BlockLength: 28 | Enabled: false 29 | 30 | Metrics/ClassLength: 31 | Enabled: false 32 | 33 | Style/Documentation: 34 | Enabled: false 35 | 36 | Style/IfUnlessModifier: 37 | Enabled: false 38 | -------------------------------------------------------------------------------- /doc/dependency_decisions.yml: -------------------------------------------------------------------------------- 1 | --- 2 | - - :permit 3 | - MIT 4 | - :who: 5 | :why: 6 | :versions: [] 7 | :when: 2023-03-02 18:39:34.628457000 Z 8 | - - :permit 9 | - Apache 2.0 10 | - :who: 11 | :why: 12 | :versions: [] 13 | :when: 2023-03-02 18:41:00.070547000 Z 14 | - - :permit 15 | - Simplified BSB, ruby 16 | - :who: 17 | :why: 18 | :versions: [] 19 | :when: 2023-03-02 18:47:46.186423000 Z 20 | - - :permit 21 | - Simplified BSB 22 | - :who: 23 | :why: 24 | :versions: [] 25 | :when: 2023-03-02 18:47:49.472823000 Z 26 | - - :permit 27 | - ruby 28 | - :who: 29 | :why: 30 | :versions: [] 31 | :when: 2023-03-02 18:47:54.139999000 Z 32 | - - :permit 33 | - Simplified BSD 34 | - :who: 35 | :why: 36 | :versions: [] 37 | :when: 2023-03-02 18:48:49.044186000 Z 38 | - - :permit 39 | - GPL-2.0 40 | - :who: 41 | :why: 42 | :versions: [] 43 | :when: 2023-03-10 13:40:33.848692000 Z 44 | - - :approve 45 | - nio4r 46 | - :who: 47 | :why: 48 | :versions: [] 49 | :when: 2024-01-12 23:54:26.539379000 Z 50 | -------------------------------------------------------------------------------- /lib/planetscale_rails/migration.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module PlanetscaleRails 4 | module Migration 5 | module Current 6 | # Allows users to set the `keyspace` option in their migration file or via an ENV var PLANETSCALE_DEFAULT_KEYSPACE. 7 | # If the migration is being run against PlanetScale (i.e. `ENABLE_PSDB` is set), then we prepend the keyspace to the table name. 8 | # 9 | # For local MySQL databases, the keyspace is ignored. 10 | def create_table(table_name, **options) 11 | keyspace = options[:keyspace] 12 | 13 | if keyspace.blank? && ENV["PLANETSCALE_DEFAULT_KEYSPACE"].present? 14 | keyspace = ENV["PLANETSCALE_DEFAULT_KEYSPACE"] 15 | log_keyspace_usage(keyspace) 16 | end 17 | 18 | if ENV["ENABLE_PSDB"] && keyspace.present? 19 | table_name = "#{keyspace}.#{table_name}" 20 | end 21 | super(table_name, **options.except(:keyspace)) 22 | end 23 | 24 | private 25 | 26 | def log_keyspace_usage(keyspace) 27 | message = "Using keyspace '#{keyspace}' from PLANETSCALE_DEFAULT_KEYSPACE environment variable" 28 | if defined?(Rails) && Rails.respond_to?(:logger) && Rails.logger 29 | Rails.logger.info(message) 30 | else 31 | puts message 32 | end 33 | end 34 | end 35 | end 36 | end 37 | -------------------------------------------------------------------------------- /planetscale_rails.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "lib/planetscale_rails/version" 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = "planetscale_rails" 7 | spec.version = PlanetscaleRails::VERSION 8 | spec.authors = ["Mike Coutermarsh", "Iheanyi Ekechukwu"] 9 | spec.email = ["coutermarsh.mike@gmail.com", "iekechukwu@gmail.com"] 10 | 11 | spec.summary = "Make Rails migrations easy with PlanetScale" 12 | spec.description = "A collection of rake tasks to make managing schema migrations with PlanetScale easy" 13 | spec.homepage = "https://github.com/planetscale/planetscale_rails" 14 | spec.license = "Apache-2.0" 15 | spec.required_ruby_version = ">= 3.0.0" 16 | 17 | spec.metadata["allowed_push_host"] = "https://rubygems.org" 18 | 19 | spec.metadata["homepage_uri"] = spec.homepage 20 | spec.metadata["source_code_uri"] = spec.homepage 21 | 22 | # Specify which files should be added to the gem when it is released. 23 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 24 | spec.files = Dir.chdir(File.expand_path(__dir__)) do 25 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features|doc)/}) } 26 | end 27 | spec.bindir = "exe" 28 | spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } 29 | spec.require_paths = ["lib"] 30 | 31 | spec.add_dependency "colorize", "~> 1.0" 32 | spec.add_dependency "rails", ">= 6.0", "< 9" 33 | end 34 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | $LOAD_PATH.unshift File.expand_path("../lib", __dir__) 4 | 5 | require "planetscale_rails" 6 | require "minitest/autorun" 7 | require "minitest/pride" 8 | require "stringio" 9 | 10 | # Add present? method to simulate Rails behavior 11 | class Object 12 | def present? 13 | !blank? 14 | end 15 | 16 | def blank? 17 | respond_to?(:empty?) ? empty? : !self 18 | end 19 | end 20 | 21 | class NilClass 22 | def blank? 23 | true 24 | end 25 | end 26 | 27 | class String 28 | def blank? 29 | strip.empty? 30 | end 31 | end 32 | 33 | # Add except method to Hash to simulate Rails behavior 34 | class Hash 35 | def except(*keys) 36 | dup.tap do |hash| 37 | keys.each { |key| hash.delete(key) } 38 | end 39 | end 40 | end 41 | 42 | # Base class that simulates Rails Migration 43 | class BaseMigration 44 | def create_table(table_name, **options) 45 | # This is the "original" create_table method that would be in Rails 46 | @last_table_name = table_name 47 | @last_options = options 48 | end 49 | end 50 | 51 | # Helper class to simulate Rails migration behavior 52 | class MockMigration < BaseMigration 53 | include PlanetscaleRails::Migration::Current 54 | 55 | attr_reader :last_table_name, :last_options 56 | end 57 | 58 | # Helper method to capture stdout 59 | def capture_stdout 60 | original_stdout = $stdout 61 | $stdout = StringIO.new 62 | yield 63 | output = $stdout.string 64 | $stdout = original_stdout 65 | output 66 | end 67 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or 22 | advances of any kind 23 | * Trolling, insulting or derogatory comments, and personal or political attacks 24 | * Public or private harassment 25 | * Publishing others' private information, such as a physical or email 26 | address, without their explicit permission 27 | * Other conduct which could reasonably be considered inappropriate in a 28 | professional setting 29 | 30 | ## Enforcement Responsibilities 31 | 32 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 33 | 34 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 35 | 36 | ## Scope 37 | 38 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 39 | 40 | ## Enforcement 41 | 42 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at coutermarsh.mike@gmail.com. All complaints will be reviewed and investigated promptly and fairly. 43 | 44 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 45 | 46 | ## Enforcement Guidelines 47 | 48 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 49 | 50 | ### 1. Correction 51 | 52 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 53 | 54 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 55 | 56 | ### 2. Warning 57 | 58 | **Community Impact**: A violation through a single incident or series of actions. 59 | 60 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 61 | 62 | ### 3. Temporary Ban 63 | 64 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 65 | 66 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 67 | 68 | ### 4. Permanent Ban 69 | 70 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 71 | 72 | **Consequence**: A permanent ban from any sort of public interaction within the community. 73 | 74 | ## Attribution 75 | 76 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 77 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 78 | 79 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 80 | 81 | [homepage]: https://www.contributor-covenant.org 82 | 83 | For answers to common questions about this code of conduct, see the FAQ at 84 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 85 | -------------------------------------------------------------------------------- /test/migration_test.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative "test_helper" 4 | 5 | class MigrationTest < Minitest::Test 6 | def setup 7 | @migration = MockMigration.new 8 | # Clear environment variables before each test 9 | ENV.delete("ENABLE_PSDB") 10 | ENV.delete("PLANETSCALE_DEFAULT_KEYSPACE") 11 | end 12 | 13 | def teardown 14 | # Clean up environment variables after each test 15 | ENV.delete("ENABLE_PSDB") 16 | ENV.delete("PLANETSCALE_DEFAULT_KEYSPACE") 17 | end 18 | 19 | def test_create_table_without_enable_psdb_ignores_keyspace 20 | table_name = "users" 21 | options = { keyspace: "test_keyspace", id: :uuid } 22 | 23 | @migration.create_table(table_name, **options) 24 | 25 | # Should pass through original table name without keyspace prefix 26 | assert_equal "users", @migration.last_table_name 27 | # Should remove keyspace option before passing to super 28 | assert_equal({ id: :uuid }, @migration.last_options) 29 | end 30 | 31 | def test_create_table_with_enable_psdb_but_no_keyspace 32 | ENV["ENABLE_PSDB"] = "1" 33 | table_name = "users" 34 | options = { id: :uuid } 35 | 36 | @migration.create_table(table_name, **options) 37 | 38 | # Should pass through original table name without keyspace prefix 39 | assert_equal "users", @migration.last_table_name 40 | assert_equal({ id: :uuid }, @migration.last_options) 41 | end 42 | 43 | def test_create_table_with_enable_psdb_and_keyspace_option 44 | ENV["ENABLE_PSDB"] = "1" 45 | table_name = "users" 46 | options = { keyspace: "test_keyspace", id: :uuid } 47 | 48 | @migration.create_table(table_name, **options) 49 | 50 | # Should prepend keyspace to table name 51 | assert_equal "test_keyspace.users", @migration.last_table_name 52 | # Should remove keyspace option before passing to super 53 | assert_equal({ id: :uuid }, @migration.last_options) 54 | end 55 | 56 | def test_create_table_with_enable_psdb_and_env_keyspace 57 | ENV["ENABLE_PSDB"] = "1" 58 | ENV["PLANETSCALE_DEFAULT_KEYSPACE"] = "env_keyspace" 59 | table_name = "users" 60 | options = { id: :uuid } 61 | 62 | @migration.create_table(table_name, **options) 63 | 64 | # Should prepend env keyspace to table name 65 | assert_equal "env_keyspace.users", @migration.last_table_name 66 | assert_equal({ id: :uuid }, @migration.last_options) 67 | end 68 | 69 | def test_logs_when_using_env_keyspace 70 | ENV["ENABLE_PSDB"] = "1" 71 | ENV["PLANETSCALE_DEFAULT_KEYSPACE"] = "env_keyspace" 72 | table_name = "users" 73 | options = { id: :uuid } 74 | 75 | output = capture_stdout do 76 | @migration.create_table(table_name, **options) 77 | end 78 | 79 | # Should log when using environment variable 80 | assert_includes output, "Using keyspace 'env_keyspace' from PLANETSCALE_DEFAULT_KEYSPACE environment variable" 81 | end 82 | 83 | def test_does_not_log_when_using_option_keyspace 84 | ENV["ENABLE_PSDB"] = "1" 85 | ENV["PLANETSCALE_DEFAULT_KEYSPACE"] = "env_keyspace" 86 | table_name = "users" 87 | options = { keyspace: "option_keyspace", id: :uuid } 88 | 89 | output = capture_stdout do 90 | @migration.create_table(table_name, **options) 91 | end 92 | 93 | # Should not log when using option keyspace 94 | refute_includes output, "Using keyspace" 95 | end 96 | 97 | def test_logs_env_keyspace_even_without_enable_psdb 98 | ENV["PLANETSCALE_DEFAULT_KEYSPACE"] = "env_keyspace" 99 | table_name = "users" 100 | options = { id: :uuid } 101 | 102 | output = capture_stdout do 103 | @migration.create_table(table_name, **options) 104 | end 105 | 106 | # Should still log when environment variable is used, even without ENABLE_PSDB 107 | assert_includes output, "Using keyspace 'env_keyspace' from PLANETSCALE_DEFAULT_KEYSPACE environment variable" 108 | end 109 | 110 | def test_create_table_option_keyspace_takes_precedence_over_env 111 | ENV["ENABLE_PSDB"] = "1" 112 | ENV["PLANETSCALE_DEFAULT_KEYSPACE"] = "env_keyspace" 113 | table_name = "users" 114 | options = { keyspace: "option_keyspace", id: :uuid } 115 | 116 | @migration.create_table(table_name, **options) 117 | 118 | # Should use option keyspace over env keyspace 119 | assert_equal "option_keyspace.users", @migration.last_table_name 120 | assert_equal({ id: :uuid }, @migration.last_options) 121 | end 122 | 123 | def test_create_table_with_empty_keyspace_option 124 | ENV["ENABLE_PSDB"] = "1" 125 | table_name = "users" 126 | options = { keyspace: "", id: :uuid } 127 | 128 | @migration.create_table(table_name, **options) 129 | 130 | # Empty keyspace should be ignored 131 | assert_equal "users", @migration.last_table_name 132 | assert_equal({ id: :uuid }, @migration.last_options) 133 | end 134 | 135 | def test_create_table_with_nil_keyspace_option_but_env_keyspace_present 136 | ENV["ENABLE_PSDB"] = "1" 137 | ENV["PLANETSCALE_DEFAULT_KEYSPACE"] = "env_keyspace" 138 | table_name = "users" 139 | options = { keyspace: nil, id: :uuid } 140 | 141 | @migration.create_table(table_name, **options) 142 | 143 | # Should fall back to env keyspace when option is nil 144 | assert_equal "env_keyspace.users", @migration.last_table_name 145 | assert_equal({ id: :uuid }, @migration.last_options) 146 | end 147 | end 148 | -------------------------------------------------------------------------------- /actions-example.md: -------------------------------------------------------------------------------- 1 | ## GitHub Actions example 2 | 3 | To automate branch creation and running migrations, you can setup a branch and run `rails psdb:migrate` from GitHub Actions. 4 | 5 | Here is a full example workflow that: 6 | 1. Creates a branch matching the git branch name. 7 | 2. Runs rails migrations. 8 | 3. Opens a deploy request if any migrations were run. 9 | 4. Comments on the pull request with the diff + link to the deploy request. 10 | 11 | ### Migrate schema workflow 12 | 13 | This workflow will run on any pull request that is opened with a change to `db/schema.rb`. 14 | 15 | Secrets needed to be set: 16 | - `PLANETSCALE_ORG_NAME` 17 | - `PLANETSCALE_DATABASE_NAME` 18 | - `PLANETSCALE_SERVICE_TOKEN_ID` 19 | - `PLANETSCALE_SERVICE_TOKEN` 20 | 21 | The PlanetScale service token must have the `connect_branch`, `create_branch`, `delete_branch_password`, `read_branch`, `create_deploy_request`, and `read_deploy_request` permissions on the database. 22 | 23 | ```yaml 24 | name: Run database migrations 25 | on: 26 | pull_request: 27 | branches: [ main ] 28 | paths: 29 | - 'db/schema.rb' 30 | 31 | jobs: 32 | planetscale: 33 | permissions: 34 | pull-requests: write 35 | contents: read 36 | 37 | runs-on: ubuntu-latest 38 | steps: 39 | - name: checkout 40 | uses: actions/checkout@v3 41 | - name: Create a branch 42 | uses: planetscale/create-branch-action@v4 43 | id: create_branch 44 | with: 45 | org_name: ${{ secrets.PLANETSCALE_ORG_NAME }} 46 | database_name: ${{ secrets.PLANETSCALE_DATABASE_NAME }} 47 | branch_name: ${{ github.head_ref }} 48 | from: main 49 | check_exists: true 50 | wait: true 51 | env: 52 | PLANETSCALE_SERVICE_TOKEN_ID: ${{ secrets.PLANETSCALE_SERVICE_TOKEN_ID }} 53 | PLANETSCALE_SERVICE_TOKEN: ${{ secrets.PLANETSCALE_SERVICE_TOKEN }} 54 | - uses: actions/checkout@v3 55 | - name: Set up Ruby 56 | uses: ruby/setup-ruby@v1 57 | with: 58 | ruby-version: 3.2.1 59 | - name: Cache Ruby gems 60 | uses: actions/cache@v3 61 | with: 62 | path: vendor/bundle 63 | key: ${{ runner.os }}-gems-${{ hashFiles('**/Gemfile.lock') }} 64 | restore-keys: | 65 | ${{ runner.os }}-gems- 66 | - name: Install dependencies 67 | run: | 68 | bundle config --local path vendor/bundle 69 | bundle config --local deployment true 70 | bundle install 71 | - name: Set migration config 72 | run: | 73 | echo "org: ${{ secrets.PLANETSCALE_ORG_NAME }}" > .pscale.yml 74 | echo "database: ${{ secrets.PLANETSCALE_DATABASE_NAME }}" >> .pscale.yml 75 | echo "branch: ${{ github.head_ref }}" >> .pscale.yml 76 | - name: Setup pscale 77 | uses: planetscale/setup-pscale-action@v1 78 | - name: Run migrations 79 | run: | 80 | bundle exec rails psdb:migrate > migration-output.txt 81 | env: 82 | PLANETSCALE_SERVICE_TOKEN_ID: ${{ secrets.PLANETSCALE_SERVICE_TOKEN_ID }} 83 | PLANETSCALE_SERVICE_TOKEN: ${{ secrets.PLANETSCALE_SERVICE_TOKEN }} 84 | - name: Open DR if migrations 85 | run: | 86 | if grep -q "migrated" migration-output.txt; then 87 | echo "DB_MIGRATED=true" >> $GITHUB_ENV 88 | if pscale deploy-request create ${{ secrets.PLANETSCALE_DATABASE_NAME }} ${{ github.head_ref }}; then 89 | cat migration-output.txt 90 | echo "DR_OPENED=true" >> $GITHUB_ENV 91 | echo "Deploy request successfully opened" 92 | else 93 | echo "Error: Deployment request failed" 94 | exit 0 95 | fi 96 | else 97 | echo "Did not open a DR since nothing found in migration-output.txt" 98 | cat migration-output.txt 99 | exit 0 100 | fi 101 | env: 102 | PLANETSCALE_SERVICE_TOKEN_ID: ${{ secrets.PLANETSCALE_SERVICE_TOKEN_ID }} 103 | PLANETSCALE_SERVICE_TOKEN: ${{ secrets.PLANETSCALE_SERVICE_TOKEN }} 104 | - name: Get Deploy Requests 105 | if: ${{ env.DR_OPENED }} 106 | env: 107 | PLANETSCALE_SERVICE_TOKEN_ID: ${{ secrets.PLANETSCALE_SERVICE_TOKEN_ID }} 108 | PLANETSCALE_SERVICE_TOKEN: ${{ secrets.PLANETSCALE_SERVICE_TOKEN }} 109 | run: | 110 | deploy_request_number=$(pscale deploy-request show ${{ secrets.PLANETSCALE_DATABASE_NAME }} ${{ github.head_ref }} -f json | jq -r '.number') 111 | echo "DEPLOY_REQUEST_NUMBER=$deploy_request_number" >> $GITHUB_ENV 112 | - name: Comment PR - db migrated 113 | if: ${{ env.DR_OPENED }} 114 | env: 115 | PLANETSCALE_SERVICE_TOKEN_ID: ${{ secrets.PLANETSCALE_SERVICE_TOKEN_ID }} 116 | PLANETSCALE_SERVICE_TOKEN: ${{ secrets.PLANETSCALE_SERVICE_TOKEN }} 117 | run: | 118 | sleep 2 119 | echo "Deploy request opened: https://app.planetscale.com/${{ secrets.PLANETSCALE_ORG_NAME }}/${{ secrets.PLANETSCALE_DATABASE_NAME }}/deploy-requests/${{ env.DEPLOY_REQUEST_NUMBER }}" >> migration-message.txt 120 | echo "" >> migration-message.txt 121 | echo "\`\`\`diff" >> migration-message.txt 122 | pscale deploy-request diff ${{ secrets.PLANETSCALE_DATABASE_NAME }} ${{ env.DEPLOY_REQUEST_NUMBER }} -f json | jq -r '.[].raw' >> migration-message.txt 123 | echo "\`\`\`" >> migration-message.txt 124 | - name: Comment PR - db migrated 125 | uses: thollander/actions-comment-pull-request@v2 126 | if: ${{ env.DR_OPENED }} 127 | with: 128 | filePath: migration-message.txt 129 | ``` 130 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | planetscale_rails (0.2.10) 5 | colorize (~> 1.0) 6 | rails (>= 6.0, < 9) 7 | 8 | GEM 9 | remote: https://rubygems.org/ 10 | specs: 11 | actioncable (8.0.1) 12 | actionpack (= 8.0.1) 13 | activesupport (= 8.0.1) 14 | nio4r (~> 2.0) 15 | websocket-driver (>= 0.6.1) 16 | zeitwerk (~> 2.6) 17 | actionmailbox (8.0.1) 18 | actionpack (= 8.0.1) 19 | activejob (= 8.0.1) 20 | activerecord (= 8.0.1) 21 | activestorage (= 8.0.1) 22 | activesupport (= 8.0.1) 23 | mail (>= 2.8.0) 24 | actionmailer (8.0.1) 25 | actionpack (= 8.0.1) 26 | actionview (= 8.0.1) 27 | activejob (= 8.0.1) 28 | activesupport (= 8.0.1) 29 | mail (>= 2.8.0) 30 | rails-dom-testing (~> 2.2) 31 | actionpack (8.0.1) 32 | actionview (= 8.0.1) 33 | activesupport (= 8.0.1) 34 | nokogiri (>= 1.8.5) 35 | rack (>= 2.2.4) 36 | rack-session (>= 1.0.1) 37 | rack-test (>= 0.6.3) 38 | rails-dom-testing (~> 2.2) 39 | rails-html-sanitizer (~> 1.6) 40 | useragent (~> 0.16) 41 | actiontext (8.0.1) 42 | actionpack (= 8.0.1) 43 | activerecord (= 8.0.1) 44 | activestorage (= 8.0.1) 45 | activesupport (= 8.0.1) 46 | globalid (>= 0.6.0) 47 | nokogiri (>= 1.8.5) 48 | actionview (8.0.1) 49 | activesupport (= 8.0.1) 50 | builder (~> 3.1) 51 | erubi (~> 1.11) 52 | rails-dom-testing (~> 2.2) 53 | rails-html-sanitizer (~> 1.6) 54 | activejob (8.0.1) 55 | activesupport (= 8.0.1) 56 | globalid (>= 0.3.6) 57 | activemodel (8.0.1) 58 | activesupport (= 8.0.1) 59 | activerecord (8.0.1) 60 | activemodel (= 8.0.1) 61 | activesupport (= 8.0.1) 62 | timeout (>= 0.4.0) 63 | activestorage (8.0.1) 64 | actionpack (= 8.0.1) 65 | activejob (= 8.0.1) 66 | activerecord (= 8.0.1) 67 | activesupport (= 8.0.1) 68 | marcel (~> 1.0) 69 | activesupport (8.0.1) 70 | base64 71 | benchmark (>= 0.3) 72 | bigdecimal 73 | concurrent-ruby (~> 1.0, >= 1.3.1) 74 | connection_pool (>= 2.2.5) 75 | drb 76 | i18n (>= 1.6, < 2) 77 | logger (>= 1.4.2) 78 | minitest (>= 5.1) 79 | securerandom (>= 0.3) 80 | tzinfo (~> 2.0, >= 2.0.5) 81 | uri (>= 0.13.1) 82 | ast (2.4.2) 83 | base64 (0.2.0) 84 | benchmark (0.4.0) 85 | bigdecimal (3.1.8) 86 | builder (3.3.0) 87 | colorize (1.1.0) 88 | concurrent-ruby (1.3.4) 89 | connection_pool (2.4.1) 90 | crass (1.0.6) 91 | date (3.4.1) 92 | drb (2.2.1) 93 | erubi (1.13.0) 94 | globalid (1.2.1) 95 | activesupport (>= 6.1) 96 | i18n (1.14.6) 97 | concurrent-ruby (~> 1.0) 98 | io-console (0.8.0) 99 | irb (1.14.3) 100 | rdoc (>= 4.0.0) 101 | reline (>= 0.4.2) 102 | json (2.6.3) 103 | logger (1.6.4) 104 | loofah (2.23.1) 105 | crass (~> 1.0.2) 106 | nokogiri (>= 1.12.0) 107 | mail (2.8.1) 108 | mini_mime (>= 0.1.1) 109 | net-imap 110 | net-pop 111 | net-smtp 112 | marcel (1.0.4) 113 | mini_mime (1.1.5) 114 | minitest (5.25.4) 115 | net-imap (0.5.2) 116 | date 117 | net-protocol 118 | net-pop (0.1.2) 119 | net-protocol 120 | net-protocol (0.2.2) 121 | timeout 122 | net-smtp (0.5.0) 123 | net-protocol 124 | nio4r (2.7.4) 125 | nokogiri (1.17.2-arm64-darwin) 126 | racc (~> 1.4) 127 | nokogiri (1.17.2-x86_64-darwin) 128 | racc (~> 1.4) 129 | nokogiri (1.17.2-x86_64-linux) 130 | racc (~> 1.4) 131 | parallel (1.22.1) 132 | parser (3.2.1.0) 133 | ast (~> 2.4.1) 134 | psych (5.2.2) 135 | date 136 | stringio 137 | racc (1.8.1) 138 | rack (3.1.8) 139 | rack-session (2.0.0) 140 | rack (>= 3.0.0) 141 | rack-test (2.1.0) 142 | rack (>= 1.3) 143 | rackup (2.2.1) 144 | rack (>= 3) 145 | rails (8.0.1) 146 | actioncable (= 8.0.1) 147 | actionmailbox (= 8.0.1) 148 | actionmailer (= 8.0.1) 149 | actionpack (= 8.0.1) 150 | actiontext (= 8.0.1) 151 | actionview (= 8.0.1) 152 | activejob (= 8.0.1) 153 | activemodel (= 8.0.1) 154 | activerecord (= 8.0.1) 155 | activestorage (= 8.0.1) 156 | activesupport (= 8.0.1) 157 | bundler (>= 1.15.0) 158 | railties (= 8.0.1) 159 | rails-dom-testing (2.2.0) 160 | activesupport (>= 5.0.0) 161 | minitest 162 | nokogiri (>= 1.6) 163 | rails-html-sanitizer (1.6.2) 164 | loofah (~> 2.21) 165 | nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) 166 | railties (8.0.1) 167 | actionpack (= 8.0.1) 168 | activesupport (= 8.0.1) 169 | irb (~> 1.13) 170 | rackup (>= 1.0.0) 171 | rake (>= 12.2) 172 | thor (~> 1.0, >= 1.2.2) 173 | zeitwerk (~> 2.6) 174 | rainbow (3.1.1) 175 | rake (13.0.6) 176 | rdoc (6.10.0) 177 | psych (>= 4.0.0) 178 | regexp_parser (2.7.0) 179 | reline (0.6.0) 180 | io-console (~> 0.5) 181 | rexml (3.2.5) 182 | rubocop (1.47.0) 183 | json (~> 2.3) 184 | parallel (~> 1.10) 185 | parser (>= 3.2.0.0) 186 | rainbow (>= 2.2.2, < 4.0) 187 | regexp_parser (>= 1.8, < 3.0) 188 | rexml (>= 3.2.5, < 4.0) 189 | rubocop-ast (>= 1.26.0, < 2.0) 190 | ruby-progressbar (~> 1.7) 191 | unicode-display_width (>= 2.4.0, < 3.0) 192 | rubocop-ast (1.27.0) 193 | parser (>= 3.2.1.0) 194 | ruby-progressbar (1.12.0) 195 | securerandom (0.4.1) 196 | stringio (3.1.2) 197 | thor (1.3.2) 198 | timeout (0.4.3) 199 | tzinfo (2.0.6) 200 | concurrent-ruby (~> 1.0) 201 | unicode-display_width (2.4.2) 202 | uri (1.0.2) 203 | useragent (0.16.11) 204 | websocket-driver (0.7.6) 205 | websocket-extensions (>= 0.1.0) 206 | websocket-extensions (0.1.5) 207 | zeitwerk (2.7.1) 208 | 209 | PLATFORMS 210 | arm64-darwin-23 211 | arm64-darwin-24 212 | x86_64-darwin-20 213 | x86_64-darwin-22 214 | x86_64-linux 215 | 216 | DEPENDENCIES 217 | minitest (~> 5.0) 218 | planetscale_rails! 219 | rake (~> 13.0) 220 | rubocop (~> 1.7) 221 | 222 | BUNDLED WITH 223 | 2.6.1 224 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PlanetScale Rails (Vitess only) 2 | 3 | [![Gem Version](https://badge.fury.io/rb/planetscale_rails.svg)](https://badge.fury.io/rb/planetscale_rails) 4 | 5 | Rake tasks for easily running Rails migrations against PlanetScale database branches. 6 | 7 | For information on how to connect your Rails app to PlanetScale, please [see our guide here](https://planetscale.com/docs/tutorials/connect-rails-app). 8 | 9 | ## Included rake tasks 10 | 11 | The rake tasks allow you to use local MySQL for development. When you're ready to make a schema change, you can create a PlanetScale branch and run migrations 12 | against it. See [usage](#usage) for details. 13 | 14 | ``` 15 | rake psdb:migrate # Migrate the database for current environment 16 | rake psdb:rollback # Rollback primary database for current environment 17 | rake psdb:schema:load # Load the current schema into the database 18 | ``` 19 | 20 | ## Installation 21 | 22 | Add this line to your application's Gemfile: 23 | 24 | ```ruby 25 | group :development do 26 | gem 'planetscale_rails' 27 | end 28 | ``` 29 | 30 | And then execute in your terminal: 31 | 32 | ``` 33 | bundle install 34 | ``` 35 | 36 | Make sure you have the [`pscale` CLI installed](https://github.com/planetscale/cli#installation). 37 | 38 | ### Disable schema dump 39 | 40 | Add the following to your `config/application.rb`. 41 | 42 | ```ruby 43 | if ENV["DISABLE_SCHEMA_DUMP"] 44 | config.active_record.dump_schema_after_migration = false 45 | end 46 | ``` 47 | 48 | This will allow the gem to disable schema dumping after running `psdb:migrate`. 49 | 50 | ## Usage 51 | 52 | 1. Using pscale, create a new branch. This command will create a local `.pscale.yml` file. You should add it to your `.gitignore`. 53 | 54 | ``` 55 | pscale branch switch my-new-branch-name --database my-db-name --create --wait 56 | ``` 57 | 58 | **Tip:** In your database settings. Enable "Automatically copy migration data." Select "Rails" as the migration framework. This will auto copy your `schema_migrations` table between branches. 59 | 60 | 2. Run your schema migrations against the branch. 61 | 62 | ``` 63 | bundle exec rails psdb:migrate 64 | ``` 65 | 66 | If you run multiple databases in your Rails app, you can specify the DB name. 67 | 68 | ``` 69 | bundle exec rails psdb:migrate:primary 70 | ``` 71 | 72 | If you make a mistake, you can use `bundle exec rails psdb:rollback` to rollback the changes on your PlanetScale branch. 73 | 74 | 3. Next, you can either open the Deploy Request via the UI. Or the CLI. 75 | 76 | Via CLI is: 77 | ``` 78 | pscale deploy-request create database-name my-new-branch-name 79 | ``` 80 | 81 | 4. To get your schema change to production, run the deploy request. Then, once it's complete, you can merge your code changes into your `main` branch in git and deploy your application code. 82 | 83 | ## Usage with multiple keyspace (or sharded) databases 84 | 85 | This gem supports working with multi-keyspace PlanetScale databases. When running migrations, Vitess will automatically route the schema change (DDL) to the correct keyspace based on the name of the table being altered. 86 | 87 | **Creating new tables** 88 | 89 | For adding a new table, you must specify the `keyspace` for the table either as part of create_table or by setting an environment variable. When running `psdb:migrate`, this gem will create the table in the correct keyspace. When running the migration locally against plain MySQL, 90 | the keyspace will be ignored and the table will be created as normal within the same database. 91 | 92 | ```ruby 93 | create_table(:new_table, id: { type: :bigint, unsigned: true }, keyspace: "keyspace-name") do |t| 94 | t.string :name 95 | end 96 | ``` 97 | 98 | _Optionally_: You can set a default keyspace for all new tables by setting `PLANETSCALE_DEFAULT_KEYSPACE` to the keyspace name. If a keyspace is not present in the `create_table` call, then the ENV var will be used when set. 99 | 100 | The keyspace resolution follows this precedence: 101 | 1. Explicit `keyspace:` option in create_table 102 | 2. `PLANETSCALE_DEFAULT_KEYSPACE` environment variable 103 | 3. No keyspace (standard behavior) 104 | 105 | ## Using PlanetScale deploy requests vs `psdb:migrate` directly in production. 106 | 107 | PlanetScale's deploy requests [solve the schema change problem](https://planetscale.com/docs/learn/how-online-schema-change-tools-work). They make a normally high risk operation, safe. This is done by running your schema change using [Vitess's online schema change](https://vitess.io/docs/18.0/user-guides/schema-changes/) tools. Once the change is made, a deploy request is [also revertible without data loss](https://planetscale.com/blog/revert-a-migration-without-losing-data). None of this is possible when running `rails db:migrate` directly against your production database. 108 | 109 | We recommend using GitHub Actions to automate the creation of PlanetScale branches and deploy requests. Then when you are ready to merge, you can run the deploy request before merging in your code. 110 | 111 | **When not to use deploy requests** 112 | 113 | If your application has minimal data and schema changes are a low risk event, then running `psdb:migrate` directly against production is perfectly fine. As your datasize grows and your application becomes busier, the risk of schema changes increase and we highly recommend using the deploy request flow. It's the best way available to safely migrate your schema. 114 | 115 | ## How to safely drop a column 116 | 117 | Before dropping the column in your database, there are a couple steps to take in your application to safely remove the column without any risk to your production application. 118 | 119 | 1. Remove all references to the column in your code. 120 | 2. Add the column name to `self.ignored_columns += %w(column_name)` in the model. [More on ignored_columns](https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-ignored_columns-3D). 121 | 3. Deploy this code to production. This ensures your application is no longer making use of the column in production and it's removed from the schema cache. 122 | 4. Follow the PlanetScale deploy request flow to drop the column. 123 | 124 | ## Usage with GitHub Actions 125 | 126 | See the [GitHub Actions examples](actions-example.md) doc for ways to automate your schema migrations with PlanetScale + Actions. 127 | 128 | ## Does this gem work with PlanetScale for Postgres? 129 | 130 | No, this gem is currently for Vitess databases only. When using PlanetScale for Postgres we recommend running `RAILS_ENV=production rails db:migrate` before your production code deploys to make schema changes. 131 | 132 | ## Development 133 | 134 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 135 | 136 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). 137 | 138 | ## Contributing 139 | 140 | Bug reports and pull requests are welcome on GitHub at https://github.com/planetscale/planetscale_rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/planetscale/planetscale_rails/blob/main/CODE_OF_CONDUCT.md). 141 | 142 | ## License 143 | 144 | The gem is available as open source under the terms of the [Apache 2.0 License](https://opensource.org/license/apache-2-0/). 145 | 146 | ## Code of Conduct 147 | 148 | Everyone interacting in the PlanetScale Rails project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/planetscale/planetscale_rails/blob/main/CODE_OF_CONDUCT.md). 149 | -------------------------------------------------------------------------------- /lib/planetscale_rails/tasks/psdb.rake: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "English" 4 | require "yaml" 5 | require "pty" 6 | require "colorize" 7 | 8 | databases = ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml 9 | 10 | def find_git_directory 11 | return ENV["GIT_DIR"] if ENV["GIT_DIR"] && !ENV["GIT_DIR"].empty? 12 | 13 | # it's not set as an env, so let's try to find it 14 | current_path = Pathname.new(Dir.pwd) 15 | 16 | until current_path.root? 17 | git_dir = current_path.join(".git") 18 | return current_path.to_s if git_dir.exist? # this can be a directory or a file (worktree) 19 | 20 | current_path = current_path.parent 21 | end 22 | 23 | nil 24 | end 25 | 26 | def load_pscale_config 27 | if File.exist?(".pscale.yml") 28 | return YAML.load_file(".pscale.yml") 29 | end 30 | 31 | # otherwise, look for a git root directory and load it from there 32 | git_dir = find_git_directory 33 | pscale_yaml_path = File.join(git_dir, ".pscale.yml") 34 | YAML.load_file(pscale_yaml_path) 35 | end 36 | 37 | def puts_deploy_request_instructions 38 | ps_config = load_pscale_config 39 | database = ps_config["database"] 40 | branch = ps_config["branch"] 41 | org = ps_config["org"] 42 | 43 | puts "Create a deploy request for '#{branch.colorize(:blue)}' by running:\n" 44 | puts " pscale deploy-request create #{database} #{branch} --org #{org}\n\n" 45 | end 46 | 47 | def kill_pscale_process 48 | Process.kill("TERM", ENV["PSCALE_PID"].to_i) if ENV["PSCALE_PID"] 49 | end 50 | 51 | def delete_password 52 | password_id = ENV["PSCALE_PASSWORD_ID"] 53 | return unless password_id 54 | 55 | ps_config = load_pscale_config 56 | database = ps_config["database"] 57 | branch = ps_config["branch"] 58 | 59 | command = "pscale password delete #{database} #{branch} #{password_id} #{ENV["SERVICE_TOKEN_CONFIG"]} --force" 60 | output = `#{command}` 61 | 62 | return if $CHILD_STATUS.success? 63 | 64 | puts "Failed to cleanup credentials used for PlanetScale connection. Password ID: #{password_id}".colorize(:red) 65 | puts "Command: #{command}" 66 | puts "Output: #{output}" 67 | end 68 | 69 | def db_branch_colorized(database, branch) 70 | "#{database.colorize(:blue)}/#{branch.colorize(:blue)}" 71 | end 72 | 73 | namespace :psdb do 74 | task check_ci: :environment do 75 | service_token = ENV["PSCALE_SERVICE_TOKEN"] || ENV["PLANETSCALE_SERVICE_TOKEN"] 76 | service_token_id = ENV["PSCALE_SERVICE_TOKEN_ID"] || ENV["PLANETSCALE_SERVICE_TOKEN_ID"] 77 | service_token_available = service_token && service_token_id 78 | 79 | if ENV["CI"] 80 | unless service_token_available 81 | missing_vars = [] 82 | missing_vars << "PLANETSCALE_SERVICE_TOKEN" unless service_token 83 | missing_vars << "PLANETSCALE_SERVICE_TOKEN_ID" unless service_token_id 84 | 85 | raise "Unable to authenticate to PlanetScale. Missing environment variables: #{missing_vars.join(", ")}" 86 | end 87 | 88 | service_token_config = "--service-token #{service_token} --service-token-id #{service_token_id}" 89 | 90 | ENV["SERVICE_TOKEN_CONFIG"] = service_token_config 91 | end 92 | end 93 | 94 | def create_connection_string 95 | ps_config = load_pscale_config 96 | database = ps_config["database"] 97 | branch = ps_config["branch"] 98 | 99 | raise "You must have `pscale` installed on your computer".colorize(:red) unless command?("pscale") 100 | if branch.blank? || database.blank? 101 | raise "Could not determine which PlanetScale branch to use from .pscale.yml. Please switch to a branch by using: `pscale branch switch branch-name --database db-name --create --wait`".colorize(:red) 102 | end 103 | 104 | short_hash = SecureRandom.hex(2)[0, 4] 105 | password_name = "planetscale-rails-#{short_hash}" 106 | command = "pscale password create #{database} #{branch} #{password_name} -f json --ttl 10m #{ENV["SERVICE_TOKEN_CONFIG"]}" 107 | 108 | output = `#{command}` 109 | 110 | if $CHILD_STATUS.success? 111 | response = JSON.parse(output) 112 | puts "Successfully created credentials for PlanetScale #{db_branch_colorized(database, branch)}" 113 | host = response["access_host_url"] 114 | username = response["username"] 115 | password = response["plain_text"] 116 | ENV["PSCALE_PASSWORD_ID"] = response["id"] 117 | 118 | adapter = "mysql2" 119 | 120 | if defined?(Trilogy) 121 | adapter = "trilogy" 122 | end 123 | 124 | url = "#{adapter}://#{username}:#{password}@#{host}:3306/@primary?ssl_mode=VERIFY_IDENTITY" 125 | 126 | # Check common CA paths for certs. 127 | ssl_ca_path = %w[/etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem /etc/ssl/cert.pem].find { |f| File.exist?(f) } 128 | 129 | if ssl_ca_path 130 | url += "&sslca=#{ssl_ca_path}" 131 | end 132 | 133 | url 134 | else 135 | puts "Failed to create credentials for PlanetScale #{db_branch_colorized(database, branch)}" 136 | puts "Command: #{command}" 137 | puts "Output: #{output}" 138 | puts "Please verify that you have the correct permissions to create a password for this branch." 139 | exit 1 140 | end 141 | end 142 | 143 | desc "Create credentials for PlanetScale and sets them to ENV['PSCALE_DATABASE_URL']" 144 | task "create_creds" => %i[environment check_ci] do 145 | ENV["PSCALE_DATABASE_URL"] = create_connection_string 146 | ENV["DISABLE_SCHEMA_DUMP"] = "true" 147 | ENV["ENABLE_PSDB"] = "true" 148 | end 149 | 150 | desc "Connects to the current PlanetScale branch and runs rails db:migrate" 151 | task migrate: %i[environment check_ci create_creds] do 152 | db_configs = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env) 153 | 154 | unless db_configs.size == 1 155 | raise "Found multiple database configurations, please specify which database you want to migrate using `psdb:migrate:`".colorize(:red) 156 | end 157 | 158 | puts "Running migrations..." 159 | 160 | command = "DATABASE_URL=\"#{ENV["PSCALE_DATABASE_URL"]}\" bundle exec rails db:migrate" 161 | IO.popen(command) do |io| 162 | io.each_line do |line| 163 | puts line 164 | end 165 | end 166 | 167 | if $CHILD_STATUS.success? 168 | puts_deploy_request_instructions 169 | else 170 | puts "Failed to run migrations".colorize(:red) 171 | end 172 | ensure 173 | delete_password 174 | end 175 | 176 | namespace :migrate do 177 | ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |name| 178 | desc "Connects to the current PlanetScale branch and runs rails db:migrate:#{name}" 179 | task name => %i[environment check_ci create_creds] do 180 | puts "Running migrations..." 181 | 182 | name_env_key = "#{name.upcase}_DATABASE_URL" 183 | command = "#{name_env_key}=\"#{ENV["PSCALE_DATABASE_URL"]}\" bundle exec rails db:migrate:#{name}" 184 | 185 | IO.popen(command) do |io| 186 | io.each_line do |line| 187 | puts line 188 | end 189 | end 190 | 191 | if $CHILD_STATUS.success? 192 | puts_deploy_request_instructions 193 | else 194 | puts "Failed to run migrations".colorize(:red) 195 | end 196 | ensure 197 | delete_password 198 | end 199 | end 200 | end 201 | 202 | namespace :schema do 203 | desc "Connects to the current PlanetScale branch and runs rails db:schema:load" 204 | task load: %i[environment check_ci create_creds] do 205 | db_configs = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env) 206 | 207 | unless db_configs.size == 1 208 | raise "Found multiple database configurations, please specify which database you want to load schema for using `psdb:schema:load:`".colorize(:red) 209 | end 210 | 211 | puts "Loading schema..." 212 | 213 | command = "DATABASE_URL=\"#{ENV["PSCALE_DATABASE_URL"]}\" bundle exec rails db:schema:load" 214 | IO.popen(command) do |io| 215 | io.each_line do |line| 216 | puts line 217 | end 218 | end 219 | 220 | unless $CHILD_STATUS.success? 221 | puts "Failed to load schema".colorize(:red) 222 | end 223 | ensure 224 | delete_password 225 | end 226 | 227 | namespace :load do 228 | ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |name| 229 | desc "Connects to the current PlanetScale branch and runs rails db:schema:load:#{name}" 230 | task name => %i[environment check_ci create_creds] do 231 | puts "Loading schema..." 232 | 233 | name_env_key = "#{name.upcase}_DATABASE_URL" 234 | command = "#{name_env_key}=\"#{ENV["PSCALE_DATABASE_URL"]}\" bundle exec rake db:schema:load:#{name}" 235 | 236 | IO.popen(command) do |io| 237 | io.each_line do |line| 238 | puts line 239 | end 240 | end 241 | 242 | unless $CHILD_STATUS.success? 243 | puts "Failed to load schema".colorize(:red) 244 | end 245 | ensure 246 | delete_password 247 | end 248 | end 249 | end 250 | end 251 | 252 | desc "Connects to the current PlanetScale branch and runs rails db:rollback" 253 | task rollback: %i[environment check_ci create_creds] do 254 | db_configs = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env) 255 | 256 | unless db_configs.size == 1 257 | raise "Found multiple database configurations, please specify which database you want to rollback using `psdb:rollback:`".colorize(:red) 258 | end 259 | 260 | command = "DATABASE_URL=\"#{ENV["PSCALE_DATABASE_URL"]}\" bundle exec rails db:rollback" 261 | 262 | IO.popen(command) do |io| 263 | io.each_line do |line| 264 | puts line 265 | end 266 | end 267 | 268 | unless $CHILD_STATUS.success? 269 | puts "Failed to rollback migrations".colorize(:red) 270 | end 271 | ensure 272 | delete_password 273 | end 274 | 275 | namespace :rollback do 276 | ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |name| 277 | desc "Connects to the current PlanetScale branch and runs rails db:rollback:#{name}" 278 | task name => %i[environment check_ci create_creds] do 279 | required_version = Gem::Version.new("6.1.0.0") 280 | rails_version = Gem::Version.new(Rails.version) 281 | 282 | if rails_version < required_version 283 | raise "This version of Rails does not support rollback commands for multi-database Rails apps. Please upgrade to at least Rails 6.1" 284 | end 285 | 286 | puts "Rolling back migrations..." 287 | 288 | name_env_key = "#{name.upcase}_DATABASE_URL" 289 | command = "#{name_env_key}=\"#{ENV["PSCALE_DATABASE_URL"]}\" bundle exec rake db:rollback:#{name}" 290 | 291 | IO.popen(command) do |io| 292 | io.each_line do |line| 293 | puts line 294 | end 295 | end 296 | 297 | unless $CHILD_STATUS.success? 298 | puts "Failed to rollback migrations".colorize(:red) 299 | end 300 | ensure 301 | delete_password 302 | end 303 | end 304 | end 305 | end 306 | 307 | def command?(name) 308 | `which #{name}` 309 | $CHILD_STATUS.success? 310 | end 311 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------