Rails + Postgres drop error: database is being accessed by other users - ruby-on-rails

I have a rails application running over Postgres.
I have two servers: one for testing and the other for production.
Very often I need to clone the production DB on the test server.
The command I'm runnig via Vlad is:
rake RAILS_ENV='test_server' db:drop db:create
The problem I'm having is that I receive the following error:
ActiveRecord::StatementInvalid: PGError: ERROR: database <database_name> is being accessed by other users DROP DATABASE IF EXISTS <database_name>
This happens if someone has accessed the application via web recently (postgres keeps a "session" opened)
Is there any way that I can terminate the sessions on the postgres DB?
Thank you.
Edit
I can delete the database using phppgadmin's interface but not with the rake task.
How can I replicate phppgadmin's drop with a rake task?

If you kill the running postgresql connections for your application, you can then run db:drop just fine. So how to kill those connections? I use the following rake task:
# lib/tasks/kill_postgres_connections.rake
task :kill_postgres_connections => :environment do
db_name = "#{File.basename(Rails.root)}_#{Rails.env}"
sh = <<EOF
ps xa \
| grep postgres: \
| grep #{db_name} \
| grep -v grep \
| awk '{print $1}' \
| xargs kill
EOF
puts `#{sh}`
end
task "db:drop" => :kill_postgres_connections
Killing the connections out from under rails will sometimes cause it to barf the next time you try to load a page, but reloading it again re-establishes the connection.

Easier and more updated way is:
1. Use ps -ef | grep postgres to find the connection #
2. sudo kill -9 "# of the connection
Note: There may be identical PID. Killing one kills all.

Here's a quick way to kill all the connections to your postgres database.
sudo kill -9 `ps -u postgres -o pid`
Warning: this will kill any running processes that the postgres user has open, so make sure you want to do this first.

I use the following rake task to override the Rails drop_database method.
lib/database.rake
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
def drop_database(name)
raise "Nah, I won't drop the production database" if Rails.env.production?
execute <<-SQL
UPDATE pg_catalog.pg_database
SET datallowconn=false WHERE datname='#{name}'
SQL
execute <<-SQL
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '#{name}';
SQL
execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}"
end
end
end
end

When we used the "kill processes" method from above, the db:drop was failing (if :kill_postgres_connections was prerequisite). I believe it was because the connection which that rake command was using was being killed. Instead, we are using a sql command to drop the connection. This works as a prerequisite for db:drop, avoids the risk of killing processes via a rather complex command, and it should work on any OS (gentoo required different syntax for kill).
cmd = %(psql -c "SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE procpid <> pg_backend_pid();" -d '#{db_name}')
Here is a rake task that reads the database name from database.yml and runs an improved (IMHO) command. It also adds db:kill_postgres_connections as a prerequisite to db:drop. It includes a warning that yells after you upgrade rails, indicating that this patch may no longer be needed.
see: https://gist.github.com/4455341, references included

Step 1
Get a list of all postgres connections with ps -ef | grep postgres
The list will look like this:
502 560 553 0 Thu08am ?? 0:00.69 postgres: checkpointer process
502 565 553 0 Thu08am ?? 0:00.06 postgres: bgworker: logical replication launcher
502 45605 553 0 2:23am ?? 0:00.01 postgres: st myapp_development [local] idle
Step 2
Stop whatever connection you want with sudo kill -9 <pid>, where pid is the value in the second column. In my case, I wanted to stop the last row, with pid 45605, so I use:
sudo kill -9 45605

Please check if your rails console or server is running in another tab and then
stop the rails server and console.
then run
rake db:drop

Let your application close the connection when it's done. PostgreSQL doesn't keep connections open , it's the application keeping the connection.

I wrote a gem called pgreset that will automatically kill connections to the database in question when you run rake db:drop (or db:reset, etc). All you have to do is add it to your Gemfile and this issue should go away. At the time of this writing it works with Rails 4 and up and has been tested on Postgres 9.x. Source code is available on github for anyone interested.
gem 'pgreset'

Rails is likely connecting to the database to drop it but when you log in via phppgadmin it is logging in via the template1 or postgres database, thus you are not affected by it.

This worked for me (rails 6):
rake db:drop:_unsafe
I think we had something in our codebase that initiated a db connection before the rake task attempted to drop it.

After restarting the server or computer, please try again.
It could be the simple solution.

You can simply monkeypatch the ActiveRecord code that does the dropping.
For Rails 3.x:
# lib/tasks/databases.rake
def drop_database(config)
raise 'Only for Postgres...' unless config['adapter'] == 'postgresql'
Rake::Task['environment'].invoke
ActiveRecord::Base.connection.select_all "select pg_terminate_backend(pg_stat_activity.pid) from pg_stat_activity where datname='#{config['database']}' AND state='idle';"
ActiveRecord::Base.establish_connection config.merge('database' => 'postgres', 'schema_search_path' => 'public')
ActiveRecord::Base.connection.drop_database config['database']
end
For Rails 4.x:
# config/initializers/postgresql_database_tasks.rb
module ActiveRecord
module Tasks
class PostgreSQLDatabaseTasks
def drop
establish_master_connection
connection.select_all "select pg_terminate_backend(pg_stat_activity.pid) from pg_stat_activity where datname='#{configuration['database']}' AND state='idle';"
connection.drop_database configuration['database']
end
end
end
end
(from: http://www.krautcomputing.com/blog/2014/01/10/how-to-drop-your-postgres-database-with-rails-4/)

I had this same issue when working with a Rails 5.2 application and PostgreSQL database in production.
Here's how I solved it:
First, log out every connection to the database server on the PGAdmin Client if any.
Stop every session using the database from the terminal.
sudo kill -9 `ps -u postgres -o pid=`
Start the PostgreSQL server, since the kill operation above stopped the PostgreSQL server.
sudo systemctl start postgresql
Drop the database in the production environment appending the production arguments.
rails db:drop RAILS_ENV=production DISABLE_DATABASE_ENVIRONMENT_CHECK=1
That's all.
I hope this helps

[OSX][Development/Test] Sometimes it is hard to determine the proper PID when you have a lot of PostgreSQL processes like checkpointer, autovacuum launcher, etc. In this case, you can simply run:
brew services restart postgresql#12

If you dockerized your app, then restart your db service
sudo docker-compose restart db

Just make sure that the you have exited the rails console on any open terminal window and exited the rails server...this is one of the most common mistake made by people

I had a similar error saying 1 user was using the database, I realized it was ME! I shut down my rails server and then did the rake:drop command and it worked!

Solution
Bash script
ENV=development
# restart postgresql
brew services restart postgresql
# get name of the db from rails app
RAILS_CONSOLE_COMMAND="bundle exec rails c -e $ENV"
DB_NAME=$(echo 'ActiveRecord::Base.connection_config[:database]' | $RAILS_CONSOLE_COMMAND | tail -2 | tr -d '\"')
# delete all connections to $DB_NAME
for pid in $(ps -ef | grep $DB_NAME | awk {'print$2'})
do
kill -9 $pid
done
# drop db
DISABLE_DATABASE_ENVIRONMENT_CHECK=1 RAILS_ENV=$ENV bundle exec rails db:drop:_unsafe

ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database "database_enviroment" is being accessed by other users
DETAIL: There is 1 other session using the database.
For rails 7: you can use -> rails db:purge

Related

Unable to make 'rake db:drop' work in development with Rails 5.1.4

I'm no longer able to rake db:drop since I upgraded from Rails 4.2 to Rails 5.1.4.
I get the following error message whenever I try to run the task:
PG::ObjectInUse: ERROR: database "myapp_development" is being
accessed by other users
DETAIL: There is 1 other session using the database.
: DROP DATABASE IF EXISTS "myapp_development"
Couldn't drop database 'myapp_development'
rails aborted!
ActiveRecord::StatementInvalid: PG::ObjectInUse: ERROR: database
"myapp_development" is being accessed by other users
DETAIL: There is 1 other session using the database.
: DROP DATABASE IF EXISTS "myapp_development"
I used to make it work with this hack:
Rails + Postgres drop error: database is being accessed by other users
Now, when I integrate this solution into my application, I get another error message:
FATAL: terminating connection due to administrator command
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
Couldn't drop database 'myapp_development'
rails aborted!
PG::AdminShutdown: FATAL: terminating connection due to
administrator command
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
Do you guys have a fix for this issue?
Btw, I'm running Postgres 9.6, ruby 2.4.2 and Rails 5.1.4.
Can you try to restart your DB,
For postgres
sudo service postgresql restart
then try
rails db:drop / rake db:drop, maybe it will work
To drop your database your database should not be accessed by any application.
This error tells that
1. you are using rails console which is using database OR,
2. you are using some tools tool postico,pgadmin, mysql workbench which is
accessing database OR
3. you are using IDE like rubymine and accessing
database via it OR
4. there is sidekiq or any other background job
server running which accessing it.
Solution:
Before dropping database take care of following things
exit all rails console,
close database tools like mysql workbench,pgadmin
close database tabs in IDE
stop sidekiq or any other background job
Why ?
database "myapp_development" is being accessed by other users.
You will get this error if your database is being opened either in console i.e rails c or rails s or any other mode.
Solution
1.Close console wherever you opened rails c or stop server if running
2.If you are unable to find console or server running i.e if everything closed still you are gettin error. Then try to close running process using below command
ps -au
This command will show all running processes.Just find keyword rails c/localhost/postgres.You can also filter processes using grep command like this
ps -au | grep 'rails c'
And kill the process using below command
kill -9 PID_NUMBER // PID NUMBER you will find in second column when you run ps -au.
It means that the database is being used by a user other than the one attempting to drop the table. The user attempting to drop the table is the one specified in config/database.yml
To see how that is, do:
za:myapp za$ cat config/database.yml | grep username
#username: myapp
# The password associated with the postgres role (username).
username: myapp
Make sure that no other user is connected to the database while you are trying to drop it. In my case, another user "za" was connected to the database. I killed the session of that user and all went well.
za:myapp za$ rails db:drop
Dropped database 'myapp_development'
Dropped database 'myapp_test'
Back to work, create and then migrate:
za:myapp za$ rake db:create
za:myapp za$ rake db:migrate
RubyDep: WARNING: (To disable warnings, see:http://github.com/e2/ruby_dep/wiki/Disabling-warnings )
== 20180218181904 DeviseCreateUsers: migrating ================================
-- create_table(:users)
-> 0.0286s
-- add_index(:users, :email, {:unique=>true})
-> 0.0183s
-- add_index(:users, :reset_password_token, {:unique=>true})
-> 0.0036s
== 20180218181904 DeviseCreateUsers: migrated (0.0507s) =======================

Can't stop rails server

I am new to rails and I am using an ubuntu machine and the rubymine IDE. The problem is that I am unable to stop the rails server. I tried to stop the server by killing the rails process. But, when I run pgrep -l rails, no such process is found. So, I am only able to kill ruby processes, but, the server won't stop.
I tried ./script/server stop (since I started it by running ./script/server start), but, that didn't work. Googling around and finding some stackoverflow posts, I tried to change the localhost port's listening port but without success. Could someone help?
You can use other ports like the following:
rails server -p 3001
Normally in your terminal you can try Ctrl + C to shutdown the server.
The other way to kill the Ruby on Rails default server (which is WEBrick) is:
kill -INT $(cat tmp/pids/server.pid)
In your terminal to find out the PID of the process:
$ lsof -wni tcp:3000
Then, use the number in the PID column to kill the process:
For example:
$ kill -9 PID
And some of the other answers i found is:
To stop the rails server while it's running, press:
CTRL-C
CTRL-Z
You will get control back to bash. Then type (without the $):
$ fg
And this will go back into the process, and then quit out of Rails s properly.
It's a little annoying, but this sure beats killing the process manually. It's not too bad and it's the best I could figure out.
Updated answer:
You can use killall -9 rails to kill all running apps with "rails" in the name.
killall -9 rails
you can use grep command in following way,
ps aux | grep rails
and then
kill -9 {process_id}
pkill -9 rails to kill all the process of rails
Updated answer
ps aux|grep 'rails'|grep -v 'grep'|awk '{ print $2 }'|xargs kill -9
This will kill any running rails process. Replace 'rails' with something else to kill any other processes.
On my MAC the killall -9 rails does not work. But killall -9 ruby does.
Following are steps to kill server process:
1. lsof -i tcp:3000
2. kill -9 1234
where 1234 is the PID of process: localhost:3000 display in step 1.
OR
Remove file(server.pid) under Rails.root/tmp/pids/ and restart server.
OR
open app in another port by using command:
rails s -p 3001
I generally use:
killall ruby
OR
pkill -9 ruby
which will kill all ruby related processes that are running like rails server, rails console, etc.
1. Simply Delete the pid file from rails app directory
Rails_app -> tmp -> pids -> pid file
Delete the file and run
rails start
2. For Rails 5.0 and above, you can use this command
rails restart
If you are using a more modern version of Rails and it uses Puma as the web server, you can run the following command to find the stuck Puma process:
ps aux | grep puma
It will result in output similar to this:
85923 100.0 0.8 2682420 131324 s004 R+ 2:54pm 3:27.92 puma 3.12.0 (tcp://0.0.0.0:3010) [my-app]
92463 0.0 0.0 2458404 1976 s008 S+ 3:09pm 0:00.00 grep puma
You want the process that is not referring to grep. In this case, the process ID is 85923.
I can then run the following command to kill that process:
kill -9 85923
Use ctrl+c to shutdown your Webrick Server.
Unfortunately if its not works then forcefully close the terminal and restart it.
Another trick is that
1. open your system-monitor(a gui application) on ubuntu
2. Select processes tab
3. Then look for a process having name 'ruby'
4. End that process
Delete the server.pid from tmp/pids folder.
In my case, the error was: A server is already running. Check /home/sbhatta/myapp/tmp/pids/server.pid.
So, I delete server.pid
rm /home/sbhatta/myapp/tmp/pids/server.pid
then run rails s
Ctrl-Z should normally do the trick.
Step 1: find what are the items are consuming 3000 port.
lsof -i:3000
step 2 : Find the process named
For Mac
ruby TCP localhost:hbci (LISTEN)
For Ubuntu
ruby TCP *:3000 (LISTEN)
Step 3: Find the PID of the process and kill it.
kill -9 PID
it's as simple as
pkill -9 ruby
nothing more nothing less
I used killall -9 rails like Sri suggested and it didn't work. I adjusted the command to killall -9 ruby and the server closed immediately.
Tl;dr: killall -9 ruby
When the rails server does not start it means that it is already running then you can start by using new port eg.
rails s -p 3001
or it starts and stops in that case you want to delete temp folder in rails directory structure it starts the rails server.
check the /tmp/tmp/server.pid
there is a pid inside.
Usually, I ill do "kill -9 THE_PID" in the cmd
I have noticed on Windows (Im using 10 but not sure if the same for oler). If you use cmd.exe and ctrl + c the raisl server stops correctly.
However, if you use Git Bash, it doesn't. It says it has but when you look at the tmp pids, its still there.
Maybe a bug with git bash?
killall -9 ruby will kill all the ruby processes, and at-least on my machine, rails servers appear as ruby processes. killall -9 rails is much more specific and doesn't work for older versions of rails servers (it gives a 'rails:no process found' because the process is named ruby)
Encountered this problem a while ago. After submitting a form in activeadmin, the rails server just hanged and I was unable to kill it using normal means (even after ctrl+z it was still running in the background). Learner's answer helped, but this command doesn't need process id.
Follow these steps:
open your project
select in tmp folder
select pids folder
delete server.pid file
now start your rails server
On rails 6 using
ps aux | grep rails was not returning the server process
I had to do
ps aux | grep puma
to find the actual process and then kill it using
kill -9 {process_id}
It is late for this question.
Here is my 2 cents. I made a rake task for stopping the server when I don't have access to it.
I only tested on Mac though.
With this you can simply add it to your project then run the rake command.
Here you go:
Gist link: -latest version will be here.
https://gist.github.com/houmanka/289184ca5d8d92de0499#file-server-rake
Some code in here:
# Make a file under: `project_root/lib/tasks/server.rake`
# Then paste the following code
namespace :server do
desc "Stop the running server by killing the PID"
task :kill do
STDOUT.puts "Enter port number: "
post_number = STDIN.gets.strip
system "pid=$(lsof -i:#{post_number.to_i} -t); kill -TERM $pid || kill -KILL $pid"
end
end
# Then to use it in the terminal: `rake server:kill`
Also, Make sure that you are doing command Cntrl+C in the same terminal (tab) which is used to start the server.
In my case, I had 2 tabs but i forgot to stop the server from correct tab and i was wondering why Cntrl+C is not working.
One super easy way would be
gem install shutup
then go in the current folder of your rails project and run
shutup # this will kill the Rails process currently running
You can use the command 'shutup' every time you want
DICLAIMER: I am the creator of this gem
NOTE: if you are using rvm install the gem globally
rvm #global do gem install shutup
For my windows 10 machine, Ctrl - C + Ctrl - D works.
We can kill rails session on Linux using PORT no
fuser -k 3000/tcp
here 3000 is a port no.
Now restart your server, you will see your server is in running state.
Just open the file using the location given
sudo vi /Users/user1/go/src/github.com/rails_app/rails_project/tmp/pids/server.pid
find the process_id / thread_id at which the process is runnning.
Kill the specified process / thread using kill -9 84699
Press Ctrl - C it will stop
if not check

stop start database

I am developing Rails v2.3 app. and using MySQL v5.1 .
I need to stop and start mysql database in one of my rake task, but I am not sure how to implement this thing, could some one help me?
namespace :db do
task :some_db_task => :environment do
#shut down mysql
...
#start mysql
end
end
By the way, I am developing on Ubuntu machine.
----------------------- update ----------------------------
I tried exec "/etc/init.d/mysql stop" , I got the following error message:
Rather than invoking init scripts through /etc/init.d, use the service(8)
utility, e.g. service mysql stop
Since the script you are attempting to invoke has been converted to an
Upstart job, you may also use the stop(8) utility, e.g. stop mysql
stop: Rejected send message, 1 matched rules; type="method_call", sender=":1.78" (uid=1000 pid=6331 comm="stop) interface="com.ubuntu.Upstart0_6.Job" member="Stop" error name="(unset)" requested_reply=0 destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init"))
I tried /etc/init.d/mysql stop also on command line, the same error raise,
By following the error message's instruction, I then tried service mysql stop , I got a new error message:
stop: Rejected send message, 1 matched rules; type="method_call", sender=":1.79" (uid=1000 pid=6343 comm="stop) interface="com.ubuntu.Upstart0_6.Job" member="Stop" error name="(unset)" requested_reply=0 destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init"))
why I can not stop mysql??
--------------- update 2 -------------------------
I realize that even though the above mentioned error message shows, the sudo /etc/init.d/mysql stop actually done its job. The MySQL get stopped by this command, meanwhile the message raising.
I'd prefer using system("sudo /etc/init.d/mysqld stop") so you can be sure the database has stoped. system() waits for the command to be executed while exec starts a background thread.
#update you may need "sudo service mysql stop" if you are using ubuntu lucid or newer
Perhaps something like the following?
namespace :db do
task :start do
exec "sudo /etc/init.d/mysqld start"
end
task :stop do
exec "sudo /etc/init.d/mysqld stop"
end
end
you can execute shell command in ruby using exec method as below
exec "/etc/rc.d/init.d/mysqld start" #start mySql
exec "/etc/rc.d/init.d/mysqld stop" #stop mySql

run multi delayed_job instances per RAILS_ENV

I'm working on a Rails app with multi RAILS_Env
env_name1:
adapter: mysql
username: root
password:
host: localhost
database: db_name_1
env_name2:
adapter: mysql
username: root
password:
host: localhost
database: db_name_2
...
..
.
And i'm using delayed_job (2.0.5) plugin to manage asynchrone and background work.
I would like start multi delayed_job per RAILS_ENV:
RAILS_ENV=env_name1 script/delayed_job start
RAILS_ENV=env_name2 script/delayed_job start
..
I noticed that I can run only one delayed_job instance
for the 2nd, I have this error "ERROR: there is already one or more instance(s) of the program running"
My question : is't possible to run multi delayed_job instances per RAILS_ENV?
Thanks
You can have multiple instance of delayed job running as long as they have different process names. Like Slim mentioned in his comment, you can use the -i flag to add a unique numerical identifier to the process name. So the commands would look like:
RAILS_ENV=env_name1 script/delayed_job -i 1 start
RAILS_ENV=env_name2 script/delayed_job -i 2 start
This would create two seperate delayed job instances, naming them delayed_job.1 and delayed_job.2
A gotcha is that when you do this you also have to use the same flags when stopping them. Omitting the -i 1 or -i 2 when calling stop, won't stop them. As delayed job won't be able to find the correct corresponding process to stop.
Not sure if it'll solve your problem but... I often need to run multiple versions of script/server - and those don't play nice with each other either. The way to get them running is to use different ports. eg:
RAILS_ENV=env_name1 script/server -p 3000
RAILS_ENV=env_name2 script/server -p 3002
Perhaps this'll work for delayed_job too?
(though I'd avoid port 3000 as it's the std rails port) :)

PGError: ERROR: source database "template1" is being accessed by other users

I'm having problems getting testing to work with Postgresql and Rails 3.
Both development and production databases I can get to work fine, however the test database throws the following errors when I run rake or db:test:prepare, etc.
PGError: ERROR: source database "template1" is being accessed by other users
Update
Googling around, it seems that one should use template0 instead of template1 when using createdb to create a new database in Postgres. In typical “So I’ll remove the cause. But not the symptom” fashion, I found vendor/rails/railities/lib/task/databases.rake and changed line 109 to read:
createdb #{enc_option} \
-U "#{abcs["test"]["username"]}" \
-T template0 #{abcs["test"]["database"]}
But I don't really wanna do that, as I'm using Rails as a GEM, any one know of another work around or fix?
database.yml:
development:
adapter: postgresql
encoding: unicode
database: test1234_development
pool: 5
username: holden
password: postgres
test:
adapter: postgresql
encoding: unicode
database: test1234_test
pool: 5
username: holden
password: postgres
Full error:
NOTICE: database "test1234_test" does not exist, skipping
PGError: ERROR: source database "template1" is being accessed by other users
DETAIL: There are 1 other session(s) using the database.
: CREATE DATABASE "test1234_test" ENCODING = 'unicode'
Short story: CREATE DATABASE works by copying an existing database. PostgreSQL won't let you copy a database if another session is connected to it. If template1 is being accessed by other users, CREATE DATABASE will fail.
The question you need to answer: Why are other sessions connected to template1?
The difference between template0 and template1
At the point you initialize a database cluster, template0 and template1 are the same. Any location-specific stuff you want to make available to every database you create by using CREATE DATABASE should go into template1. So, for example, if you add the procedural langauge PL/python to template1, every database you create later will include PL/python.
The database template0 is intended to be a "virgin" template. It should contain only standard database objects--the ones created by initializing the cluster. As a "virgin" template, it should never be changed. Never.
If you need to specify encoding and locale settings (collation), then you can do that by copying template0. You can't do that by copying template1.
This problem occur when you had logged(psql template1 or psql template0) in template1 and template0 database and exit using below command.
Ctrl + z
Better way exist from db use below postgres command then problem will not create:
\q + enter
There are 2 solutions, If have problem.
Solution - 1
Restart posgres service like.
sudo service postgresql restart
Solution - 2
sudo ps aux | grep template1
Make sure don't delete this processes
postgres 8363 0.0 0.0 111760 7832 pts/11 T 09:49 0:00 /usr/lib/postgresql/9.5/bin/psql template1
ankit 18119 0.0 0.0 14224 976 pts/14 S+ 12:33 0:00 grep --color=auto template1
rest of process should be kill using below command.
sudo kill -9
Now try to create db again.
Hope this help you.
Ankit H Gandhi.
Just restart the service of database.
I restarted my system and the error was still showing. However, I followed the steps below to sort it out.
Stop all processes using the postgres port 5432 by doing this in command prompt (Admin): Type netstat -ano in command prompt. Find the pid with Local Address of 0.0.0.0:5432. Then use taskkill /pid {pid} /f to kill the task.
Start the postgres service in windows services.
I also got this error while trying to reset the database while I had the default Ruby on Rails server WEBrick running:
$ bin/rake db:reset
PG::Error: ERROR: database "dev" is being accessed by other users
DETAIL: There is 1 other session using the database.
: DROP DATABASE IF EXISTS "dev"
The other user here was the running Rails app. After shutting down the server with CTRL + c, I was able to re-run the database reset command without any problems.
It makes sense too. You can't drop the database if someone else is currently connected to it, as Mike Sherrill also points out.
Solution for me was to delete old server and create a new one from Postgresql administration web interface. Could now create new database without this error.
I was also stuck setting up postgres on ruby on rails project, ensure that you have installed pg locally and created a user with its password then on your database.yml should have:- host: localhost, password: (set password) then run:
$ rails db:create
$ rails db:migrate

Resources