Herberth's blog

Just another software engineer

Commands Conversion Table From MySQL to PostgreSQL

The above title (One who has no dog hunts with a cat - “Quem não tem cão caça com gato”) is a portuguese proverb which exemplifies the developer routine regarding to adapting tools and creating others when there are no other available.

Those who use an IDE (like Visual Studio) and a static-typed language are quite used to use the “refact” tool. It allows you to rename variables and methods, extract methods, rename classes and more, without breaking the code. There are even other extensions, like resharper, which make it even more powerful.

Non-static-language programmers, like me, are often jealous of what C# guys can do without too much effort. Because of the nature of dynamic languages, is very hard to develop a tool to do exactly what Visual Studio can do. We have to find our way to fix our code in multiple places. And we often do it the hard way.

Sometime ago I read a serie of posts called “Unix as an IDE” and it taught me how to use my enviroment to edit code more efficiently.

One of the things the series of posts havent showed me is the power of sed. This simple tool can do almost the same thing as Visual Studio’s refact tool does sometimes.

Let’s suppose we are maintaining an old PHP project that has queries all over the place and which those uses “mysql_db_query” (now deprecated) instead of “mysql_query”. Here’s a life-saving command:

$ find /your/project/folder/ -name "/blog/2013/02/22/one_who_has_no_dog_hunts_with_a_cat_a_sed_story/.html" | xargs sed -i s/mysql_db_query/mysql_query/

We can read it as follows: “find every file ending with *.php in folder /your/project/folder and then substitute mysql_db_query with mysql_query in each one of them”. Pretty simple, huh?

A more complicated example

I’m working on a Django project which uses bootstrapform to better rendering some forms. However, since we’re moving to Crispy Forms, bootstrapform is no longer needed. So let’s remove it!

First, let’s change

{% load bootstrap  %}
{% load crispy_forms_tags  %}
inside templates. We can do it as follows:

$ sed --in-place 's/ {% load bootstrap  %}/{% load crispy_forms_tags  %}/' `find . -name "*.html"`

The command is slightly different from the previous one, but it works like a charm.

The second one is a bit more difficult. We need to change

{{any_form|bootstrap }}


{% crispy any_form %}

There are no other way: you need to have some regex knowledge to pick this up:

$ sed --in-place 's//{% crispy \1  %}/' `find . -name "*.html"`

In this case, grouping saved my day. It is important to remember that sed does not only work on source code files: it works everywhere.

If you are a programmer that uses Unix, keep your sed skills sharp. If you uses windows to work, I can recommend sed for windows or cygwin for a more complete environment.