<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>postgresql &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/postgresql/</link>
	<description>Feed of posts on WordPress.com tagged "postgresql"</description>
	<pubDate>Sat, 28 Nov 2009 13:05:12 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[PostgreSQL: Particionamiento de Tablas]]></title>
<link>http://saforas.wordpress.com/2009/11/27/postgresql-particionamiento-de-tablas/</link>
<pubDate>Fri, 27 Nov 2009 21:00:05 +0000</pubDate>
<dc:creator>sAfOrAs</dc:creator>
<guid>http://saforas.wordpress.com/2009/11/27/postgresql-particionamiento-de-tablas/</guid>
<description><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></description>
<content:encoded><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></content:encoded>
</item>
<item>
<title><![CDATA[PostgreSQL: Window Functions (Funciones Ventana)]]></title>
<link>http://saforas.wordpress.com/2009/11/27/postgresql-window-functions-funciones-ventana/</link>
<pubDate>Fri, 27 Nov 2009 20:59:14 +0000</pubDate>
<dc:creator>sAfOrAs</dc:creator>
<guid>http://saforas.wordpress.com/2009/11/27/postgresql-window-functions-funciones-ventana/</guid>
<description><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></description>
<content:encoded><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></content:encoded>
</item>
<item>
<title><![CDATA[SubQuery]]></title>
<link>http://plusplus.wordpress.com/2009/11/18/sub-query/</link>
<pubDate>Tue, 17 Nov 2009 23:53:34 +0000</pubDate>
<dc:creator>plusplus</dc:creator>
<guid>http://plusplus.wordpress.com/2009/11/18/sub-query/</guid>
<description><![CDATA[You can only do correlate subqueries in SELECT and WHERE clauses. So, a subquery in FROM clause does]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>You can only do correlate subqueries in SELECT and WHERE clauses.</p>
<p>So, a subquery in FROM clause does not have access to the outer select.</p>
<pre>select 	"Damage" , "IdAttackerWeapon" as w,
	(select sum(dd)
	from
		(select "Damage", "IdAttackerWeapon", abs(("Damage" - t."Damage")) as dd
		from fact_eventplayerdamage order by dd asc limit 5)
	t1)
from fact_eventplayerdamage t
group by "Damage", w</pre>
<p>&#8211;</p>
<p>Reza</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Ejemplo para llamar una función pg/psql]]></title>
<link>http://dennysoliver.wordpress.com/2009/11/17/ejemplo-para-llamar-una-funcion-pgpsql-2/</link>
<pubDate>Tue, 17 Nov 2009 21:59:25 +0000</pubDate>
<dc:creator>dennysoliver</dc:creator>
<guid>http://dennysoliver.wordpress.com/2009/11/17/ejemplo-para-llamar-una-funcion-pgpsql-2/</guid>
<description><![CDATA[  Este es un ejemplo de como llamar una funcion pg/sql que retorna un valor, y leer el valor dentro ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="padding-left:30px;"> </p>
<div id="_mcePaste" style="text-align:justify;">Este es un ejemplo de como llamar una funcion pg/sql que retorna un valor, y leer el valor dentro de un jsp. En este caso mi función devuelve un valor de tipo boolean.</div>
<div style="padding-left:30px;"><strong>Esta es la funcion en postgres</strong></div>
<blockquote>
<pre style="text-align:justify;">CREATE OR REPLACE FUNCTION agregar(double precision, character varying, integer, character varying, </pre>
<pre style="text-align:justify;">character varying, character varying)</pre>
<pre style="text-align:justify;">  RETURNS boolean AS
$BODY$
declare
 id ALIAS FOR $3;
 establecidas int :=0;
 agregadas int :=0;
 inicio date :=TO_DATE($5,'YYYY/MM/DD');
 termino date :=TO_DATE($6,'YYYY/MM/DD');
 nulo date:= null;
 mensaje boolean := false;
BEGIN
 select into establecidas from proyectos where id=id;
 agregadas :=  count(id) from etapas where id=id;
 IF agregadas &#60; establecidas THEN
insert into etapas (monto, observaciones, id_proy, nombre,</pre>
<pre style="text-align:justify;"> fch_inicio, fch_termino, prorroga) values ($1,$2,$3,$4,inicio,termino,nulo);</pre>
<pre style="text-align:justify;">mensaje:=true;
 END IF;
 RETURN mensaje;
END;
$BODY$
  LANGUAGE 'plpgsql'</pre>
</blockquote>
<p style="text-align:justify;"><strong>Aquí mandamos llamar la función y capturamos el valor</strong></p>
<blockquote>
<pre style="text-align:justify;">CallableStatement proc = conn.prepareCall("{ ?=call agregar( ?,?,?,?,?,? ) }");
proc.setFloat(2,monto);
proc.setString(3,observaciones);
proc.setInt(4,p);
proc.setString(5,nombre);
proc.setString(6,fch_inicio);
proc.setString(7,fch_termino);
proc.registerOutParameter( 1, Types.BOOLEAN );
proc.execute();
if(proc.getBoolean(1))
response.sendRedirect("lista.jsp?clave="+p);
else
out.println("&#60;h3 id='colora'&#62;&#60;center&#62;No se pude agregar,&#60;/center&#62;&#60;/h3&#62;");
proc.close();</pre>
</blockquote>
<p>En algunas maquinas puede generar un error la jsp en el tipo de dato que se registra, esto se soluciona registrando el tipo de dato Types.BOOLEAN por Types.BIT y ya no habrá problema alguno, y para obtener el valor de retorno podemos seguir haciendo uso del metodo getBoolean(1) ya que <a href="http://java.sun.com/javase/6/docs/api/java/sql/CallableStatement.html#getBoolean(java.lang.String)" target="_blank">la documentacion dice esto:</a> Recupera el valor de un parámetro JDBC bit o booleano como un booleano en el lenguaje de programación Java.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Retrieving an hierarchical tree recursively with PL/PgSQL]]></title>
<link>http://gustavostraube.wordpress.com/2009/11/17/retrieving-an-hierarchical-tree-recursively-with-plpgsql/</link>
<pubDate>Tue, 17 Nov 2009 16:39:32 +0000</pubDate>
<dc:creator>Gustavo Straube</dc:creator>
<guid>http://gustavostraube.wordpress.com/2009/11/17/retrieving-an-hierarchical-tree-recursively-with-plpgsql/</guid>
<description><![CDATA[From PostgreSQL 8.4 you can write WITH queries using the optional RECURSIVE modifier to make a query]]></description>
<content:encoded><![CDATA[From PostgreSQL 8.4 you can write WITH queries using the optional RECURSIVE modifier to make a query]]></content:encoded>
</item>
<item>
<title><![CDATA[Como criar senha para usuário postgres do PostgreSQL (ubuntu)]]></title>
<link>http://pedrolinhares.wordpress.com/2009/11/17/como-criar-senha-para-usuario-postgres-do-postgresql-ubuntu/</link>
<pubDate>Tue, 17 Nov 2009 15:13:48 +0000</pubDate>
<dc:creator>pedrolmota</dc:creator>
<guid>http://pedrolinhares.wordpress.com/2009/11/17/como-criar-senha-para-usuario-postgres-do-postgresql-ubuntu/</guid>
<description><![CDATA[Se você, como eu, instalou o postgresql pelo apt-get logo percebeu que não tinha a senha default par]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Se você, como eu, instalou o postgresql pelo apt-get logo percebeu que não tinha a senha default para o usuário padrão postgres. Bom, até hoje não sei se existe essa senha (se souber me diga..), porém consegui modifica-lá fazendo o seguinte.</p>
<p>Primeiro acesse o arquivo pg_hba.conf em /etc/postgresql/8.3/main/pg_hba.conf<br />
O arquivo estará com umas linha mais ou menos assim:<br />
# Database administrative login by UNIX sockets -<br />
local   all         postgres                          ident (ou ident sameuser)<br />
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD</p>
<p>ident significa que o usuário do banco deverá ser o mesmo do sistema operacional. Entretanto não é isso que queremos e como não sabemos a senha do usuário postgres criado faça:</p>
<p>$ sudo passwd postgres</p>
<p>Forneça a senha para usuário root e em seguida nova senha para o usuário postgres. Feito isso hora de mecher no arquivo pg_hba.conf, faça isso:<br />
# Database administrative login by UNIX sockets -<br />
local   all         postgres                          trust<br />
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD</p>
<p>Isso fará como que o banco permita que qualquer usuário do sistema operacional ou da rede que possa acessar o banco tenha acesso como qualquer usuário do banco e que possa acessar qualque banco de dados.</p>
<p>Reinicie o Postgresql:</p>
<p>$ sudo /etc/init.d/postgresql-8.3 restart</p>
<p>Feito isso, agora faça:</p>
<p>$ psql -U postgres</p>
<p>deverá acessar o banco postgres como  usuário postgres sem necessidade de senha.</p>
<p>agora defina uma senha para o usuário postgres, fazendo:</p>
<p>ALTER USER postgres  ENCRYPTED PASSWORD &#8216;password&#8217;;</p>
<p>Saia do psql e no prompt volte a acessar o pg_hba.conf e faça:<br />
local   all         postgres                          md5<br />
# TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD</p>
<p>Com o method md5 irá requisitar uma senha para o usuário do &#8220;banco de dados&#8221; não do sistema operacional.<br />
Reinicie o postgresql:</p>
<p>$ sudo /etc/init.d/postgresql-8.3 restart</p>
<p>E acesse o banco:</p>
<p>$ psql -U postgres</p>
<p>deverá pedir a senha que foi a criada pelo psql através do comando ALTER USER.</p>
<p>Agora deverá funcionando. Senão, é porque esqueci algo, sendo assim, procure no google o que estiver faltando mas em geral é algo como isso.</p>
<p>Sempre que modificar o arquivo pg_hba.conf reinicie o postgresql.</p>
<p>Para maiores detalhes e outras coisas que não estão aqui, acesse:</p>
<p><a href="http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html">http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html</a></p>
<p><a href="http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-PASSWORD">http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-PASSWORD</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Script slicing by PgMDD]]></title>
<link>http://pgolub.wordpress.com/2009/11/17/script-slicing-by-pgmdd/</link>
<pubDate>Tue, 17 Nov 2009 09:55:50 +0000</pubDate>
<dc:creator>pashagolub</dc:creator>
<guid>http://pgolub.wordpress.com/2009/11/17/script-slicing-by-pgmdd/</guid>
<description><![CDATA[Preface November, 4th. Release Candidate 1 of Database Designer for PostgreSQL 1.2.9 become availabl]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://pgolub.wordpress.com/files/2009/11/slicer.jpg"><img class="alignright size-medium wp-image-959" title="slicer" src="http://pgolub.wordpress.com/files/2009/11/slicer.jpg?w=285" alt="slicer" width="222" height="234" /></a></p>
<h2>Preface</h2>
<p>November, 4th. Release Candidate 1 of <a href="http://microolap.com/products/database/postgresql-designer/">Database Designer for PostgreSQL</a> 1.2.9 <a href="http://microolap.com/products/database/postgresql-designer/news/detail.php?ID=1296">become available</a>. Among three changes comparing to the last beta there is the one which attracts attention — &#8220;Execute Script In Single Transaction (Alt + F9)&#8221; functionality added. World community shocked.</p>
<p>&#8220;What means added? We thought it always was executed in single transaction&#8230;&#8221;  – resounded from all sides.</p>
<p>November, 14th. <a href="http://microolap.com/">MicroOLAP</a> Headquarters. Explanatory mission entrusted to the best agent&#8230; Me. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div id="attachment_970" class="wp-caption alignleft" style="width: 180px"><a href="http://pgolub.wordpress.com/files/2009/11/pgadmin-multiple-set.png"><img class="size-medium wp-image-970 " title="pgadmin-multiple-set" src="http://pgolub.wordpress.com/files/2009/11/pgadmin-multiple-set.png?w=283" alt="pgadmin-multiple-set" width="170" height="180" /></a><p class="wp-caption-text">pgAdmin shows the last result set</p></div>
<p>Right now there is no any opportunity to remember who got the idea about script slicing in SQL Executor. The gist was — each returned result set must be displayed.</p>
<p>Have a look how <a href="http://pgadmin.org/">pgAdmin</a> handles multiple result sets. As you can see only the last is available while others are discarded (we may read about this on the Messages tab).</p>
<p>One more notice. Multiple statements in pgAdmin always executed in the single transaction context. This is not a miracle since <a href="http://www.postgresql.org/docs/8.4/static/libpq-exec.html">PQsendQuery</a> function from client library used.</p>
<p>By the way, the fact that PQsendQuery used give us a hope that someday pgAdmin will handle all result sets.</p>
<div id="attachment_972" class="wp-caption alignright" style="width: 161px"><a href="http://pgolub.wordpress.com/files/2009/11/pgmdd-multiple-set.png"><img class="size-medium wp-image-972 " title="pgmdd-multiple-set" src="http://pgolub.wordpress.com/files/2009/11/pgmdd-multiple-set.png?w=252" alt="pgmdd-multiple-set" width="151" height="180" /></a><p class="wp-caption-text">PgMDD shows all result sets in separate tabs</p></div>
<table style="border-collapse:collapse;margin-top:15px;margin-bottom:15px;" border="0" cellspacing="0" cellpadding="5" bgcolor="LightYellow">
<tbody>
<tr>
<td><img class="alignnone size-full wp-image-164" title="note" src="http://pgolub.wordpress.com/files/2009/01/note.gif" alt="note" width="10" height="10" /></td>
<td>Just for note, I&#8217;m not saying pgAdmin is a dinosaur or something. I like it a lot. This is &#8220;must have&#8221; tool for sure. I&#8217;m using it because of other GUI administration utility absence. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </td>
</tr>
</tbody>
</table>
<p>As you probably guessed PgMDD creates separate tab for each result set from the very first release.</p>
<p>There is one more important issue why script slicing was implemented. Database Designer is some kind of ideal world. You may use any names, any functions, any data types for model creating.</p>
<p>But real life is cruel. Generated script must work in any conditions even if some statements may fail, e.g. old server version, non-existent role, lack of privileges for some operations, object with the same name already exists etc. That&#8217;s why PgMDD&#8217;s SQL Executor should give the developer right of choice — abort execution or proceed anyway.</p>
<h2>How it&#8217;s made</h2>
<p>Let me one phrase before I begin: there is no any SQL parser library (or suite) on the market which suits even the basic needs  (I mean PostgreSQL dialect of course). I guarantee this!</p>
<p>God is my witness, our team tried every 3rd party library we meet. Without success.</p>
<p>In Russian speaking IT folklore there is an adage &#8220;Переписать всё нахрен!&#8221;. Loose translation is &#8220;Rewrite all from scratch!&#8221;</p>
<p>OK, the moment of glory. We made it ourselves using the <a href="http://pgolub.wordpress.com/2009/05/13/metamorphosis-of-gram-y-8-4-beta1/">native PostgreSQL grammar</a>. Yeah, bite me unbelievers!</p>
<p>Let&#8217;s omit technical details. I know nobody cares anyway. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  Our parser is absolutely&#8230; no, I mean <strong>absolutely</strong> compatible with PostgreSQL. But with 8.3.x version. <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  It&#8217;s just a matter of time to update it, but we missed the moment.</p>
<p>So we have two reasons to add &#8220;Execute in Single Transaction&#8221; functionality:</p>
<ul>
<li>Ability to ROLLBACK all changes made by script in case of need</li>
<li>PgMDD parser cannot proceed with some PostgreSQL 8.4.x features</li>
</ul>
<p>That&#8217;s all folks!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[PostgreSQL: Consultas Enumeradas]]></title>
<link>http://saforas.wordpress.com/2009/11/27/postgresql-consultas-enumeradas/</link>
<pubDate>Fri, 27 Nov 2009 20:57:40 +0000</pubDate>
<dc:creator>sAfOrAs</dc:creator>
<guid>http://saforas.wordpress.com/2009/11/27/postgresql-consultas-enumeradas/</guid>
<description><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></description>
<content:encoded><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></content:encoded>
</item>
<item>
<title><![CDATA[PostgreSQL: Configuración del Idioma (locales)]]></title>
<link>http://saforas.wordpress.com/2009/11/27/postgresql-configuracion-del-idioma-locales/</link>
<pubDate>Fri, 27 Nov 2009 20:52:58 +0000</pubDate>
<dc:creator>sAfOrAs</dc:creator>
<guid>http://saforas.wordpress.com/2009/11/27/postgresql-configuracion-del-idioma-locales/</guid>
<description><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></description>
<content:encoded><![CDATA[SUGERENCIA: Si has utilizado la base de datos dbadmision en ejercicios previos es mejor volver a cre]]></content:encoded>
</item>
<item>
<title><![CDATA[install redmine (project management tool) on centos 5.4 with postgres backend]]></title>
<link>http://gkoenig.wordpress.com/2009/11/27/install-redmine-project-management-tool-on-centos-5-4-with-postgres-backend/</link>
<pubDate>Fri, 27 Nov 2009 10:58:53 +0000</pubDate>
<dc:creator>gkoenig</dc:creator>
<guid>http://gkoenig.wordpress.com/2009/11/27/install-redmine-project-management-tool-on-centos-5-4-with-postgres-backend/</guid>
<description><![CDATA[Hello, if you&#8217;re looking for a very nice, flexible, open-source project management tool with g]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Hello,<br />
if you&#8217;re looking for a very nice, flexible, open-source project management tool with great functionality, e.g. sourcecode integration, you have to check-out <strong>REDMINE</strong> (<a href="http://www.redmine.org/">homepage</a>).<br />
Since I&#8217;m running CentOS 5.4 I&#8217;ll provide you with the very easy installation procedure:</p>
<p>howto install redmine on centos5.4<br />
=====================<br />
# prerequisites</p>
<ul>
<li>enable the epel yum repository</li>
<li>installed postgresql database (I&#8217;m using the latest 8.4 provided from pgdg repository)</li>
</ul>
<p># install some packages<br />
<code>yum install ruby ruby-devel ruby-libs ruby-irb ruby-rdoc ruby-postgres rubygems<br />
gem install rails</code><br />
# create user/db<br />
<code>su postgres<br />
createuser -P redmine (no superuser, can create databases)<br />
psql -U redmine postgres<br />
postgres#&#62;create database redmine;<br />
postgres#&#62;\q</code><br />
# download latest stable redmine from http://rubyforge.org/frs/?group_id=1850<br />
<code>cd /opt<br />
wget http://rubyforge.org/frs/download.php/67144/redmine-0.8.7.tar.gz<br />
tar -xvzf redmine-0.8.7.tar.gz</code><br />
# edit ruby database configuration<br />
<code>cd redmine-0.8.7<br />
cp config/database.yml.example config/database.yml<br />
vi config/database.yml</code><br />
# modify the settings to your recently created database<br />
<code>production:<br />
adapter: postgresql<br />
database: redmine<br />
host: localhost<br />
username: redmine<br />
password: &#60;your redmine database user password&#62;<br />
encoding: utf8</code></p>
<p># create a session store (for storing session cookies)<br />
<code>rake config/initializers/session_store.rb</code><br />
# create the database structure for your configured database in the &#8220;production&#8221; section<br />
<code>RAILS_ENV=production rake db:migrate</code><br />
# populate the tables with some initial data<br />
<code>RAILS_ENV=production rake redmine:load_default_data</code><br />
# set some file permissions (assumption: you&#8217;ll run redmine as user redmine)<br />
<code>cd /opt/redmine-0.8.7<br />
sudo chown -R redmine:redmine files log tmp public/plugin_assets<br />
sudo chmod -R 755 files log tmp public/plugin_assets</code><br />
# adjust your mailserver settings<br />
<code>cp config/email.yml.example config/email.yml<br />
vi config/email.yml<br />
...insert your mailserver/credentials and method of sending emails<br />
</code><br />
# start the webserver as the user you &#8220;enabled&#8221; in the previous step<br />
<code>ruby script/server webrick -e production</code><br />
the builtin web-server will start.<br />
Now you can point your browser to http://localhost:3000 and<br />
you&#8217;ll see the welcome page, click &#8220;sign in&#8221; and type credentials &#8220;admin&#8221;/&#8221;admin&#8221;.<br />
now you are logged in.</p>
<p>As this admin user you can start creating users, projects, issues, &#8230;.<br />
Just play around and have fun, it&#8217;s a great tool</p>
<p>any comments highly appreciated&#8230;.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Create a spatial database with PostGIS]]></title>
<link>http://gismemento.wordpress.com/2009/11/25/create-a-spatial-database-with-postgis/</link>
<pubDate>Wed, 25 Nov 2009 09:25:01 +0000</pubDate>
<dc:creator>Helder Nunes</dc:creator>
<guid>http://gismemento.wordpress.com/2009/11/25/create-a-spatial-database-with-postgis/</guid>
<description><![CDATA[Ensure your PostgreSQL database is correctly installed and running. Do do it just check the connecti]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Ensure your PostgreSQL database is correctly installed and running. Do do it just check the connection using PgAdmin III client. If an error arrises, probabily your server isn&#8217;t running. nu Start it using the &#8220;Start server&#8221; entry in the start menu of your operating system or else on Ubuntu this will work (if the server was installed as in <a href="http://gismemento.wordpress.com/2009/11/24/installing-postgesql-with-postgis/">this</a> previous post)</p>
<p><code>sudo /opt/PostgreSQL/8.4/installer/server/startserver.sh</code></p>
<p><strong>1)</strong> Open the Databases tree item and have a look at the available databases. The postgres database is the user database for the default postgres user and is not too interesting to us. The template_postgis database is what we are going to use to create spatial databases. Right-click on the Databases item and select New Database.</p>
<p><img src="http://revenant.ca/www/postgis/workshop/_images/install-27.png" alt="" width="507" height="367" /></p>
<blockquote><p><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;">Note: If you receive an error indicating that the source database (</span><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;">template_postgis</span><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;">) is being accessed by other users, this is likely because you still have it selected. Right-click on the </span><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;">PostgreSQL 8.4</span><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"> item and select </span><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;">Disconnect</span><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;">. You can then double-click the same item to reconnect and try again.</span></p></blockquote>
<p><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"><strong>2)</strong></span><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"> Fill in the <em>New Database</em> form with the info below and click OK.</span></p>
<p><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;"><strong>Name</strong>: your_database_name</span></p>
<p><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;"><strong>Owner</strong>: postgres</span></p>
<p><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;"><strong>Encoding</strong>: UTF8</span></p>
<p><span style="font-family:'Consolas ,Deja Vu Sans Mono ,Bitstream Vera Sans Mono ,monospace';color:#333333;background-color:#f2f2f2;"><strong>Template</strong>: template_postgis</span></p>
<p><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"><strong>3)</strong></span><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"> Select the new database and click on the SQL query button (or go to Tools &#62; Query Tool).</span></p>
<p><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"><strong>4)</strong></span><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"> Enter the following query into the query text field: </span></p>
<p><code>SELECT postgis_full_version();</code></p>
<p><span style="font-family:'helvetica ,microsoft sans serif ,arial ,sans-serif';color:#000000;"><strong>5)</strong> Click the play button in the toolbar (F5 will work also) to execute the query. The query will return a string that confirms that PostGIS is properly enabled in the database.</span></p>
<p><img src="http://revenant.ca/www/postgis/workshop/_images/install-29.png" alt="" width="500" height="415" /></p>
<p><a href="http://revenant.ca/www/postgis/workshop/creatingdb.html" target="_blank">Information source</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Installing PostgeSQL and PostGIS]]></title>
<link>http://gismemento.wordpress.com/2009/11/24/installing-postgesql-with-postgis/</link>
<pubDate>Tue, 24 Nov 2009 20:53:21 +0000</pubDate>
<dc:creator>Helder Nunes</dc:creator>
<guid>http://gismemento.wordpress.com/2009/11/24/installing-postgesql-with-postgis/</guid>
<description><![CDATA[This is a simple method I found to install postgres and postgis in ubuntu/windows. Browse to this ur]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>This is a simple method I found to install postgres and postgis in ubuntu/windows. Browse to this url <a href="http://www.postgresql.org/download/" target="_blank">http://www.postgresql.org/download/</a> and in &#8220;Binary Packages&#8221; you may choose the operating system where you will be using the server. Choosing windows or linux you will download an executable, but the problem in linux you will have to chmod it in order to use it as one. This will do the trick using the terminal: </p>
<pre><span style="font-family:'Courier New,courier';">  chmod 777 filename.bin</span></pre>
<p> and that&#8217;s it. The binary file can now be run: </p>
<pre><span style="font-family:'Courier New,courier';">  sudo ./filename.bin</span></pre>
<p> This will show a GUI installer interface where you will be able to define the root password. The final process will be the selection of addons like database connectors, web components to work with, wikis and the spatial extension we are looking for &#8211; postgis. First select the server already running in your OS platform: </p>
<p><img src="http://www.bostongis.com/images/snippets/app_stackbuilder_postgis.png" width="493" height="336" /></p>
<p>In the next screen be sure to check the PostGIS extension. </p>
<p><img src="http://www.bostongis.com/images/snippets/app_stackbuilder_postgis02.png" width="491" height="333" /></p>
<p>The installer will then download and install the selected extensions. Open PgAdmin III and be sure that a database called <em>template_postgis</em> exists.</p>
<p><img src="http://revenant.ca/www/postgis/workshop/_images/install-26.png" width="491" height="333" /></p>
<p>That was a peace of cake&#8230; the next post will be about creating a georeferenced enabled database.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[COPY command psql-- loading large LiDAR Point Dataset]]></title>
<link>http://smathermather.wordpress.com/2009/11/24/copy-command-psql-loading-large-lidar-point-dataset/</link>
<pubDate>Tue, 24 Nov 2009 19:13:28 +0000</pubDate>
<dc:creator>smathermather</dc:creator>
<guid>http://smathermather.wordpress.com/2009/11/24/copy-command-psql-loading-large-lidar-point-dataset/</guid>
<description><![CDATA[Ok, so the INSERT statements were too numerous for inputing the LiDAR point dataset (about a billion]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Ok, so the INSERT statements were too numerous for inputing the LiDAR point dataset (about a billion points&#8230; .)  They kept crashing the postgres daemon.  So, I used copy from a CSV file:</p>
<pre>COPY base.cuy_lidar_all FROM 'c:/path/cuy_lidar_ground_veg.insert' WITH CSV</pre>
<p>Keep your fingers crossed&#8230; .</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[postgres and bloated table]]></title>
<link>http://gkoenig.wordpress.com/2009/11/24/postgres-and-bloated-table/</link>
<pubDate>Tue, 24 Nov 2009 10:23:37 +0000</pubDate>
<dc:creator>gkoenig</dc:creator>
<guid>http://gkoenig.wordpress.com/2009/11/24/postgres-and-bloated-table/</guid>
<description><![CDATA[From time to time there are news/messages about bloated tables in postgres and a thereby decreased p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>From time to time there are news/messages about bloated tables in postgres and a thereby decreased performance of the database.<br />
The postgres-wiki contains a view (extracted from a script of the bucardo project) to check for bloat in your database <a href="http://wiki.postgresql.org/wiki/Show_database_bloat">here</a><br />
For a quick reference you can check your table/index sizes regularly and check the no. of tuples to assume where bloat comes in.<br />
e.g. check size of your tables and indexes:<br />
<code><br />
SELECT    relname AS table_name,<br />
                 pg_size_pretty(pg_relation_size(oid)) AS table_size,<br />
                 pg_size_pretty(pg_total_relation_size(oid)) AS total_size<br />
       FROM      pg_class<br />
       WHERE     relkind in ('r','i')<br />
       ORDER BY  pg_relation_size(oid) DESC;<br />
</code></p>
<p>check no. of tuples<br />
<code><br />
SELECT   relname, relkind, reltuples, relpages<br />
FROM     pg_class<br />
ORDER BY relpages DESC;<br />
</code></p>
<p>If you&#8217;re facing such a situation you have to check your <strong>(auto)vacuum</strong> settings and if it&#8217;s working correctly.<br />
Starting with Postgres 8.3.x the autovacuum daemon works reliable for most cases and should be enabled. On some workloads a manual vacuum is needed anyhow. In combination with setting the (auto)vacuum parameters you have to consider the <strong>Free Space Map (FSM)</strong> parameter.<br />
Open your postgresql.conf and check it out (every parameter has a very good comment there):<br />
* enable autovacuum and log every run &#62; 1 sec.<br />
<code><br />
autovacuum = on<br />
log_autovacuum_min_duration = 1000<br />
</code></p>
<p>fine tune when autovacuum will check the tables. The number is the fraction of the table size which needs modified data to run an autovacuum.</p>
<p>Apart from the bloated-table/index stuff, for the query planner it is very important to have <strong>up-to-date statistics</strong>. If you need an analyze more often, shrink the number to e.g. <em>autovacuum_analyze_scale_factor = 0.02</em> and the tables will be autoanalyzed more often<br />
<code><br />
autovacuum_vacuum_scale_factor = 0.2<br />
autovacuum_analyze_scale_factor = 0.1<br />
</code><br />
prevent autovacuum from running too often<br />
<code><br />
autovacuum_naptime = 1min #time between two runs<br />
</code></p>
<p>And don&#8217;t forget to check your postgresql.log file for any hints the database system provides.<br />
Regarding bloated tables I detected something like:<br />
<code><br />
WARNING:  relation "public.table_one" contains more than "max_fsm_pages" pages with useful free space<br />
HINT:  Consider using VACUUM FULL on this relation or increasing the configuration parameter "max_fsm_pages"<br />
</code></p>
<p>A &#8220;normal&#8221; vacuum wouldn&#8217;t help in this case because it doesn&#8217;t release the pages to the os, they will only be marked as free in the FSM (Free Space Map).<br />
<strong>If your FSM isn&#8217;t big enough your tables will be bloated even with running autovacuum and perhaps manual vacuum, because the pages with no longer needed data cannot be marked as free and therefore never be overwritten.</strong><br />
One solution would be to run a<br />
<code><br />
vacuum full verbose analyze table_name<br />
</code><br />
This &#8220;defragment&#8221;-command marks unused pages as &#8220;can be overwritten&#8221; and moves pages from the bottom into this marked pages. =&#62; The table size will shrink<br />
! But be aware: vacuum full locks the table <strong>exclusive</strong>. Consider running this command in maintenance windows or during night.</p>
<p>You should also keep in mind to &#8220;defragment&#8221; bloated indexes with<br />
<code><br />
REINDEX INDEX <em>indexname</em> # recreate index explicitly<br />
REINDEX TABLE <em>tablename</em> # recreate all indexes for this table<br />
</code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Instalando e Configurando o PostgreSQL no Ubuntu Linux]]></title>
<link>http://jus2think.wordpress.com/2009/11/24/instalando-o-postgresql-no-ubuntu/</link>
<pubDate>Tue, 24 Nov 2009 02:04:32 +0000</pubDate>
<dc:creator>Wesley</dc:creator>
<guid>http://jus2think.wordpress.com/2009/11/24/instalando-o-postgresql-no-ubuntu/</guid>
<description><![CDATA[PostgreSQL O PostgreSQL é um Sistema Gerenciador de Bancos de Dados Objeto Relacional (SGBD ou SGBDO]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>PostgreSQL</strong></p>
<p><img class="alignleft size-medium wp-image-79" title="logo_postgres" src="http://jus2think.wordpress.com/files/2009/11/logo_postgres.jpg?w=300" alt="Logo do PostgreSQL" width="300" height="237" /> O <a href="http://www.postgresql.org/" target="_blank">PostgreSQL</a> é um Sistema Gerenciador de Bancos de Dados Objeto Relacional (SGBD ou SGBDOR) gratuito e de código-fonte aberto que é considerado por muitos o mais avançado SGBD de código-fonte aberto existente na atualidade. Neste post, veremos como instalar e configurar o servidor PostgreSQL e também como instalar e configurar as ferramentas de administração de bancos de dados <strong>phpPgAdmin</strong> e <strong>pgAdmin</strong> (pdAdmin3) que podem ser utilizados para acessar um servidor rodando na sua máquina local ou em qualquer outra máquina na sua rede (ou na internet). Em nosso exemplo usaremos um sistema <a href="http://www.ubuntu.com/" target="_blank">Ubuntu</a> Linux (ou, para ser mais específico, um <a href="http://www.kubuntu.com/">Kubuntu</a> 9.10), mas os mesmos princípios podem ser utilizadas para a configuração de uma instalação do PostgreSQL em outras distribuições Linux e até mesmo em outros sistemas operacionais.</p>
<p><strong>Instalação e Configuração do PostgreSQL</strong></p>
<p>A maneira mais fácil de se instalar o PostgreSQL no Ubuntu, ou qualquer outra distribuição baseada no Debian, é através dos repositórios de pacotes. Para isso, você pode usar o seu gerenciador de pacotes gráfico (tal como o <a href="http://en.wikipedia.org/wiki/Adept_Manager" target="_blank">Adept</a> ou o <a href="http://en.wikipedia.org/wiki/Synaptic_%28software%29" target="_blank">Synaptic</a>) ou usar o apt-get na linha de comando:<br />
<span style="color:#800000;">usuario@notebook:~$ sudo apt-get install postgresql</span></p>
<p>Serão baixados da internet os pacotes necessários e suas dependências e, em pouco tempo, você já terá a última versão do PostgreSQL (atualmente, versão 8.4) instalada em sua máquina. A primeira coisa a fazer após a instalação é configurar a senha do usuário &#8220;padrão&#8221; do sistema, o usuário &#8220;<strong>postgres</strong>&#8221; que é criado com a instalação do PostgreSQL. Para isso, basta usar o cliente de linha de comando &#8220;psql&#8221; que foi instalado junto com servidor:<br />
<span style="color:#800000;">usuario@notebook:~$ sudo su postgres -c psql postgres<br />
psql (8.4.1)<br />
Digite &#8220;help&#8221; para ajuda.<br />
postgres=# ALTER USER postgres WITH PASSWORD &#8216;123&#8242;;<br />
ALTER ROLE<br />
postgres=# \q</span></p>
<p>Observe que entre os apóstrofos, no lugar de &#8220;123&#8243;, você deve utilizar a senha que você deseja configurar. Para sair do console do psql pressione simultâneamente Ctrl+D, será ecoado &#8220;\q&#8221; na tela e você retornará ao prompt do sistema.</p>
<p><strong>Se seu objetivo é apenas usar o usuário padrão do sistema para testar localmente aplicativos que se conectem ao PostgreSQL vocẽ pode parar a leitura desta sessão aqui </strong>e pular para a sessão de configuração dos clientes phpPgAdmin e pgAdmin.<br />
Mas, se você está configurando um servidor para uma rede local, talvez seja útil fazer também as configurações que seguem.<br />
Uma outra configuração interessante pode ser liberar o acesso ao SGBD para os usuários comuns da máquina, para isso, localize e edite como super-usuário o arquivo &#8220;pg_hba.conf&#8221; (no Ubuntu, localizado na pasta &#8220;/etc/postgresql/8.4/main&#8221; , mas isto pode variar conforme o sistema operacional ou versão do SGBD instalada na sua máquina):<br />
<span style="color:#800000;">usuario@notebook:~$ sudo kate /etc/postgresql/8.4/main/pg_hba.conf</span><br />
No lugar do editor &#8220;kate&#8221; você pode utilizar qualquer outro de sua preferência como o &#8220;gedit&#8221; ou o &#8220;nano&#8221;.</p>
<p>Com o arquivo aberto, localize as linhas:<br />
<span style="color:#800000;"># Database administrative login by UNIX sockets<br />
local all postgres ident sameuser</span><br />
e substitua a segunda, ficando assim:<br />
<span style="color:#800000;"># Database administrative login by UNIX sockets<br />
local all all trust</span><br />
Isso irá liberar a administração local das bases de dados para os usuários comuns da sua máquina.</p>
<p>Se você deseja também liberar o acesso para conexões via rede basta substituir as seguintes linhas (no mesmo arquivo):<br />
<span style="color:#800000;"># IPv4 local connections:<br />
host all all 127.0.0.1/32 md5</span><br />
por:<br />
<span style="color:#800000;"># IPv4 local connections:<br />
host all all 0.0.0.0/0 trust</span><br />
Note que estas foram configurações bastante genéricas que você talvez precise revisar para aumentar o grau de segurança ou otimização do seu servidor.</p>
<p>Para que estas configurações relativas à rede tenham efeito, você precisa também alterar o arquivo &#8220;postgresql.conf&#8221;, presente na mesma pasta, para configurar seu servidor para aceitar conexões vindas da rede local. Abra este arquivo, novamente usando o &#8220;kate&#8221; ou o seu editor de texto preferido:<br />
<span style="color:#800000;">usuario@notebook:~$ sudo kate /etc/postgresql/8.4/main/postgresql.conf</span><br />
Localize e substitua a linha:<br />
<span style="color:#800000;"># listen_addresses = &#8216;localhost&#8217;</span><br />
por:<br />
<span style="color:#800000;">listen_addresses = &#8216;*&#8217;</span><br />
Após alteradas estas configurações é preciso reiniciar o servidor PostgreSQL para que as novas configurações tenham efeito:<br />
<span style="color:#800000;">usuario@notebook:~$ sudo /etc/init.d/postgresql-8.4 restart<br />
* Restarting PostgreSQL 8.4 database server</span><br />
Note que a versão do seu servidor instalado pode ser diferente, necessitando que você altere o &#8220;8.4&#8243; no final do comando.</p>
<p><strong>Instalação e Configuração do phpPgAdmin</strong></p>
<div id="attachment_81" class="wp-caption alignleft" style="width: 310px"><a href="http://img7.imageshack.us/img7/8833/phppgadmin.jpg" target="_blank"><img class="size-medium wp-image-81" title="Tela inicial do phpPgAdmin." src="http://jus2think.wordpress.com/files/2009/11/phppgadmin.jpg?w=300" alt="Tela inicial do phpPgAdmin." width="300" height="187" /></a><p class="wp-caption-text">Tela inicial do phpPgAdmin.</p></div>
<p>O <a href="http://phppgadmin.sourceforge.net/" target="_blank">phpPgAdmin</a> é uma ferramenta de administração de banco de dados para a web, por ser escrito em PHP, requer um servidor de páginas web instalado localmente. Ele é bastante popular em servidores de hospedagem, permitindo aos usuários acessar e editar suas bases de dados através do navegador, sem a necessidade de instalar um software localmente. Se você não deseja ter um servidor web completo instalado na sua máquina você pode pular esta etapa e ler sobre a instalação do cliente pgAdmin à seguir. Se você é um desenvolvedor de páginas web é provável que você já tenha o Apache instalado em sua máquina para testes.<br />
Para instalar o phpPgAdmin basta utilizar novamente o apt-get (ou o seu cliente gráfico de instalação de pacotes):<br />
<span style="color:#800000;">usuario@notebook:~$ sudo apt-get install phppgadmin</span><br />
Ele irá instalar o phpPgAdmin e as dependências necessárias (incluindo o servidor Apache e o suporte a PHP).<br />
Feito isso, você deve iniciar o servidor Apache:<br />
<span style="color:#800000;">usuario@notebook:~$ sudo /etc/init.d/apache2 start<br />
* Starting web server apache2<br />
apache2: Could not reliably determine the server&#8217;s fully qualified domain name, using 127.0.1.1 for ServerName</span></p>
<div id="attachment_82" class="wp-caption alignleft" style="width: 310px"><a href="http://img20.imageshack.us/img20/4316/phppgadminerro.jpg" target="_blank"><img class="size-medium wp-image-82" title="Erro no phpPgAdmin Login desabilitado." src="http://jus2think.wordpress.com/files/2009/11/phppgadminerro.jpg?w=300" alt="Erro no phpPgAdmin: Login desabilitado." width="300" height="187" /></a><p class="wp-caption-text">Erro no phpPgAdmin: Login desabilitado.</p></div>
<p>Após, basta abrir o seu navegador e acessar o seu servidor local em <strong>http://localhost/phppgadmin</strong><br />
É possível que você receba a mensagem &#8220;Login disallowed for security reasons.&#8221; (&#8220;Login desabilitado por razões de segurança.&#8221;) ao tentar realizar login com o usuário &#8220;postgres&#8221;. Esta mensagem é exibida por uma configuração padrão do phpPgAdmin que desabilita o login de usuários administrativos. Para alterar esta configuração basta editar o arquivo &#8220;config.inc.php<strong>&#8221; </strong>localizado no diretório de configurações do phpPgAdmin na sua máquina (no Ubuntu, o arquivo está em &#8220;/etc/phppgadmin/config.inc.php&#8221;):<br />
<span style="color:#800000;">usuario@notebook:~$ sudo kate /etc/phppgadmin/config.inc.php</span><br />
Com o arquivo aberto, localize a linha:<br />
<span style="color:#800000;">$conf['extra_login_security'] = true;</span><br />
e altere para:<br />
<span style="color:#800000;">$conf['extra_login_security'] = false;</span><br />
Neste arquivo também estão disponíveis outras opções de configuração, como alterar a porta padrão na qual o PostgreSQL irá receber conexões (por padrão, a porta configurada é a <strong>5432</strong>).<br />
Alterações feitas, basta recarregar (F5) a página web aberta no seu navegador e fazer login com o seu usuário (ou com o usuário &#8220;postgres&#8221;).</p>
<p><strong>Instalação do pgAdmin</strong></p>
<div id="attachment_83" class="wp-caption alignleft" style="width: 310px"><a href="http://img692.imageshack.us/img692/5572/pgadmin.jpg" target="_blank"><img class="size-medium wp-image-83" title="Tela inicial do pgAdmin3." src="http://jus2think.wordpress.com/files/2009/11/pgadmin.jpg?w=300" alt="Tela inicial do pgAdmin3." width="300" height="187" /></a><p class="wp-caption-text">Tela inicial do pgAdmin3.</p></div>
<p>O <a href="http://www.pgadmin.org/" target="_blank">pgAdmin</a> é outra opção de cliente para administrar a sua base de dados, diferente do phpPgAdmin ele é um software desktop que não necessita que um servidor web, como o Apache, esteja instalado na sua máquina. Para instalá-lo no Ubuntu usando o apt-get, digitamos:<br />
<span style="color:#800000;">usuario@notebook:~$ sudo apt-get install pgadmin3</span><br />
Após a instalação, basta localizar o atalho do pgAdmin no menu do seu sistema ou usar o comando &#8220;<strong>pgadmin3</strong>&#8221; no terminal de comandos para abrir a interface gráfica do mesmo. Nenhuma configuração extra é necessária, basta clicar no ícone com a imagem de um &#8220;plug&#8221; na barra de ferramentas do programa para configurar a sua nova conexão.</p>
<p><strong>PostgreSQL x MySQL</strong></p>
<p>Aqui abrimos parênteses para tratar de uma dúvida comum à muitos usuários iniciantes: as diferenças entre o <a href="http://www.mysql.com/" target="_blank">MySQL</a> e o PostgreSQL. Ambos são SGBDs de código fonte-aberto e disponíveis gratuitamente para diversas plataformas tais como Linux, Solaris, Windows ou Mac. Podemos dizer, superficialmente, que o MySQL é um SGBD mais &#8220;rápido&#8221; e com menos recursos avançados (se comparado ao PostgreSQL) usado tipicamente em sistemas Web, enquanto o PostgreSQL é um SGBD mais confiável e robusto, que conta com inúmeros recursos avançados inexistentes no MySQL. Esta comparação é bastante simplista e menos verdadeira a cada nova versão lançada de qualquer um dos dois SGBDs, mas ainda é válida. Uma leve conclusão a respeito do foco de cada SGBD pode ser retirada do slogan presente na página web principal de cada projeto: &#8220;PostgreSQL: The world&#8217;s most advanced open source database&#8221; (&#8220;PostgreSQL: O banco de dados de código-fonte aberto mais avançado do mundo&#8221;) e &#8220;MySQL: The world&#8217;s most popular open source database&#8221; (&#8220;MySQL: O banco de dados de código-fonte aberto mais popular do mundo&#8221;).</p>
<p><strong>Finalizando</strong></p>
<p>O objetivo principal aqui foi demonstrar de maneira prática como instalar o PostgreSQL e configurá-lo para funcionar com o seu Ubuntu Linux e para isso não entramos em detalhes quanto ao seu funcionamento ou ao seu uso.<br />
Dúvidas, críticas, sugestões e correções são sempre bem-vindas nos comentários, um abraço!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Novos serviços cloud disponíveis na BSRSoft]]></title>
<link>http://bsrsoft.wordpress.com/2009/11/23/novos-servicos-cloud-disponiveis-na-bsrsoft/</link>
<pubDate>Tue, 24 Nov 2009 00:03:41 +0000</pubDate>
<dc:creator>BSRSoft IDC</dc:creator>
<guid>http://bsrsoft.wordpress.com/2009/11/23/novos-servicos-cloud-disponiveis-na-bsrsoft/</guid>
<description><![CDATA[Acabamos de disponibilizar diversos novos serviços em nosso segmento de cloud computing (computação ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;">Acabamos de disponibilizar diversos novos serviços em nosso segmento de cloud computing (computação em nuvem) em nosso portal.</p>
<p style="text-align:justify;">Todos eles estão relacionados a bancos de dados.</p>
<p style="text-align:justify;">Já contávamos com o MySQL Cloud e agora oferecemos serviços Postgres Cloud e Oracle DB Cloud (versão 10g).</p>
<p style="text-align:justify;">Com essas opções, cobruimos praticamente todo o espectro de aplicações que precisam de bancos de dados para funções desde controle de um simples site até aplicações empresariais com grande quantidade de transações e necessidade de alta escalabilidade, alta estabilidade e velocidade, além de granualaridade em configurações.</p>
<p style="text-align:justify;">Todos estes serviços rodam em nossos cluster especializados em bancos de dados, especialmente otimizados para tarefas que envolvem grande quantidade de IO de disco (usamos RAID 5 SCSI), grande quantidade de memória em cada nó e enorme poder de processamento.</p>
<p style="text-align:justify;">Somos capazes hoje, de atender a grandes exigências do mercado corporativo, a custos baixos, aproveitando todo o ganho de escala que a computação em nuvem proporciona.</p>
<p style="text-align:justify;">Alta velocidade na entrega de serviços contratados neste cluster , agilidade na escalabilidade e baixa latência de conexão são outros diferenciais que somos capazes de oferecer dentro de nossa infraestrutura.</p>
<p style="text-align:justify;">Nosso produtos de DB na nuvem agora são:</p>
<ul style="text-align:justify;">
<li>MySQL 5 Cloud</li>
<li>PostgreSQL Cloud</li>
<li>Oracle 10g Cloud
<p>Mais dados sobre estes serviços e informações para contratação instantânea em:</li>
</ul>
<p style="text-align:justify;"><a href="http://shop.bsrsoft.com.br/category.php?id_category=15" target="_blank">http://shop.bsrsoft.com.br/category.php?id_category=15</a></p>
<p>&#160;</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Limitations to Trigger Based Unique Constraint]]></title>
<link>http://smathermather.wordpress.com/2009/11/23/limitations-to-trigger-based-unique-constraint/</link>
<pubDate>Mon, 23 Nov 2009 18:16:01 +0000</pubDate>
<dc:creator>smathermather</dc:creator>
<guid>http://smathermather.wordpress.com/2009/11/23/limitations-to-trigger-based-unique-constraint/</guid>
<description><![CDATA[A unique constraint implemented as a trigger checking hashed geometry seems like a good idea, that i]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>A unique constraint implemented as a trigger checking hashed geometry seems like a good idea, that is until I applied it to a multi-10GB dataset.  Not surprisingly, it starts off fast on inserts, and slows down a lot as time goes on.  So, I thought I&#8217;d approach duplicates another way, by deleting them once they exist.  So for my table:</p>
<pre>base.cuy_contours_2
</pre>
<p>I have hashed my geometry, and added an index:</p>
<pre>UPDATE base.cuy_contours_2 SET hash = MD5(ST_AsBinary(the_geom));
CREATE INDEX cuy_contours_2_hash_idx ON base.cuy_contours_2(hash);</pre>
<p>I will follow by deleting the duplicate geometries by checking the hashed geometry:</p>
<pre>DELETE
 FROM base.cuy_contours_2
 WHERE gid NOT IN
 (SELECT        MAX(dup.gid)
 FROM        base.cuy_contours_2 as dup
 GROUP BY    dup.hash
 );
</pre>
<p>But, after a very long time, I get an error:</p>
<pre>ERROR:  could not read block 356366 of relation 1663/17185/12118368: Permission
denied
</pre>
<p>So, it&#8217;s a  down week, and most of my maps are cached, so we&#8217;ll take the postgres service down, and run it in single user mode:</p>
<pre>postgres --single -D c:\postgre_data</pre>
<p>And rerun the command on one line, per single user mode, with no semicolon:</p>
<pre>
<pre>DELETE FROM base.cuy_contours_2 WHERE gid NOT IN (SELECT MAX(dup.gid) FROM base.cuy_contours_2 as dup GROUP BY dup.hash );
</pre>
</pre>
<p>and hope for the best&#8230; .</p>
<p>Oh and thanks to :</p>
<p><a href="http://www.postgresonline.com/journal/index.php?/archives/22-Deleting-Duplicate-Records-in-a-Table.html">http://www.postgresonline.com/journal/index.php?/archives/22-Deleting-Duplicate-Records-in-a-Table.html</a></p>
<p>For help with this one.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[JPA show SQL query]]></title>
<link>http://bugsmacgyvered.wordpress.com/2009/11/23/jpa-show-sql-query/</link>
<pubDate>Mon, 23 Nov 2009 13:26:44 +0000</pubDate>
<dc:creator>opiquetus</dc:creator>
<guid>http://bugsmacgyvered.wordpress.com/2009/11/23/jpa-show-sql-query/</guid>
<description><![CDATA[If you need to show SQL in JBoss debug screen (console) from your JPA / EJB project: &lt;properties]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>If you need to show SQL in JBoss debug screen (console) from your JPA / EJB project:</p>
<blockquote><p>&#60;properties&#62;<br />
&#60;property name= &#8220;hibernate.dialect&#8221;value=&#8221;org.hibernate.dialect.PostgreSQLDialect&#8221; /&#62;<br />
&#60;property name= &#8220;hibernate.show_sql&#8221; value=&#8221;true&#8221; /&#62;<br />
&#60;/properties&#62;</p></blockquote>
<p>in persistence.xml should do the trick.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Servidor de Baixo Custo]]></title>
<link>http://winlix.wordpress.com/2009/11/22/servidor-de-baixo-custo/</link>
<pubDate>Sun, 22 Nov 2009 19:10:57 +0000</pubDate>
<dc:creator>André Steigleder</dc:creator>
<guid>http://winlix.wordpress.com/2009/11/22/servidor-de-baixo-custo/</guid>
<description><![CDATA[cpanel, CPANEL, Cpanel, fantastico, Fantástico, fantástico, script. Php,PHP,RVSitesBuilder,  RVSites]]></description>
<content:encoded><![CDATA[cpanel, CPANEL, Cpanel, fantastico, Fantástico, fantástico, script. Php,PHP,RVSitesBuilder,  RVSites]]></content:encoded>
</item>
<item>
<title><![CDATA[PL/pgSQL – SQL Procedural Language]]></title>
<link>http://wirabumisoftware.wordpress.com/2009/11/22/plpgsql-%e2%80%93-sql-procedural-language/</link>
<pubDate>Sun, 22 Nov 2009 12:30:48 +0000</pubDate>
<dc:creator>wirabumisoftware</dc:creator>
<guid>http://wirabumisoftware.wordpress.com/2009/11/22/plpgsql-%e2%80%93-sql-procedural-language/</guid>
<description><![CDATA[Tulisan ini menguraikan apa dan bagaimana cara membuat function menggunakan PL/pgSQL. Didalamnya ter]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Tulisan ini menguraikan apa dan bagaimana cara membuat function menggunakan PL/pgSQL. Didalamnya terdapat panduan tahap demi tahap dalam membuat dan menggunakan function menggunakan PL/pgSQL. Setelah membaca tulisan ini, anda diharapkan dapat membuat dan menggunakan fungsi menggunakan PL/pgSQL.<br />
<!--more--><strong>Overview</strong><br />
PL/pgSQL adalah procedural language yang loadable (dapat langsung digunakan tanpa restart server) pada sistem database PostgreSQL. PL/pgSQL didesain dengan tujuan supaya kita dapat membuat sebuah procedural language yang:</p>
<ul>
<li> dapat dipakai untuk membuat function atau trigger</li>
<li> dapat menambahkan sruktur kontrol pada bahasa SQL</li>
<li> dapat melakukan komputasi kompleks</li>
<li> semua type, function, dan operator yang didefinisikan user (buatan anda sendiri atau orang lain) dapat diturunkan (inherit)</li>
<li> dapat dipercaya oleh server</li>
<li> mudah digunakan</li>
</ul>
<p>Function yang telah anda buat menggunakan PL/pgSQL dapat digunakan sebagaimana function bawaan yang sudah ada. Misalnya, anda dapat membuat fungsi komputasi kondisional yang kompleks, kemudian menggunakannya untuk membuat operator atau menggunakannya untuk membuat index.<br />
<strong></strong></p>
<p><strong>Keuntungan menggunakan PL/pgSQL</strong><br />
SQL merupakan bahasa yang digunakan PostgreSQL, dan begitu pula sebagian besar sistem database relasional (RDBMS: Relational Dtabase Management System) juga menggunakanSQL sebagai bahasa query. Bahasa ini begitu portable (dapat dipakai dimana saja, dan tentu ada sedikit perbedaan antar RDBMS) dan mudah dipelajari.<br />
Namun, setiap pernyataan SQL harus dijalankan secara terpisah oleh server database. Artinya, setiap aplikasi client anda harus mengirimkan setiap perintah SQL pada server satu per satu. Seletah mengirim 1 perintah SQL, client menunggu hasil prosesnya, kemudian menerima hasilnya dan memroses hasil tersebut. Client kemudian melakukan komputasi selanjutnya, dan kemudian mengirim pernyataan SQL berikutnya pada server. Begitu seterusnya. Hal ini tentu menimbulkan beban komunikasi antara server dan client, yang tentu akan menimbulkan beban jaringan, utamanya jika client dan server database anda terpisah.<br />
Dengan menggunakan PL/pgSQL anda dapat mengelompokkan sebuah blok komputasi atau serangkaian query langsung didalam server, yang tentu saja anda memanfaatkan keunggulan procedural language dan kemudahan penggunaan SQL, sekaligus menghemat ongkos komunikasi dan beban jaringan.<br />
beban komunikasi dari server ke client dan sebaliknya dihilangkan<br />
client tidak perlu menerima hasil/data pada saat proses berlangsung, cukup menerima hasil akhir dari proses tersebut, dan siap digunakan untuk proses komputasi berikutnya<br />
dapat mencegah pengiriman query dari client ke server berulang-ulang, karena function dijalankan di sisi server<br />
Hal ini tentu saja meningkatkan performa aplikasi anda secara signifikan. Dalam membuat function menggunakan PL/pgSQL, anda dapat menggunakan tipe data, operator, dan function pada SQL.<br />
<strong></strong></p>
<p><strong>Tipe data parameter dan hasil yang didukung<br />
</strong>Function yang dibuat dari PL/pgSQL dapat menerima parameter dalam bentuk skalar apa saja (integrer, char, float, dsb) maupun array yang didukung server, dan dapat pula mengembalikan nilai/hasil dengan tipe data tersebut. Function ini juga dapat menerima parameter dan mengembalikan nilai dengan tipe data komposit (tipe row). Function ini juga dapat mengembalikan nilai berupa record yang kolomnya sesuai dengan query yang dijalankan. Function yang dibuat dari PL/pgSQL juga dapat menerima parameter dan mengembalikan nilai bertipe polymorphic (anyelement, anyarray, dsb).<br />
Function dari PL/pgSQL juga dapat dideklarasikan untuk mengembalikan nilai berupa sebuah set atau tabel. Dengan demikian fungsi ini dapat memberikan hasil dengan menjalankan perintah RETURN NEXT untuk setiap elemen dalam 1 record hasil query, atau menggunakan RETURN QUERY untuk mendapatkan semua hasil query.<br />
Function ini juga dapat dideklarasikan untuk menghasilkan nilai void jika anda menghendaki function ini tidak mengembalikan apa-apa.<br />
Function ini juga memiliki kemampuan untuk menerima parameter dengan tipe data berupa output, sehingga anda tidak perlu memberi perintah secara eksplisit untuk mengembalikan sebuah nilai dari suatu function. Ini seringkali berguna jika anda ingin mengembalikan beberapa nilai sekaligus.<br />
Function Anda yang Pertama<br />
Pada bagian ini anda akan saya ajak untuk membuat function, tentu saja function anda yang pertama. Pertama anda harus memiliki software-software yang dibutuhkan. Jika anda meggunakan windows, ada cukup perlu master installer PostgreSQL yang didalamnya sudah memasukkan server PostgreSQL dan aplikasi (client) manajemen database PgAdmin. Jika anda menggunakan linux, gunakan server PostgreSQL dan PgAdmin sesuai dengan distribusi/distro yang anda gunakan. Saya menggunakan PostgreSQL 8.3 dan PgAdmin 1.8.<br />
Buatlah sebuah database untuk mempraktekkan contoh-contoh yang akan saya tampilkan. Buat database baru dengan nama contohplsql. Kemudian jalankan script SQL yang dapat di-download disini, pada database tersebut. Jika sukses, database contohplsql akan memiliki 3 tabel (nama, alamat, negara) dan 2 function (uuid_generate_v4, get_uuid). Kedua function ini hanya digunakan untuk meng-generate primary key pada tiap-tiap record menggunakan algoritma UUID. Klik disini untuk informasi lebih lanjut tentang UUID.<br />
Melalui PgAdmi, masuklah pada database contohplsql, kemudian buka window baru untuk menuliskan script SQL.<br />
[gambar 1]<br />
[gambar 2]<br />
Kemudian tuliskan kode berikut:<br />
<em>CREATE FUNCTION somefunc() RETURNS integer AS $$<br />
&#60;&#60; outerblock &#62;&#62;<br />
DECLARE<br />
quantity integer := 30;<br />
BEGIN<br />
RAISE NOTICE &#8216;Quantity here is %&#8217;, quantity;  &#8212; mencetak 30<br />
quantity := 50;</em></p>
<p><em>/* Create a subblock */</em></p>
<p><em>DECLARE<br />
quantity integer := 80;<br />
BEGIN<br />
RAISE NOTICE &#8216;Quantity here is %&#8217;, quantity;  &#8212; mencetak 80<br />
RAISE NOTICE &#8216;Outer quantity here is %&#8217;, outerblock.quantity;  &#8212; mencetak 50<br />
END;</em></p>
<p><em>RAISE NOTICE &#8216;Quantity here is %&#8217;, quantity;  &#8212; mencetak 50</em></p>
<p><em>RETURN quantity;<br />
END outerblock;<br />
$$ LANGUAGE plpgsql;<br />
</em></p>
<p>Jalankan kode tersebut, anda baru saja membuat function anda yang pertama, dengan nama somefunc. Kemudian panggillah function yang baru saja anda buat dengan menjalankan perintah berikut:<br />
<em>SELECT * FROM somefunc()<br />
</em>Maka anda akan mendapatkan hasil berupa return value bertipe integer bernilai 50. Selamat! Anda baru saja berhasil membuat function.<br />
Struktur PL/pgSQL<br />
PL/pgSQL merupakan bahasa yang dibangun dari blok-blok. Syntax lengkap untuk mendefinisikan sebuah function harus membentuk sebuah blok. Sebuah blok didefinisikan sebagai berikut:<br />
<em>[&#60;&#62;]<br />
[DECLARE<br />
declaration]<br />
BEGIN<br />
statement<br />
END [label];<br />
</em>Pada function pertama yang sudah anda buat tedapat blok yang bernama outerblock. Karena dia didefinisikan dibagian atas, blok ini melingkupi seluruh function. Didalam blok outerblock terdapat blok yang tidak diberi nama (jadi block sebenarnya ditandai dari adanya BEGIN dan END). Setiap deklarasi dan setiap statement dalam sebuah blok harus diakhiri dengan titik koma (;). Sebuah blok yang berada dalam blok lain, tanda titik koma harus ada setelah END. Khusus untuk blok yang menandakan badan function (mencakup keseluruhan isi function) tidak perlu titik koma.<br />
Label hanya diperlukan untuk menandai sebuah blok jika anda menggunakan statement EXIT, atau untuk menandai nama variable yang sifatnya lokal di dalam blok tersebut. Label yang diberikan harus cocok antara yang ada di bagian BEGIN dan END. Pada function contohplsql, block outerblock diakhiri dengan END outerblock;<br />
Semua kata kunci (key word) dibedakan huruf besar/kecil. Identifier secara implisit dikonvesi menjadi huruf kecil, kecuali yang telah diberi petik ganda, sama seperti SQL pada umumnya.<br />
Ada 2 cara untuk menuliskan komentar pada PL/pgSQL. Pertama menggunakan awalan double dash (&#8211;), kedua menggunakan awalan /* dan akhiran */.<br />
Setiap statement dalam sesi statement pada sebuah blok dapat ditempatkan pada sebuah sub-blok. Pembuatan sub-blok bisa didasarkan pada logika pemrograman maupun untuk tujuan melokalisir variable. Namun, anda masih bisa mengakses varible diluar blok dengan jalan menggunakan nama label blok tersebut. Perhatikan function pertama yang sudah anda buat. Blok bagian luar bernama outerblock, sedangkan didalam blok ini terdapat sub-blok yang tidak diberi nama. Pada contoh ini, sub-blok digunakna untuk melokalisir varible. Didalam sub-blok ini terdapat variable quantity, dimana namanya sama dengan variable pada blok induknya. Namun karena posisinya berbeda blok, kedua variable ini berbeda. Untuk mengakses variable quantity pada sub-blok cukup menggunakan quantity saja, sementara untuk quantity yang berada pada blok induk harus menggunakan outerblock.quantity.<br />
Catatan: Pada function pertama yang sudah anda buat sebenarnya tedapat blok diluar semua blok yang telah didefinisikan. Blok ini dibuat oleh server secara implisit dan mencakup semua bagian dari blok-blok yang telah anda buat. Blok ini memiliki nama yang sama dengan nama function. Jadi, sebenarnya pada blok inilah anda mendeklarasikan parameter function, begitu juga varible spesial lainnya seperti FOUND. Dengan demikian anda dapat mengakses nama parameter dan variable khusus lainnya menggunakan nama function ini.<br />
Penting untuk memahami dan tidak bingung akan penggunaan BEGIN/END sebagai blok dan sebagai transaction. Pada PL/pgSQL pernyataan BEGIN/END hanya digunakan untuk pengelompokan saja, dia tidak bisa start/commit sebuah transaction. Namun, sebuah blok yang didalamnya terdapat klausa EXCEPTION akan membentuk susunan blok tertentu dimana sebuah rangkaian statement didalamnya dapat di-roll back tanpa mempengaruhi perintah-perintah di blok lain.</p>
<p><strong>Declaration<br />
</strong>Semua variable yang digunakan dalam blok harus dideklarasikan dalam bagian deklarasi pada blok tersebut. (Kecuali varible yang digunakan dalam iterasi LOOP, yang akan dideklarasikan secara otomatis sebagai integer). PL/pgSQL dapat memiliki tipe variable sebagaimana yang dimiliki SQL, seperti integer, char, maupun varchar.<br />
Pada function somefunc dideklarasikan 1 variable bernama quantity pada outerblock, dan 1 variable bernama quantity pada sub-blok. Berikut adalah contoh deklarasi variable:<br />
<em>user_id integer;<br />
quantity numeric(5);<br />
url varchar;<br />
myrow tablename%ROWTYPE;<br />
myfield tablename.columnname%TYPE;<br />
arow RECORD;<br />
</em>Syntax umum untuk mendeklarasikan variable adalah sebagai berikut:<br />
<em>name [ CONSTANT ] type [ NOT NULL ] [ { DEFAULT &#124; := } expression ];</em><br />
Jika dalam deklarasi varible terdapat klausa DEFAULT, maka value awal akan dimasukkan ke dalam variable tersebut. Namun, jika tidak ada klausa DEFAULT, nilaia awal yang dimasukkan dalam variable tersebut adalah SQL NULL. Klausa CONSTANT membuat nilai variable ini selalu tetap, sehingga jika terjadi perintah pengisian nilai pada variable ini akan terjadi error. Klausa NOT NULL membuat pengisian SQL NULL pada variable ini error. Oleh karena itu, jika terdapat salah satu saja dari kedua properti ini, maka sebuah variable harus memiliki klausa DEFAULT. Khusus untuk klausa NOT NULL, nilai awal yang dimasukkan tidak boleh NULL.<br />
Klausa DEFAULT dijalankan setiap kali blok tersebut dijalankan, jadi tidak hanya saat function di-compile. Contoh, jika anda mendefinisikan varible bertipe DATE, kemudian diisi dengan nilai default NOW(), maka isi varible tersebut akan berubah setiap blok dijalankan, bukan hanya saat pertama kali function ini di-compile.<br />
Contoh penggunaan klausa DEFAULT dan CONSTANT:<br />
<em>quantity integer DEFAULT 32;<br />
url varchar := &#8216;http://mysite.com&#8217;;<br />
user_id CONSTANT integer := 10;<br />
</em></p>
<p><strong>Alias untuk Parameter Fungsi<br />
</strong>Alias digunakan untuk memberikan nama pada parameter fungsi. Secara default nama parameter adalah angka yang urut sesuai definisi paramter fungsi. Perhatikan contoh berikut:<br />
<em>CREATE FUNCTION somefunc(integer, varchar) RETURNS integer AS $$<br />
</em>Pada contoh diatas, terdapat 2 parameter pada function somefunc, keduanya berturut-turut bertipe integer dan varchar. Secara default kedua parameter tersebut berturut-turut bernama $1 dan $2. Penamaan semacam ini, pada kasus tertentu, menyulitkan anda dalam membuat dan membaca kode function. Untuk itu diperlukan penamaan parameter yang mencerminkan penggunaan parameter tersebut. Proses penamaan ini disebut dengan alias.<br />
Terdapat 2 cara membuat alias pada parameter function. Perhatikan 2 contoh berikut:<br />
<em>CREATE FUNCTION instr(varchar, integer) RETURNS integer AS $$<br />
DECLARE<br />
v_string ALIAS FOR $1;<br />
index ALIAS FOR $2;<br />
BEGIN<br />
&#8211; some computations using v_string and index here<br />
END;<br />
$$ LANGUAGE plpgsql;</em></p>
<p><em>CREATE FUNCTION sales_tax(subtotal real, OUT tax real) AS $$<br />
BEGIN<br />
tax := subtotal * 0.06;<br />
END;<br />
$$ LANGUAGE plpgsql<br />
</em>Pada contoh pertama, alias dilaksanakan pada bagian deklarasi function. Sedangkan pada contoh kedua, alias dilaksanakan saat pendefinisian parameter. Kedua contoh diatas tidak sepenuhnya identik. Pada contoh kedua, kita dapat membuat referensi sales_tax.subtotal, sedangkan pada contoh pertama fitur ini tidak ada. Hal ini disebabkan karena PL/pgSQL akan membuatkan label khusus secara implisit yang melingkup semua isi function dengan nama label sama dengan nama function, sehingga sales_tax.total nampak pada label ini, sedangkan pada contoh kedua alias parameter berada pada label yang berbeda.<br />
Pada kasus parameter dan return function yang bertipe polymorphic, PL/pgSQL akan secara otomatis membuat variable bernama $0 yang akan menjadi tipe data aktual dari return function tersebut. Ini dapat digunakan sebagai variable yang dapat menampung nilai return dari suatu function, meski kadang ini tidak diperlukan. Selanjutnya, variable ini dapat diberi alias seperti parameter, yang telah dijelaskan sebelumnya. Perhatikan contoh berikut:<br />
<em>CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement)<br />
RETURNS anyelement AS $$<br />
DECLARE<br />
result ALIAS FOR $0;<br />
BEGIN<br />
result := v1 + v2 + v3;<br />
RETURN result;<br />
END;<br />
$$ LANGUAGE plpgsql;</em></p>
<p><em>CREATE FUNCTION add_three_values(v1 anyelement, v2 anyelement, v3 anyelement,<br />
OUT sum anyelement)<br />
AS $$<br />
BEGIN<br />
sum := v1 + v2 + v3;<br />
END;<br />
$$ LANGUAGE plpgsql;<br />
</em>Pada contoh pertama, alias dilaksanakan pada bagian deklarasi function. Pada contoh kedua, alias dilaksanakan pada pendefinisian parameter.</p>
<p><strong>Menyalin Tipe Data<br />
</strong><em>variable%TYPE</em></p>
<p>Anda dapat mendefinisikan sebuah variable dengan tipe data yang dinamis, artinya tipe data variable tersebut dapat berubah saat function dijalankan (on the fly). Tipe data seperti ini banyak dibutuhkan jika anda ingin membuat variable yang menampung data dari sebuah kolom pada suatu tabel. %TYPE akan menyajikan tipe data atau tipe kolom pada sebuah tabel. Jika anda ingin membuat variable yang bernama user_id dan digunakan untuk menampung nilai kolom user_id pada tabel user, maka syntax yang digunakan adalah:<br />
<em>user_id user.user_id%TYPE;</em></p>
<p>Jika kolom user_id bertipe integer maka variable user_id juga beritipe integer. Jika dikemudian hari anda mengubah kolom ini sehingga bertipe float, maka variable user_id juga akan bertipe float, tanpa harus mengganti function ini.</p>
<p><strong>Row Type<br />
</strong><em>name tablename%ROWTYPE;<br />
name composite_type_name;</em></p>
<p>Sebuah variable komposit adalah variable row (atau variable row-type). Sebuah variable row dapat menampung nilai dari seluruh kolom hasil perintah select. Setiap kolom dapat diakses menggunakan tanda dot (.), misalnya: variablerow.namafield.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[List Table &amp; Dump DB di PostgreSQL]]></title>
<link>http://terjemahanku.wordpress.com/2009/11/22/list-table-dump-db-di-postgresql/</link>
<pubDate>Sun, 22 Nov 2009 10:49:54 +0000</pubDate>
<dc:creator>Agust Andy</dc:creator>
<guid>http://terjemahanku.wordpress.com/2009/11/22/list-table-dump-db-di-postgresql/</guid>
<description><![CDATA[Setelah lama tidak mainan PostgreSQL saya jadi terlupa beberapa perintah dasar it. Salah satunya men]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p style="text-align:justify;font:normal 11px verdana;">Setelah lama tidak mainan PostgreSQL saya jadi terlupa beberapa perintah dasar it. Salah satunya menampilkan tabel.</p>
<p><code>\dt</code></p>
<p style="text-align:justify;font:normal 11px verdana;">Sedangkan untuk nge-dump database bisa pakai perintah di bawah. <em>Pretty simple</em>. Perintah ini akan nge-dump baik struktur maupun data.</p>
<p><code>$ pg_dump nama_database &#62; out_file.sql</code></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[A brief introduction to AppStruct]]></title>
<link>http://blog.gahooa.com/2009/11/21/a-brief-introduction-to-appstruct/</link>
<pubDate>Sat, 21 Nov 2009 05:26:45 +0000</pubDate>
<dc:creator>Jason Garber</dc:creator>
<guid>http://blog.gahooa.com/2009/11/21/a-brief-introduction-to-appstruct/</guid>
<description><![CDATA[Have been very busy at work lately.  We made the decision about a month ago to switch (most|all) new]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Have been very busy at work lately.  We made the decision about a month ago to switch (most&#124;all) new projects over to use Python 3 with Apache, mod_wsgi, and AppStruct.  You may know what the first 3 are, but the 4th??</p>
<p style="padding-left:30px;"><em>Special thanks goes to </em><strong><em>Graham Dumpleton</em></strong><em> behind mod_wsgi, and </em><strong><em>James William Pye</em></strong><em> behind Python&#62;&#62;Postgresql.   They are not involved or affiliated with AppCove or AppStruct (aside from great mailing list support) <strong>BUT</strong> if it were not for them, this framework would not exist.</em></p>
<p>AppStruct is a component of Shank, a meta-framework.  A stand-alone component in it&#8217;s own right, it represents the AppCove approach to web-application development.  Most of it is in planning, but the parts that have materialized are really, really cool.</p>
<p>Briefly, I&#8217;ll cover the two emerging areas of interest:</p>
<h1><strong>AppStruct.WSGI</strong></h1>
<p>This is a very pythonic (in my opinion) web application framework targeted toward Python 3.1 (a challenge in itself at this point).  We really wanted to base new development on Python 3.1+, as well as PostgreSQL using the excellent Python3/PostgreSQL library at <a href="http://python.projects.postgresql.org/">http://python.projects.postgresql.org/</a>.  However, none of the popular frameworks that I am aware of support Python 3, and most (if not all) of them have a lot of baggage I do not want to bring to the party.</p>
<p><a href="http://werkzeug.pocoo.org/">Werkzeug</a> was the most promising, but alas, I could not find Python 3 support for it either.  In fact, I intend to utilize a good bit of code from Werkzeug in finishing off AppStruct.WSGI.  (Don&#8217;t you just love good OSS licences?  AppStruct will be released under one of those also).</p>
<p>HTTP is just not that complicated.  It dosen&#8217;t need bundled up into n layers of indecipherable framework upon framework layers.   It doesn&#8217;t need abstracted to death.  I just needs to be streamlined a bit (with regard to request routing, reading headers, etc&#8230;).</p>
<p>Python is an amazing OO language.  It&#8217;s object model (or data model) is one of (if not the) most well conceived of any similar language, ever.  I want to use that to our advantage&#8230;</p>
<p>Inheritance, including multiple inheritance, has very simple rules in Python.  Want to use that as well.</p>
<p>Wish to provide developers with access to the low level guts they need for 2% of the requests, but not make them do extra work for the 98% of requests.</p>
<p>Speed is of the essence.  Servers are not cheap, and if you can increase your throughput by 5x, then that&#8217;s a lot less servers you need to pay for.</p>
<p><strong>So, how does it work?</strong></p>
<p>Well, those details can wait for another post.  But at this point the library is &#60; 1000 lines of code, and does a lot of interesting things.</p>
<ul>
<li>A fully compliant WSGI application object</li>
<li>1 to 1 request routing to Python packages/modules/classes</li>
<li>All request classes derived from AppStruct.WSGI.Request</li>
</ul>
<p>The application maps requests like <strong>/some/path/here</strong> to objects, like <strong>Project.WSGI.some.path.here</strong>.  If there is a trailing slash, then the application assumes that the class is named Index.  The object that is found is verified to be a subclass of AppStruct.WSGI.Request, and then&#8230;</p>
<p>Wait!  What about security?</p>
<p>Yes, yes, very important.  A couple things to point out.  First, the URLs are passed through a regular expression that ensures that they adhere to only the characters that may be used in valid python identifiers (not starting with _), delimited by &#8220;/&#8221;.  Second, the import and attribute lookup verify that any object (eg class) found is a subclass of the right thing.  And so on and so forth&#8230;</p>
<p>But you may say &#8220;wait, what about my/fancy-shmancy/urls/that-i-am-used-to-seeing?  Ever hear of mod_rewrite?  Yep.  Not trying to re-invent the wheel.  Use apache for what it was made for, not just a dumb request handler.</p>
<p><strong>What about these request objects?</strong></p>
<p>They are quite straightforward.  There are several attributes which represent request data, the environment, query string variables, post variables, and more.  There is a .Response attribute which maps to a very lightweight response object.</p>
<p>Speaking of it &#8212; it has only 4 attributes:<strong> [Status, Header, Iterator, Length]</strong>.  As you see, it&#8217;s pretty low-level-wsgi-stuff.  But the developer would rarely interact with it, other than to call a method like .Response.Redirect(&#8216;http://somewhere-else.com&#8217;, 302)</p>
<p>Once the application finds the class responsible for handling the URL, it simply does this (sans exception catching code):</p>
<pre style="padding-left:30px;">RequestObject = Request(...)</pre>
<pre style="padding-left:30px;">with RequestObject:
   RequestObject.Code()
   RequestObject.Data()</pre>
<pre style="padding-left:30px;">return RequestObject.Response</pre>
<p>Wow, that&#8217;s simple.  Let me point out one more detail.  The default implementation of Data() does this:</p>
<pre style="padding-left:30px;">def Data(self):
   self.Response.Iterator = [self.Text()]
   self.Response.Length = len(self.Response.Iterator[0])</pre>
<p>So the only thing really required of this Request class is to override Text() and return some text?  Yep, that simple.</p>
<p>But typically, you would at some point mixin a template class that would do something like this:</p>
<pre style="padding-left:30px;">class GoodLookingLayout:
   def Text(self):
      return ( 
         """&#60;html&#62;&#60;head&#62;...&#60;/head&#62;&#60;body&#62;&#60;menu&#62;""" +
         self.Menu() +
         """&#60;/menu&#62;&#60;div&#62;""" +
         self.Body() +
         """&#60;/div&#62;&#60;/body&#62;&#60;/html&#62;"""
         )</pre>
<p>And then it would be up to the developer to override Menu and Body (each returning the appropriate content for the page).</p>
<p><strong>Ohh</strong>, you may say.  What about templating engine X?  Well, it didn&#8217;t support Python 3, and I probabally didn&#8217;t want it anyway (for 9 reasons)&#8230;  If it&#8217;s really, really good and fits this structure, drop me a line, please.</p>
<p><strong>What about that Code() method?</strong></p>
<p>Yeah, that&#8217;s the place that any &#8220;logic&#8221; of UI interaction should go.  I&#8217;m not advocating mixing logic and content here, but you could do that if you wanted.  You will find in our code, a seperate package for application business logic and data access that the request classes will call upon.  But again, if you are writing a one page wonder, why go to all the trouble?</p>
<p>The only requirement for the Code() method is that it calls <strong>super().Code()</strong> at the top.  Since the idea is that the class <strong>.Foo.Bar.Baz.Index</strong> will inherit from the class <strong>.Foo.Bar.Index</strong>, this gives you a very flexible point of creating .htaccess style initialization/access-control code in one place.  So in /Admin/Index, you could put a bit of code in Code() which ensures the user is logged in.  This code will be run by all sub-pages, therefore ensuring that access control is maintained.  Relative imports are important for this task.</p>
<pre style="padding-left:30px;">from .. import Index as <span style="color:#ff0000;">PARENT</span>
from AppStruct.WSGI.Util import *</pre>
<pre style="padding-left:30px;">class Index(<span style="color:#ff0000;">PARENT</span>):
   def Code(self):
      super().Code()
      self.Name = self.Post.FirstName + " " + self.Post.LastName
      # some other init stuff
   def Body(self):
      return "Hello there " + HS(self.Name) + "!"</pre>
<p><strong>Summary of AppStruct.WSGI&#8230;</strong></p>
<p>To get up and running with a web-app using this library:</p>
<ol>
<li>A couple mod_wsgi lines in httpd.conf</li>
<li>A .wsgi file that has 1 import and 1 line of code</li>
<li>A request class in a package that matches an expected URI (myproject.wsgi.admin.foo ==  /admin/foo)</li>
</ol>
<p><strong>Speed?</strong></p>
<p>With no database calls, it&#8217;s pushing over 2,000 requests per second on a dev server.  With a couple PostgreSQL calls, it is pushing out ~ 800 per second.</p>
<h1>AppStruct.Database.PostgreSQL</h1>
<p>This is not nearly as deep as the WSGI side of AppStruct, but still really cool.  To start off, I&#8217;d like to say that James William Pye has created an amazing Postgresql connection library in Python 3.  I mean just amazing.  In fact, almost so amazing that I didn&#8217;t want to change it (but then again&#8230;)</p>
<p>What we did here was subclass the <strong>Connection</strong>, <strong>PreparedStatement</strong>, and <strong>Row </strong>classes.  (well, actually replaced the Row class).</p>
<p>Once these were subclassed, we simply added a couple useful features.  Keep in mind that all of the great functionality of the underlying library is retained.</p>
<p><strong>Connection.CachePrepare(SQL)<br />
Connection._PS_Cache</strong></p>
<p>Simply a dictionary of {SQL: PreparedStatementObject} that resides on the connection object.  When you directly or indirectly invoke CachePrepare, it says &#8220;if this SQL is in the cache, return the associated object.  Otherwise, prepare it, cache it, and return it&#8221;.  This approach really simplifies the storing of prepared statement objects in a multi-threaded environment, where there is really no good place to store them (and be thread safe, connection-failure safe, etc&#8230;)</p>
<p><strong>Connection.Value(SQL, *args, **kwargs)<br />
Connection.Row(SQL, *args, **kwargs)</strong></p>
<p><strong></strong>These simple functions take (SQL, *args, **kwargs) and return either a single value or a single row.  They will raise an exception is != 1 row is found.  They make use of CachePrepare(), so you get the performance benefits of prepared statements without the hassle.  More on *args, **kwargs later under PrePrepare()</p>
<p><strong>Connection.ValueList(SQL, *args, **kwargs)<br />
Connection.RowList(SQL, *args, **kwargs)</strong></p>
<p><strong></strong>Same as above, except returns an iterator (or list, not sure) of  zero or more values or rows.</p>
<p><strong>Row class</strong></p>
<p>Simply a dictionary that also supports attribute style access of items.  After evaluating the Tuple that behaves like a mapping, I decided for our needs, a simple dict would be a better representation of a row.</p>
<p><strong>Connection.PrePreprepare(SQL, args, kwargs) -&#62; (SQL, args)</strong></p>
<p>Ok, so what&#8217;s the big deal?  Well, the big deal is that we don&#8217;t like positional parameters.  They are confusing to write, read, analyze, and see what the heck is going on when you get about 30 fields in an insert statement.  Feel free to argue, but maybe I&#8217;m not as young as I once was.</p>
<p>We do like keyword parameters.  But postgresql prepared statement api uses numeric positional parameters.  Not changing that&#8230;</p>
<p>The most simple use case is to pass SQL and keyword arguments.</p>
<pre style="padding-left:30px;">"SELECT a,b,c FROM table WHERE id = $id AND name = $name"
dict(id=100, name='joe')</pre>
<p>It returns</p>
<pre style="padding-left:30px;">"SELECT a,b,c FROM table WHERE id = $1 AND name = $2"
(100, "joe")</pre>
<p>Which is suitable for passing directly into the Connection.prepare() method that came with the underlying library.</p>
<p>I don&#8217;t know about you, but we find this to be very, very useful.</p>
<p>If you pass tuples of (field, value) as positional arguments, then they will replace <strong>[Field]</strong>, <strong>[Value]</strong>, and <strong>[Field=Value]</strong> (in the SQL) with lists of fields, lists of values (eg $1, $2), or lists of field=values (eg name=$1, age=$2).  That really takes the verbosity out of INSERT and UPDATE statements with long field lists.</p>
<h1>Conclusion</h1>
<p>This is just in the early stages, and has a good deal of polishing to be done (especially on the WSGI side).  My purpose here was to introduce you to what you can expect to get with AppStruct, some of the rationale behind it, and that it&#8217;s really not that hard to take the bull by the horns and make software do what you want it to (especially if you use python).</p>
<p>Feel free to comment.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Comparison of different SQL implementations]]></title>
<link>http://pgolub.wordpress.com/2009/11/19/comparison-of-different-sql-implementations/</link>
<pubDate>Thu, 19 Nov 2009 06:22:51 +0000</pubDate>
<dc:creator>pashagolub</dc:creator>
<guid>http://pgolub.wordpress.com/2009/11/19/comparison-of-different-sql-implementations/</guid>
<description><![CDATA[Found a comprehensive research called &#8220;Comparison of different SQL implementations&#8221;. Gre]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Found a comprehensive research called <a href="http://troels.arvin.dk/db/rdbms/">&#8220;Comparison of different SQL implementations&#8221;</a>.</p>
<p>Great work done.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[10 Very useful web design and web programming tools]]></title>
<link>http://kahrn.wordpress.com/2009/11/18/10-very-useful-webdesign-and-web-programming-tools/</link>
<pubDate>Wed, 18 Nov 2009 20:28:31 +0000</pubDate>
<dc:creator>kahrn</dc:creator>
<guid>http://kahrn.wordpress.com/2009/11/18/10-very-useful-webdesign-and-web-programming-tools/</guid>
<description><![CDATA[Web development today Web development today isn&#8217;t just HTML editing or basic php scripts. Web ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><strong>Web development today</strong></p>
<p>Web development today isn&#8217;t just HTML editing or basic php scripts. Web development and programming today is usually achieved with a wide set of tools &#8212; any popular website around today uses a wide set of tools. For example,</p>
<ul>
<li>reddit.com &#8212; reddit uses <a href="http://python.org" target="_blank">Python</a> and <a href="http://en.wikipedia.org/wiki/PostgreSQL" target="_blank">PostgreSQL</a>, which spit out html (of xhtml syntax), javascript and <a href="http://www.w3schools.com/css/css_intro.asp" target="_blank">CSS</a>.</li>
<li>slashdot.com &#8212; slashdot.com uses Perl and MySQL, sitting on top of Apache.</li>
<li>microsoft.com &#8212; microsoft.com uses a combination of ASP.NET, running on top of IIS. The output is html (xhtml syntax), css and javascript.</li>
</ul>
<h2>The tools</h2>
<h3>Web Developer / Firefox Extension</h3>
<p>Firefox Web Developer Extension is a useful tool for being able to disable various features on a page, manage cookies, view specific css information using a picker tool for any specific elements and being able to manager userstyles. You can also manage images and various other tools including the ability to view generated source.</p>
<p>You can download it at <a href="https://addons.mozilla.org/en-US/firefox/addon/60" target="_blank">Mozilla Add-ons</a></p>
<h3>ColorZilla / Firefox Extension</h3>
<p><a href="http://kahrn.wordpress.com/files/2009/11/blogwebdevcolorzilla.png"><img src="http://kahrn.wordpress.com/files/2009/11/blogwebdevcolorzilla.png?w=300" alt="" title="Colorzilla Firefox Extension" width="125" height="119" class="alignright size-medium wp-image-246" /></a>ColorZilla is an extension to firefox that adds a color picker tool to the browser UI. It is then possible to return information for a given pixel on a website.</p>
<p>You can download it at the <a href="https://addons.mozilla.org/en-US/firefox/addon/271" target="_blank">Mozilla Add-ons</a> site.</p>
<h3>MeasureIT / Firefox Extension</h3>
<p><a href="http://kahrn.wordpress.com/files/2009/11/blogwebdevmeasureit.png"><img src="http://kahrn.wordpress.com/files/2009/11/blogwebdevmeasureit.png?w=150" alt="" title="MeasureIT Firefox Extension" width="150" height="83" class="alignright size-thumbnail wp-image-250" /></a>The measureIT Firefox extension adds a measuring tool that appears as an overlay on any webpage you need to use it on.</p>
<p>You can download measureIT at the <a href="https://addons.mozilla.org/en-US/firefox/addon/539" target="_blank">Mozilla Add-ons</a> site</p>
<h3>DOM Inspector / Firefox Extension</h3>
<p><a href="http://kahrn.wordpress.com/files/2009/11/blogwebdevdominspector.png"><img src="http://kahrn.wordpress.com/files/2009/11/blogwebdevdominspector.png?w=150" alt="" title="Firefox DOM Inspector" width="150" height="112" class="alignright size-thumbnail wp-image-253" /></a>The Document Object Model Inspector is a tool to inspect the DOM of any webpage. It often comes with the default install of firefox as an option.</p>
<p>You can download DOM Inspector at <a href="https://developer.mozilla.org/en/dom_inspector" target="_blank">https://developer.mozilla.org/en/dom_inspector</a></p>
<h3>Firebug / Firefox Extension</h3>
<p>Firebug is an extension which is useful for editing css, html or javascript elements within a webpage.</p>
<p>You can download Firebug at the <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" target="_blank">Mozilla Add-ons</a> site.</p>
<h3>Google page speed / Firebug Extension</h3>
<p><a href="http://kahrn.wordpress.com/files/2009/11/blogwebdevgooglepagespeed11.png"><img src="http://kahrn.wordpress.com/files/2009/11/blogwebdevgooglepagespeed11.png?w=150" alt="" title="Google web page speed for Firebug" width="150" height="116" class="alignright size-thumbnail wp-image-255" /></a>Google page speed is a Firebug extension that is able to give you a wealth of information on the download speeds and execution time of your website. It can also give you tips on how to reduce overheads and improve code.</p>
<p>You can download the Google page speed Firebug extension at the <a href="http://code.google.com/speed/page-speed/download.html" target="_blank">google page speed</a> site.</p>
<h3>Notepad++</h3>
<p><a href="http://kahrn.wordpress.com/files/2009/11/blogwebdevnotepadplusplus1.png"><img src="http://kahrn.wordpress.com/files/2009/11/blogwebdevnotepadplusplus1.png?w=150" alt="" title="Notepad++" width="150" height="115" class="alignright size-thumbnail wp-image-259" /></a>Notepad++ is a tool I often use when working on smaller projects where I do not need a full IDE.</p>
<blockquote><p><strong>Notepad++</strong> is a free (as in &#8220;free speech&#8221; and also as in &#8220;free beer&#8221;) source code editor and Notepad replacement that supports several languages. Running in the MS Windows environment, its use is governed by <a href="http://www.gnu.org/copyleft/gpl.html" target="_blank">GPL</a> License.<br />
Based on a powerful editing component <a href="http://www.scintilla.org/" target="_blank">Scintilla</a>, Notepad++ is written in C++ and uses pure Win32 API and STL which ensures a higher execution speed and smaller program size.</p></blockquote>
<p>You can download it over at the <a href="http://notepad-plus.sourceforge.net/uk/site.htm">notepad++ sourceforge</a> project site.</p>
<h3>Netbeans with PHP Development plugin</h3>
<p><a href="http://kahrn.wordpress.com/files/2009/11/blogwebdevnetbeans.png"><img src="http://kahrn.wordpress.com/files/2009/11/blogwebdevnetbeans.png?w=150" alt="" title="Netbeans with PHP Plugin" width="150" height="116" class="alignright size-thumbnail wp-image-260" /></a>Netbeans is a Java IDE developed by Sun. It supports various plugins &#8212; one being PHP development extensions. When working on large projects, Netbeans proves useful.</p>
<p>You can download it at the <a href="http://netbeans.org/">Netbeans</a> site.</p>
<h3>Visual SVN</h3>
<p>VisualSVN is a SVN server for Windows. It is quick and easy to use and requires little previous knowledge of server administration or svn experience, but it can also be quite powerful.</p>
<p>You can download it at the <a href="http://www.visualsvn.com/server/download/">VisualSVN Server</a> site. It is free for both personal and commercial use.</p>
<h3>Tortoise SVN</h3>
<p>TortoiseSVN is an SVN client that interfaces with Windows Explorer to interface with SVN.</p>
<p>You can download it at the <a href="http://tortoisesvn.tigris.org/">TortoiseSVN</a> site.</p>
<h3>XAMPP</h3>
<p>XAMPP is a quick and easy way to get an apache server, MySQL daemon and PHP all running on Windows for a development environment. It also supports an FTP server and a few other things.</p>
<p>You can download it at the <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> site.</p>
<p><strong>Forums</strong><br />
You can come and discuss web development, get website reviews and also SEO information at the <a href="http://tdlabs.co.uk/forums">Transcendental Labs</a> forum.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Finding Median with PostgreSql]]></title>
<link>http://plusplus.wordpress.com/2009/11/18/finding-median-with-postgresql/</link>
<pubDate>Wed, 18 Nov 2009 18:48:58 +0000</pubDate>
<dc:creator>plusplus</dc:creator>
<guid>http://plusplus.wordpress.com/2009/11/18/finding-median-with-postgresql/</guid>
<description><![CDATA[This is how you can get the median value of a column in PostgreSql. Thanks to http://old.nabble.com/]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>This is how you can get the median value of a column in PostgreSql. Thanks to http://old.nabble.com/SELECT-TOP&#8211;d-PERCENT,-or-SELECT-&#8230;-LIMIT&#8211;d-PERCENT&#8212;td19941366.html</p>
<p>&#160;</p>
<p>WITH c AS (select count(*)/2 as n from FOO) select COL from FOO order by COL asc limit (1) offset (select n from c);</p>
<p>&#160;</p>
<p>It is much simpler if you are using SQL Server as described in: http://www.sqlmag.com/Article/ArticleID/49827/sql_server_49827.html</p>
<pre>SELECT MAX(Value) FROM
  (SELECT TOP 50 PERCENT Value FROM dbo.VOrders ORDER BY Value) AS H1;

--
Reza++
</pre>
</div>]]></content:encoded>
</item>

</channel>
</rss>
