Question

I try to convert this ActiveRecord schema to sqlalchemy

def db_schema
  ActiveRecord::Schema.define do
unless table_exists? :strains
  create_table :strains do |t|
    t.column :name, :string
    t.column :description, :string
  end
end

# indices
unless index_exists? :strains, :id
  add_index :strains, :id
end
  end
end

Is this SQLalchemy the equivalent to ActiveRecord?

class Strain(db.Model):
    __tablename__ = 'strains'
  name = db.Column(db.String(), index=True, unique=True)
  description = db.Column(db.String())
Was it helpful?

Solution

Close, but seems to be missing id column. I don't know exactly how ActiveRecord behaves regarding nullable/default, so I'm just guessing good defaults for some of this.

class Strain(db.Model):
    __tablename__ = 'strains'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, unique=True, index=True)
    description = Column(String, nullable=False, default='')

Also, MySQL and some other dbs expect a length for String, and treat String different than Text. At least PostgreSQL and SQLite don't care though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top