Storing chess positions efficiently in PostgreSQL
Wednesday, May 7th, 2008PostgreSQL has a wonderful feature which is called User-Defined types. It allows anyone to create a new datatype, along with the relevant operators, which are then managed almost natively by Postgres.
I decided to use this feature to manage chessboard positions in a more efficient manner than the usual ASCII storage which looks like “rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR”
I named this new type EPD, for “Extended Position Description”. I know that all the relevant data is not present (I shall typically store information like the active color, the casting availability, and a few other fields), but it didn’t sound like a bad choice for a name.
It allows to do some cool things like:
– Create a table with the epd type
chess=# CREATE TEMPORARY TABLE test_epd(my_epd epd);
CREATE TABLE– Insert a string - it gets automatically converted to a native format and only takes 32 bytes
chess=# INSERT INTO test_epd VALUES (’rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR’);
INSERT 0 1– And converted back into a string
chess=# SELECT * FROM test_epd;
my_epd
———————————————
rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
(1 row)– What’s on A2 ?
chess=# SELECT epd_piece_at(my_epd, ‘a2′) FROM test_epd;
epd_piece_at
————–
n
(1 row)chess=#
The code is available here. The installation process is:
- Compile: make
- Install the .so: make install
- Configure postgresql: cat epd.sql | psql