ERROR: permission denied for relation after Heroku pg_dump and import to development database - ruby-on-rails

I am pretty new to heroku & postgresql. I am trying to dump my production database into my local development database in my local machine.
I dumped like this (my actual info redacted):
pg_dump --host=<myhost> --port=<port> --username=<username> --password --dbname=app_production > output.sql
Then I imported to my local app_development database like this:
psql -d app_development -f output.sql
but now, when I start my server I get this:
PG::InsufficientPrivilege: ERROR: permission denied for relation schema_migrations : SELECT "schema_migrations".* FROM "schema_migrations"
I also use Navicat to see the local database, and now I can't open any of my tables. Each time I try I get
ERROR: permission denied for relation <nameofwhatevertable>
How can I reset permissions for my app_development database when I've dumped my app_production database.

It seems like your db permissions have been mangled. Do you have PgAdmin III installed? http://www.pgadmin.org/download/
PgAdmin III will let you reset all db and user parameters. It will also allow you to see what is going on in your database(s) and tables so you can debug them.
It's a PostGreSQL development tool that is very much like MySQL Workbench. Free download from PostGreSQL. Runs on multiple platforms. Easy to set up.
It is most handy in cases like this, when you're trying to track down an intractable error. Highly recommended tool. Takes the guessing out of pg work.

Related

How can I switch database inside a Rails console on Heroku?

I'm trying to migrate users from one system to another. Each system has its own database and different classes.
My plan is to connect to one database, read some info from one database via SQL commands:
ActiveRecord::Base.connection.execute(sql_command)
do something with the data and then write some results on the new database using normal models.
I plan on doing that inside Sidekiq job but I'm trying to do some testing using a Rails console on Heroku.
This should be pretty straightforward, but this proves ridiculously difficult.
When I launched a Rails console on Heroku. I'm connecting to DATABASE_URL, which is ok, but when I try to connect to the old database and execute a command, like this:
ActiveRecord::Base.establish_connection(adapter: "postgresql", encoding: "unicode", pool: 10, url: "postgres://...info...")
ActiveRecord::Base.connection.execute("select count(*) from users")
I end up with:
PG::ConnectionBad (could not connect to server: No such file or directory)
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
I can, however, connect to this old database by launching my rails console on heroku using DATABASE_URL as the env variable:
$ heroku run 'DATABASE_URL=postgres://...info... rails console' -a console' -a app
BUT I don't know how to switch back to my new database so I can update things.
How does one switch databases at run time when using rails console on heroku?
Why try to runtime switch the database? Why not have both connected at the same time and specify at the model level which database they read/write from? Rails supports connecting multiple databases and specifying in individual models what database connection to use: https://guides.rubyonrails.org/active_record_multiple_databases.html
The problem was that using url: didn't work and all parameters needed to be specified.
config = {"adapter"=>"postgresql", "encoding"=>"unicode", "pool"=>10, "username"=>"u...", "password"=>"p...", "port"=>5432, "database"=>"d...", "host"=>"ec2..."}
If you go for a 3tier database yml, you can use this:
config = ActiveRecord::Base.configurations["production"]["seconddb"]
Then, you can use establish_connection
ActiveRecord::Base.establish_connection(config)
ActiveRecord::Base.connection.execute("select count(*) from users")
Once I started specifying username, password, port, database and host, it all worked like a charm.
To work with both databases at the same time, a good way is to create a class
class OtherDB < ActiveRecord::Base
establish_connection(ActiveRecord::Base.configurations["production"]["seconddb"])
end
Then you can call things that way
OtherDB.table_name = "table_name"
OtherDB.first
ref (Establish a connection to another database only in a block?)
And to run SQL commands:
OtherDB.connection.execute("select count(*) from users")

Unable to CREATE DATABASE postgresql on Heroku Hobby database

I connected to Heroku postgresql DB (Hobby env):
heroku pg:psql --app
The prompt shows :
appname::DATABASE=>
Error :
appname::DATABASE=> CREATE DATABASE hello ENCODING 'UTF-8';
ERROR: permission denied to create database
Any help regarding this will be appreciated.
Creating a database is disallowed because it's unnecessary. When you provision a Heroku Postgres add-on, the database and user are created on your behalf. You can see the information by running heroku config and checking the database configuration string.

How to deal with foreign keys when moving a postgres database between machines

I'm trying to move a postgres database between machines as I move from one development platform to another. I have yaml_db gem installed on both machines.
On my old platform I do:
rake db:scheme:dump
rake db:data:dump
When I go to reload the database on my new machine I've discovered that my 2 dozen foreign_keys are preventing me for loading my data. What are my options?
You're copying a database, Rails really shouldn't have anything to do with the process (and as you're seeing, it just gets in the way).
Instead, put on your DBA hat and copy the database without bothering with Rails. Dump the data using pg_dump and then restore the data with pg_restore. The database's backup/restore tools know all about foreign keys, triggers, extensions, and anything else that Railsy tools don't understand.
you can use pg_dump command to dump your database using:
eg:
pg_dump -U <user-name> -h <host> <database> > <file-name>.sql
pg_dump -U postgres -h 127.0.0.1 database1 > database1.sql
Then copy file to other machine and run following command to restore database
psql <database-name> < path/to/sql_dump_file
psql database1 < database1.sql

Check db status through DATABASE_URL

I've been given access to Heroku application with rather strange setup. It has one database but when I run heroku config, I get different DATABASE_URL and HEROKU_POSTGRESQL_BRONZE_URL.
When I run heroku pg:info I get the following result:
=== HEROKU_POSTGRESQL_BRONZE_URL
Plan: Dev
Status: available
Connections: 1
PG Version: 9.2.4
Created: 2013-09-05 11:02 UTC
Data Size: 6.5 MB
Tables: 0
Rows: 0/10000 (In compliance)
Fork/Follow: Unsupported
I realised that my database is at DATABASE_URL, but I can't access that database, only through heroku run console. All heroku pg commands fail with this message:
! Unknown database: DATABASE_URL. Valid options are: HEROKU_POSTGRESQL_BRONZE_URL
If I run heroku pg HEROKU_POSTGRESQL_BRONZE_URL, I get access to empty database from above.
Since I have some issues with running migrations, I think my database might be full, and I'd like to check it. Any ideas how I can do that?
Here's the error after I run heroku run rake db:migrate:
PG::Error: ERROR: permission denied for relation schema_migrations
: INSERT INTO "schema_migrations" ("version") VALUES ('20130918114202')
More information about the setup:
rails 3.2.12
RAILS_ENV: staging (I don't have access to production, but I know this is "dev" server and there's also real "staging" from which this app was forked).
I have same problem and i fixed it:
Just Keep a Backup from your database and restore it back again, here is the steps:
heroku pg:info <-- to get the Database Name
heroku addons:add pgbackups <-- make sure you have the addons for backup
heroku pgbackups:capture <-- Capture the backup
heroku pgbackups <-- check your backups and make sure its there
heroku pg:reset DATABASE_NAME <-- Reset your database don't worry we have a backup, replace DATABASE_NAME with database name
heroku pgbackups:restore DATABASE_NAME b001 <-- Restore the backup again, replace DATABASE_NAME with database name and b001 with your Database version you can see this version number in heroku pgbackups step
heroku run rake db:migrate <-- Now you can run your migration and Operate in normal mode.
This seems like something screwy on the Heroku side. Have you tried submitting a ticket with them? I've always had good luck with their support.
I just got an update from my client. Before, I couldn't drop the database, because of the data in it. At the end, we decided to drop the database since the data can be added back (it's dev server, doesn't matter if we loose some dummy data).
I didn't find a solution for the problem above, but promoting HEROKU_POSTGRESQL_BRONZE_URL and restoring from backup solved the issue about not being able to access the database.

Installing Postgres on windows for use with Ruby-on-Rails

Currently I get the following error:
PGError (FATAL: password authentication failed for user "postgres" ):
when my app tries to access the database.
I wanted to test my SQL calls against postgres as my app regular breaks when pushed up to production on Heroku because of the stricter requirements of postgres (which I think is probably a healthy thing) over sqlite 3. So I have a similar request to this for a not out of date tutorial for installing postgres for use with ruby on rails on windows (7) please. I thought it'd be a quick 20 minutes of downloading and installing but 2 and a bit hours later and I don't think I'm very close yet. So far I've:
Downloaded and installed Postgres Version 8.4.8-1 from here
Set my environment variables such that Path (for User) is: C:\Ruby192\bin;C:\Program Files (x86)\PostgreSQL\8.4\bin
Gemfile:
gem 'pg', '0.11.0' # instead of gem 'sqlite3', '1.3.3'
ran bundle install for my rails app seemingly successfully, but haven't found easy way to validate installation yet.
set database.yml as suggested here to:
development:
adapter: postgresql
database: db/development
username: postgres
password: secret
host: localhost
encoding: UTF8
pool: 5
timeout: 5000
I know I need to set up a user name and password for Postgres, maybe also start the postgres server, connect to it(?) and put in my local IP address I'll connect to it on into a config files somewhere and then edit one of the other .conf files in 'C:\Program Files (x86)\PostgreSQL\8.4\data' etc...
I think Rails has made me soft, am I over thinking things or is it actually fairly tricky to set up and I should just go back to Sqlite3, for which there's also the awesomely useful SQLite Manager, Firefox plugin?
I'm still searching for a beginners guide to installing and using Postgres for rails but so far have only been confused by most of the stuff I look at / tried following like this, this, this, this, this(for Snow Leopard), this(linux).
Any pointers would be much appreciated. Thanks!
James
An approach to installing Postgres on windows 7 for use as PostgreSQL database for a rails 3 (3.0.7) project.
Preamble (you can skip this bit)
So the first thing to point out is that Postgres is not just a different file extension from .sqlite3, it's a whole mechanism for managing your databases. As such it has a client/server model, of which you'll need to set up both to use Postgres as the database for your rails app.
Motivation for going through considerable pain of Postgres setup versus almost effortless sqlite setup: if you're deploying to Heroku, they're currently using Postgres so some of your SQL calls that are fine on sqlite3 will break when used with Postgres. It's much easier to debug postgres locally rather than when it's on Heroku's servers.
So I did the following things:
(Disclaimer: I may have forgotten to include some of the things I did... it took me over 48 hours of on and off pain to get it to work... if the following advice doesn't work for you then the huge (2300 pages!!) but very thorough Postgres documentation should help. I'd recommend downloading this anyway if you're serious about using Postgres as it has a lot of material that I've only just begun to understand the significance of.)
(Second disclaimer: I have almost certainly broken 20 sensible Postgres guidelines and exposed security holes in the Postgres database whilst doing so. If there any obvious things an experienced Postgres user disagrees with, please edit my post.)
.Step 1. Download and install PostgreSQL v9.0.4-1 from here because here said only 9.0.x would be supported on windows 7. I kept all the default options and just used 'secret' as the password when prompted by the Postgres installer for one (again not entirely sure what the consequences of sharing that info on the internet is... will soon find out I'm sure). You'll need this password in step 3.
.Step 2. Change environment variables such that Path (for system, not user (I'm not sure if this is significant or not)) is: C:\Program Files\PostgreSQL\9.0\bin
(n.b. I'm on 64-bit windows hence it not being installed for 32-bit in 'C:\Program Files (x86)\PostgreS...')
Don't forget to change access rights to folder PostgreSQL\9.0 and remove any default readonly rights on the folder or content.
(You may also need to restart your computer for these to take effect - thanks #Gavin -although not likely).
.Step 3. Test Postgres installation by trying to create a new database:
From command line: createdb -U postgres mydb_as_postgres.
You should be prompted to enter the password now, if you're not it may be that you need to start the server first (I can't remember whether I needed to do this or not). The easiest way is through pgAdmin III, which should be 'pgAdmin3.exe' in a folder somewhere like C:\Program Files\PostgreSQL\9.0\bin. Once you've started pgAdmin III there should be a panel on the left called 'Object Browser'. In this there should be a tree with:
Server Groups > Servers > PostgreSQL 9.0 (localhost:5432)
Right click on 'PostgreSQL 9.0 (localhost:5432)' and select 'Connect'.
The createdb -U postgres mydb_as_postgres command should create a new databse called 'mydb_as_postgres' which you can check by firing up pgAdmin III and double clicking on 'PostgreSQL 9.0 (localhost:5432)'. Under this there should be:
Databases (2) which should list 2 databases called mydb_as_postgres and postgres
I called it _as_postgres because the -U postgres part of the command tells Postgres to create the database with the postgres user as it's owner, which you need to specify when you're not signed in as the postgres user. I have all of my files stored as 'AJames' user though so if you're the same and want to keep developing your app when signed in as a different user you need to create a Postgres 'role' for that user now (see step 4).
.Step 4. Through pgAdmin III. Right-click on Login Roles (which for me is in):
Object Browser > Server Groups > Servers > PostgreSQL 9.0 (localhost:5432) > Login Roles
Right-click on Login Roles and select 'New Login Role...'
in Role name, put in your operating system user name, which for me is AJames,
and fill in your password under the 'Role Privileges' tab, I checked all the boxes, but an experienced postgres user would likely strongly recommend to only check the 'inherits rights from parent roles' and the 'can create database objects' But I'm not an experienced user and just want to debug Rails SQL calls in Postgres so I also checked the 'Superuser' and 'Can create roles', just in case.
.Step 5. You should now be able to create a new database without being signed in as the postgres user. Try typing:
createdb mydb_as_user
Hopefully this should work for you.
.Step 6. Okay, so you've got a development.sqlite3 file in your rails 'db/' directory. Initially I was going to set the next test as converting this from sqlite3 to psql.
I couldn't get this to work though but I left my attempts here as the solution I used required having the data in a Rails app on Heroku.com (see instead the solution from step 7 onwards). For those who only have a local app and no data in Heroku, they can't use the same approach, so they might need to explore something like this:
x6.1 First, test 'psql' by trying a command from your command line like:
psql mydb_as_user
this should display something like below (after you've typed in your password):
C:>psql mydb_as_user
Password:
psql (9.0.4)
WARNING: Console code page (850) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
mydb5=#
x6.2 try entering:
CREATE TABLE users_table (id integer, "name" text);
It should display:
CREATE TABLE
mydb5=#
If you check in pgAdmin III, you should see the table there under:
Object Browser > Server Groups > Servers > PostgreSQL 9.0 (localhost:5432) > Databases > mydb_as_user > Schemas > public > Tables > users_table >
x6.3 Okay, next to try the conversion. Downloaded sqlite-shell precompiled binary for windows.
x6.4 Create a new directory, I used 'C:\temp' and put the sqlite3.exe and your development.sqlite3 files in it.
x6.5 Use the following commands (which are from here) to dump the development.sqlite3 database into Postgres.
sqlite3 development .dump | psql development2
you might get an error like:
psql: FATAL: database "development2" does not exist
x6.6 so I went into pgAdmin III and made a development 2 database, tried the command again and got:
ERROR: syntax error at or near "PRAGMA"
LINE 1: PRAGMA foreign_keys=OFF;
^
BEGIN
COMMIT
Like I said, I couldn't get it to work. I'm sure there's a way of getting round that error but I thought of a different way and so I instead used this solution (which requires a Heroku account to have your data and does the conversion from sqlite3 to psql using the Taps gem (I believe):
.Step 7. in pgAdmin III I created another database. Under the properties tab I set name: 'development', owner: 'AJames' (replace this with your own Windows user name). And under the privileges tab, set role: 'public' and checked the ALL option (thought this resets to unchecked so I'm not sure that's necessary).
.Step 8. add
gem 'pg', '0.11.0'
to your gem file. You'll probably also want to remove the:
gem 'sqlite3'
at this point too.
.Step 9. set database.yml as suggested here to:
development:
adapter: postgresql
database: db/development
username: AJames # replace this with your own user name
password: secret # replace this with your own password
host: localhost
encoding: UTF8
pool: 5
timeout: 5000
If you are working on an open source project and don't want your password to be made publicly available, have a look at some of the answers to Securely providing the database password in a Rails app.
.Step 10. from command line in your rails app's root directory run:
rake db:migrate
This will create the new schema and all the tables in the Postgres database.
.Step 11. run heroku db:pull from your command line (again from in the root directory of your rails app) to pull all your data down and into your new empty Postgres database. I think at this point your taps gem will be doing this work for you.
.Step 12. Hopefully there is no step 12! ...and it should now be working for you. Happy RoR PostgreSQL debugging! Please edit, or let me know, if there are any errors in this.
Also, here's a list of additional stuff that might be interesting/useful:
This is a blog post about Postgres passwords, what they're for,
why you need them, how to change them etc.
This, under 'Creating a spatial database', is useful for newbies to
understand what pg_hba.conf is about and the second link that
Reno gave above, under the 'Using pgAdmin III GUI' is useful to
testing to see if postgres is actually working, before trying to fit
it with Rails (i.e. try creating a database and putting a table and
some data into it).
In the huge but very comprehensive Postgres documentation, I'd
start on page 58, 'I. tutorial'. Then on pdf page 431(!) there's
'Chapter 17. Server setup and operation' that I also found useful.
the answer from AJP is the correct one with just a small re-config.
The line
database: db/development
does not work for me.
I have to change it to
database: development
I use this for ruby on rails for the command
rake db:create
and
rake db:migrate
to work
None of your links appeared to be the (arguably) most useful documentation - the official postgresql docs. I recently configure a Linux Mint box with postgresql and django using a combination of those documents and these, though the latter are specific to Linux.
I'd worry more about validating the postgresql side of things, less about rails. That is to say, your question should be "How can I set up and test a postgresql server on a Windows 7 box", moreso than you need to know how to get it locked into rails.
Edit:
Maybe this could also be of use to you - official postgresql wiki with detailed installation guides.
Good luck!

Resources