2

How do I rename a database table in web2py? If there is not a direct way, what is the best workaround to do this? All I found was this thread http://groups.google.com/group/web2py/browse_thread/thread/ef724508324347e2/7966a423c293bdec where the creator of web2py says he does not have an easy way.

User
  • 62,498
  • 72
  • 186
  • 247

1 Answers1

1

To change the database schema while running web2py

db.executesql('ALTER TABLE old_name RENAME TO new_name;')

This will not change your code! Only you can change your code.

So, if you are only doing this once, say because you have an ugly or ambiguous table name and want to refactor your code, then it is likely best not to use web2py to change the table name in the database schema. Here is how I would do it.

  • Stop the application

  • Rename the table in the db schema using the sqlite3 console program, or whatever database management program you use instead. I guess this might be your real problem, because you are accustomed to using web2py as your database management program. Well, I guess you will have to learn how to use the sqlite3 console console program.

  • Change the code in your model

  • Restart the application.

However, if you really insist on using web2py only to manage your database, then something like this should work:

  • Create a new controller, say 'table_rename' Add the line

    db.executesql('ALTER TABLE old_name RENAME TO new_name;')

to the controller

  • Brows to application/table_rename

  • Stop the application

  • Change your model code

  • Remove table_rename

  • Restart application.

ravenspoint
  • 19,093
  • 6
  • 57
  • 103
  • but will the model know about this? Or do I have to change the model separately? models.py file will still have a define_table('old_name'...). Which do I do first? – User Sep 27 '11 at 20:27
  • The SQL will change the database schema. It will not change your code! Only you can change your code. – ravenspoint Sep 27 '11 at 21:19
  • web2py keeps metadata about sql.. does your answer account for that? Of course I know I can go into the database an arbitrarily rename stuff.. but I want to do it in a kosher way so that web2py does not get confused and/or corrupted. – User Sep 27 '11 at 21:24
  • Perhaps you should stop the entire web2py server. – ravenspoint Sep 27 '11 at 21:34