Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3/postgres - how long is a string if you don't apply :limit in schema

My googlefu must be weak because I cannot find anything to tell me the default limit of a string column in my Rails app (hosted at Heroku, using PostgreSQL as the database).

Any help would be appreciated!

like image 531
jpw Avatar asked Nov 14 '11 23:11

jpw


2 Answers

ActiveRecord uses varchar(255) (or character varying (255) to be pedantic) if you don't specify a specific limit. You can always hop into PostgreSQL with psql and say \d your_table to get the table as PostgreSQL sees it.

I don't think the default is specified anywhere but it is right here in the source:

NATIVE_DATABASE_TYPES = {
  :primary_key => "serial primary key",
  :string      => { :name => "character varying", :limit => 255 },
  #...

The closest thing to a specification is in the Migrations Guide:

These will be mapped onto an appropriate underlying database type, for example with MySQL :string is mapped to VARCHAR(255).

But that's not about PostgreSQL and not exactly a guarantee.


As an aside, if you're using PostgreSQL, you should almost always go straight to :text and pretend that :string doesn't exist. PostgreSQL treats them the same internally except that it has to do a length check on varchar. There's a bit more discussion on this over here in another one of my answers: Changing a column type to longer strings in rails.

like image 75
mu is too short Avatar answered Nov 15 '22 14:11

mu is too short


In rails 4 there is no default limit for string type as you can see in the source:

NATIVE_DATABASE_TYPES = {
        primary_key: "serial primary key",
        bigserial: "bigserial",
        string:      { name: "character varying" },
        text:        { name: "text" },
        #...

if you don't specify a limit ActiveRecord will just set character varying and you could store there a string of any length as stated in the documentation:

If character varying is used without length specifier, the type accepts strings of any size

like image 25
kirlev Avatar answered Nov 15 '22 13:11

kirlev