Páginas

Tuesday, May 29, 2012

Compiling SQLite as a shared library on Ubuntu

I wanted to have the most recent SQLite available for my Python applications.
Ubuntu repositories couldn't help, so, for future reference, here is what I did:

cd /tmp
wget http://www.sqlite.org/sqlite-autoconf-3071201.tar.gz
tar xvzf sqlite-autoconf-3071201.tar.gz
cd sqlite-autoconf-3071201/
# set your own options
CFLAGS="-Os -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_RTREE" ./configure --prefix=/usr
make

# quick-n-dirty way to replace the original lib
sudo mv /usr/lib/x86_64-linux-gnu/libsqlite3.so.0.8.6{,.orig}
sudo mv /usr/bin/sqlite3{,.orig}

chmod -x .libs/libsqlite3.so.0.8.6
sudo cp .libs/libsqlite3.so.0.8.6 /usr/lib/x86_64-linux-gnu/
sudo cp .libs/sqlite3 /usr/bin/

cd
# check that Python sees the new version
python -c 'import sqlite3; print sqlite3.sqlite_version'
# check that SQLite shell works
sqlite3

Sunday, May 27, 2012

How to select random rows from a SQLite table fast

Today I wanted to select some random rows from a large (~3GB, ~900K rows) SQLite database, where the approach found elsewhere on the Web is simply too slow:

SELECT * FROM table ORDER BY random() LIMIT n; 

 Instead of doing that, I came up with a faster alternative:

SELECT * FROM table WHERE random() % k = 0 LIMIT n;

In the examples above, adjust *, table, k and n as suitable for you. n is the (maximum) number of rows returned, and k is an integer constant that determines how probable it is to select a given row.
For instance, k = 2 means (about) 0.5 probability, k = 3 means 0.33, k = 4 means 0.25 and so on.

My alternative above will return random rows, but sorted by the primary key. If you want random rows in random order you can save the retrieved rows in a temporary table and then shuffle them:

CREATE TEMP TABLE temp_rows AS
    SELECT * FROM table WHERE random() % k = 0 LIMIT n;
SELECT * FROM temp_rows ORDER BY random();

That went faster than a compound select.

Thursday, May 10, 2012

Ser uma pessoa melhor a cada dia


Como inspiração para todos os dias dar o melhor de si, segue uma mensagem postada pelo meu ex-COMCIA (viva o Colégio Naval!) Emerson. Grifei algumas partes:

Não consigo achar nada mais gratificante do que chegar ao final de cada dia com a certeza de que fiz o melhor que pude no trabalho, tratei o melhor possível as pessoas com as quais convivo, dei a maior atenção e carinho que pude à minha família.
Se o mundo é cão e nada presta, pelo menos hoje a minha parte eu fiz pra mudar isso, e assim ir pro travesseiro com a consciência tranquila!
O melhor e o pior é que amanhã começa o desafio de novo, do zero!!
Não sei se conseguirei me safar mais uma vez, mas vou tentar, e assim seguir tentando, até o esforço virar hábito.
Boa noite a todos!!!