使用PostgreSQL时,角色不存在且无法创建数据库。

64

我在使用Heroku来构建我的应用程序,需要使用PostgreSQL数据库,但仍然可以在开发时使用SQLite3。由于Heroku强烈反对在同一应用程序中使用两种不同的数据库,因此我决定将开发环境改为使用PostgreSQL。我安装了gem pg,并访问了官方的PostgreSQL网站以获取Windows安装程序,并更改了database.yml文件。在安装过程中,需要设置一个PostgreSQL密码,因此我设置了一个密码。 我不得不将pg_hba.conf文件从使用md5更改为trust,以便在尝试创建数据库时避免出现fe_sendauth: no password supplied错误。

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# IPv4 local connections:
host    all             all             127.0.0.1/32            trust # was md5
# IPv6 local connections:
host    all             all             ::1/128                 trust # was md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#host    replication     postgres        127.0.0.1/32            trust
#host    replication     postgres        ::1/128                 trust

摆脱了那个问题后,现在出现了这个:
$ rake db:create
(in C:/app)
FATAL:  role "User" does not exist 
Couldn't create database for {"adapter"=>"postgresql", "encoding"=>"utf8", 
"database"=>"app_test", "pool"=>5, "username"=>nil, "password"=>nil} 

我仍然有我的development.sqlite3text.sqlite3,这可能是问题吗?需要做什么?

这是我的完整代码:https://gist.github.com/1522188

3个回答

139

在你的database.yml中添加一个用户名,最好使用你的应用程序名称(或名称变体)作为用户名,我将使用app_name作为占位符:

development:
  adapter: postgresql
  encoding: utf8
  database: app_development
  pool: 5
  username: app_name
  password:

然后使用 psql.exe 在 PostgreSQL 中创建用户(也称为“角色”):

$ psql -d postgres
postgres=# create role app_name login createdb;
postgres=# \q

第一行是在你的终端中,接下来两行在psql中。然后执行rake db:create

User用户可能是默认用户,但在PostgreSQL中user已经被占用,所以如果你想使用User作为用户名,你需要引用它来保留大小写:

postgres=# create role "User" login createdb;

无论如何,每个应用程序最好创建一个用户。

您还需要对database.yml中的test条目进行类似的操作。


2
它不让我进入 psql.exe。当我尝试打开它时,窗口会弹出然后自动关闭,所以我尝试去命令提示符并输入 c:\Program Files..\..\bin > psql.exe > psql: FATAL: role "User" does not exist 再次得到 FATAL。有什么想法吗? - LearningRoR
2
@wrbg:你在安装时创建了一个 postgres 用户,对吧?如果需要密码,则尝试 psql -d postgres -U postgres -W。如果不需要密码,则使用 psql -d postgres -U postgres - mu is too short
3
你能执行 psql -d postgres -U postgres 吗? - mu is too short
1
@wrbg:尝试使用create role app_name login createdbalter role app_name createdb,然后再运行rake db:create。我上次执行此操作时可能设置了不同的默认值。 - mu is too short
2
@wrbg:您可以在 psql 中使用 \du 命令查看用户/角色及其权限,或使用 \l 命令列出数据库。如果您的用户设置正确,则 rake db:create 命令应该会创建数据库,而 psql -U app_name -d app_development 命令则可进入该数据库。 - mu is too short
显示剩余7条评论

10
如果您的机器上有一个特定的账户/用户,例如名为postgres,则执行此命令将为您带来一个提示,要求您输入角色名称。
sudo -u postgres createuser --interactive

然后执行

rake db:create

应该有效!


10

如果在config/database.yml中没有指定username,PostgreSQL会尝试使用您的帐户(登录)名称来创建数据库。在OS X和Linux上,您可以使用whoami查看此用户。看起来您正在使用Windows。

解决方案A: 创建一个与所需用户名匹配的PostgreSQL用户。例如:

createuser --superuser some_user

解决方案B: 通过显式地设置用户名(如mu的答案所示)来更改数据库用户。


真的需要 --superuser 吗?还是 -d 就足够了? - Meekohi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接