LoginSignup
1
2

More than 3 years have passed since last update.

herokuで「ERROR: cannot execute ALTER TABLE in a read-only transaction」がでて困る

Last updated at Posted at 2020-10-12

問題

herokuの「Heroku Postgres - Add-ons」で行を追加しようと「ERROR: cannot execute ALTER TABLE in a read-only transaction」と怒られます.

sql_test2.png

解決策

こんなpythonからPostgresデータベースにアクセスするクラスを作成.


import os
import psycopg2
import json
import pprint

class PostgreSql:
    def __init__(self):
        self.conn = self.get_connection()
        self.cur  = self.conn.cursor()

    ##############################################
    # DBコネクション取得関数
    #
    def get_connection(self):
        dsn = "host=XXXXXXXXXXXXXX\
            port=XXXX \
            dbname=XXXXXXXXXX \
            user=XXXXXXXXX \
            password=XXXXXXXXXXXXXX"
        return psycopg2.connect(dsn)

    ##############################################
    # insert関数
    #
    def insert(self, sqlStr):
        self.cur.execute('BEGIN')
        self.cur.execute(sqlStr)
        self.cur.execute('COMMIT')

    ##############################################
    # mysqlでselectする用の関数
    #
    def select(self,  sqlStr):
        self.cur.execute(sqlStr)
        return list(self.cur)

if __name__ == "__main__":

    psql = PostgreSql()

    ##############################################
    # カラムの追加
    #
    sql = "ALTER TABLE tbl_name ADD COLUMN category2 text;"
    psql.insert(sql)

作成したpsqlクラスのinsert関数を使用してカラムを追加しましょう!!

    sql = "ALTER TABLE tbl_name ADD COLUMN category2 text;"
    psql.insert(sql)

これでherokuのダッシュボードでselectして追加されていたら完了!!

sql_test.png

以上,「ERROR: cannot execute ALTER TABLE in a read-only transaction」の解決方でした.

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2