Prime user table for the first user

24 views
Skip to first unread message

Ralph Shnelvar

unread,
Jul 11, 2017, 9:33:05 AM7/11/17
to Ruby on Rails: Talk
Let's say I expect to have a billion users in my Postgres users table.

I want to make sure the first user gets to set it's role attribute to enum :admin as the default when the record is created and all other users are enum  :user.

Of course a billion users is ridiculous.  I'm just trying to understand what the, uh, best way to see if a Postgres table is empty without actually having to load it.

Hassan Schroeder

unread,
Jul 11, 2017, 11:06:10 AM7/11/17
to rubyonrails-talk
On Tue, Jul 11, 2017 at 6:33 AM, Ralph Shnelvar <ral...@dos32.com> wrote:

> I want to make sure the first user gets to set it's role attribute to enum
> :admin as the default when the record is created and all other users are
> enum :user.
>
> Of course a billion users is ridiculous. I'm just trying to understand what
> the, uh, best way to see if a Postgres table is empty without actually
> having to load it.

Assuming the table is "users" and User is an ActiveRecord model,
(User.count == 0)
should work.

However, doing that for every subsequent user creation seems like
a bit of a waste. I would just use the db/seeds.rb file to create that
first admin user and be done with it :-)

FWIW,
--
Hassan Schroeder ------------------------ hassan.s...@gmail.com
twitter: @hassan
Consulting Availability : Silicon Valley or remote

Matt Jones

unread,
Jul 13, 2017, 8:06:35 AM7/13/17
to Ruby on Rails: Talk
I suspect `User.exists?` is going to be the lightest possible option. `User.count == 0` will also work, but I know there are some DBs where that operation can be expensive on large tables.

This is still going to do a query every time it checks, so if that's too much load you could cache the result:

class User < ActiveRecord::Base
  def self.any_users?
    @any_users ||= exists?
  end
end

Then your role-defaulting code can check `self.class.any_users?`, which will only run one query (per server) that returns true.

NOTE NOTE NOTE: the above is not 100% thread-safe. It assumes that there is exactly one user sending requests trying to be the first. If you're worried about somebody racing to sign up for that first account, you'll want to come up with a more secure approach.

--Matt Jones
Reply all
Reply to author
Forward
0 new messages