PostgreSQL Syntax Highlighting in Emacs

So, a little while ago I discovered sql-mode and syntax highlighting, plus a little, for PostgreSQL SQL scripts.

I know, you’re asking, “But, Aaron, how did you not discover this a long time ago?!” Simply put, I usually do everything I need to do in the psql shell. I’ve never really needed to write SQL scripts or edit them.

Then, shadowdaemon was pipping his squeak about having gotten psql-mode working in Emacs. That got me to take a look at what modes are available for PostgreSQL and Emacs. (app-emacs/psql is now masked as it has been abandoned by upstream a really long time ago, and the package required dev-db/postgresql-server which was incorrect.)

So, I just opened an SQL script that came along with rsyslog and Emacs set itself to sql-mode, which is included as a part of the core install. Not quite the proper mode for a PostgreSQL script, but close. There is a product selection, though, so with that one setting I had proper syntax highlighting going and I could connect straight to the database within Emacs. Pretty nifty if I do say so myself, which I do.

Now for some interesting bits. I’m obviously quite involved with PostgreSQL and I’d want my Emacs to default to PostgreSQL syntax highlighting, so I’ve added the following to my ~/.emacs:

(eval-after-load "sql"
  '(progn
    (sql-set-product 'postgres)
    )
  )

This works out pretty nicely as now Emacs defaults to using the proper syntax scheme. I wanted to take this a step further and have psql do the right thing also, but I use the server/client mode with Emacs so I don’t have a ton of windows open at any given time. Also, when emacsclient is invoked by psql, I want it to set the proper mode, so here comes some trickery.

In my ~/.bashrc I added:

PSQL_EDITOR="emacsclient --eval \"(setq-default major-mode 'sql-mode)\"; emacsclient"

When psql is given \e, it’ll open a connection to my Emacs server with the sql-mode loaded, and my ~/.emacs sets the product and all is right with the world.

So, vim, what can you do? Seriously. I’d like to resolve an easy bug (bugs.gentoo.org) before I die.

3 thoughts on “PostgreSQL Syntax Highlighting in Emacs”

Leave a Reply