Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reload the table schema in sequel?

Tags:

ruby

sequel

Given I have the following migration:

Sequel.migration do
  up do
    alter_table :users do
      add_column :is_admin, :default => false
    end

    # Sequel runs a DESCRIBE table statement, when the model is loaded.
    # At this point, it does not know that users have a is_admin flag.
    # So it fails.

    @user = User.find(:email => "[email protected]")
    @user.is_admin = true
    @user.save!
  end
end

Then sequel does not automatically reload the table structure (see comment inline).

I am using this ugly hack to work around it:

# deep magic begins here. If you remove a single line, it will
# break the migration.

User.db.schema("users", :reload => true)
User.instance_variable_set(:@db_schema, nil)
User.columns
User.new.respond_to?(:is_admin=)
sleep 1

Is there a better way?

like image 577
iblue Avatar asked Sep 05 '12 14:09

iblue


People also ask

How do you update a SQL table schema?

To change the schema of a table by using SQL Server Management Studio, in Object Explorer, right-click on the table and then click Design. Press F4 to open the Properties window. In the Schema box, select a new schema. ALTER SCHEMA uses a schema level lock.

How do you edit a table in a schema?

To edit the table schema from the table editor, right-click on the table you wish to edit in the left navigation pane and choose “Edit table...”, as shown below. This will open the schema editor. The schema editor is a powerful tool that you can use to configure your schema.

Which is used to update table structure?

The SQL ALTER TABLE command is used to change the structure of an existing table.


1 Answers

Much simpler than your hack is this hack: (re)set the dataset to the table name:

User.set_dataset :users

Seen in action:

require 'sequel'
DB = Sequel.sqlite
DB.create_table :users do
  primary_key :id
  String :name
end

class User < Sequel::Model; end
User << { name:"Bob" }

DB.alter_table :users do
  add_column :is_admin, :boolean, default:false
end

p User.first       #=> #<User @values={:id=>1, :name=>"Bob", :is_admin=>false}>

p User.setter_methods    #=> ["name="]
User.set_dataset :users  # Make the magic happen
p User.setter_methods    #=> ["name=", "is_admin="]

@user = User.first
@user.is_admin = true
@user.save

p User.first       #=> #<User @values={:id=>1, :name=>"Bob", :is_admin=>true}>

Note that there is no Sequel::Model#save! method; I changed it to save so that it would work.

like image 194
Phrogz Avatar answered Oct 05 '22 13:10

Phrogz