Prime user table for the first user

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.

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 :slight_smile:

FWIW,

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