Wednesday, July 2, 2008

Using Vim and MySQL to Create Fixtures (for Rails)

...I've had to build a lot of fixtures using extant data from a MySQL database.  I don't want the whole database in my fixtures... just a subset, based on some examples I use in my specs.

So I run a query to get the subset I want, being sure to grab all the contents from a given table (and ONLY one table).  Something like this:

  FROM a_fancy_table ft
    JOIN some_table st ON ( = st.a_fancy_table_id)
  WHERE IN (1, 2, 3)\G

The \G is essential, here.  I then copy the output of that to the some_table.yml file, created with vim.

  1. <ap multiple times, until everything is left-justified, then
  2. >ap once, so that it's all indented 1 level, then
  3. :%s/  \*\+ \(\d\+\). row \*\+/^Msome_prefix_\1:
  4. finally, rename any of those that are really significant.
...Of course, the ^M is really ^v[ENTER], and the some_prefix is whatever you want to name your objects.

...If that makes sense, you'll find it's a huge time-saver.  Unless you're copying entire tables, in which case you can use Dmitry's script.

No comments: