Search code examples
ruby-on-railsfacebookpostgresqltypes

What datatype to use for Facebook user id in Rails and PostgreSQL


I have a PostgreSQL database for a Rails application.

I want to store the Facebook user id so I thought I could use integer but its not big enough so I chose float.

However now Rails adds .0 to the end of my user id's

What datatype can I use so this does not happen for Facebook user ids which are very long example: 100002496803785


Solution

  • You can use :limit => 8 on your integer column to get a bigint. For example:

    class Pancakes < ActiveRecord::Migration
        def change
            create_table :pancakes do |t|
                t.integer :c, :limit => 8
            end
        end
    end
    

    And then, from psql:

    => \d pancakes
                             Table "public.pancakes"
     Column |  Type   |                       Modifiers                       
    --------+---------+-------------------------------------------------------
     id     | integer | not null default nextval('pancakes_id_seq'::regclass)
     c      | bigint  | not null
    Indexes:
        "pancakes_pkey" PRIMARY KEY, btree (id)
    

    And there's your eight byte bigint column.

    You could also use a string for the Facebook ID. You're not doing any arithmetic on the IDs so they're really just opaque bags of bits that happen to look like large integers, strings will sort and compare just fine so they might be the best option. There would be some storage and access overhead due to the increased size of a string over the integer but it probably wouldn't be enough to make any noticeable difference.

    Never use a double for something that needs to be exact. You'd probably be fine (except for the trailing .0 of course) in this case because you'd have 52 bits of mantissa and that means that the double would act like a 52 bit integer until your values got large enough to require the exponent. Even so, using double for this would be an awful idea and an abuse of the type system.