21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Banco de dados 175

return '%s - %s' % (band, track)

$$ language plpythonu;

O código em Python foi marcado em verde.

Saída da função (através do psql):

music=> select pformat(track, band) from tracks;

pformat

-------------------------

Kashmir - Led Zeppelin

Starless - King Crimson

Yes - Siberian Khatru

Genesis - Supper's Ready

(4 registros)

O ambiente de execução de Python no PostgreSQL provê o módulo plpy

(importado automaticamente) que é uma abstração para o acesso aos recursos

do SGBD.

Exemplo com plpy:

create function inibands()

returns setof text

as $$

bands = plpy.execute('select distinct band from tracks order by 1')

return [''.join(filter(lambda c: c == c.upper(), list(band['band']))) for band

in bands]

$$ language plpythonu;

Saída da função (através do utilitário psql):

music=> select inibands();

inibands

----------

KC

LZ

Y

G

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!