Tuesday, August 12, 2008

[GENERAL] Alias for function return buffer in pl/pgsql?

Hello all, long time no chit-chat on the PG mailing list.  We’re upgrading from 8.0.3 to 8.3 and found that some stored procedures utilizing int_agg that we had left over from 7.3 had terrible performance.  No problem, using ANY() we’re able to regain that performance, more or less, and at the same time greatly simplify our stored procedures.  But things can never be fast enough, can they?  So I have a question or two.  Here’s my function for reference:

 

CREATE OR REPLACE FUNCTION bg_nodes2descendants(INT[], INT) RETURNS SETOF connection_generation AS

'

 

DECLARE

_row connection_generation%ROWTYPE;

_children INT[];

 

BEGIN

 

-- this is faster than constructing in the loop below

--_children = array(SELECT connectee_node_id FROM connections WHERE connection_type_id = 1 AND connector_node_id = ANY($1));

 

FOR _row IN

    SELECT connection_id, connection_type_id, connector_node_id, connector_node_type_id, connectee_node_id,

            connectee_node_type_id, current, timestamp, $2 + 1

        FROM connections WHERE connection_type_id = 1 AND connector_node_id = ANY($1)

    LOOP

        _children := _children || _row.connectee_node_id;

        RETURN NEXT _row;

    END LOOP;

 

IF FOUND THEN

    RETURN QUERY SELECT * FROM bg_nodes2descendants(_children, $2+1);

END IF;

 

RETURN;

END

 

' LANGUAGE 'plpgsql';

 

     So, my concern is alluded to in the comment above.  When I use this function in places where it returns large results, building the _children array directly (in the commented out line) is about 25% faster.  But I’d like to avoid building the children array altogether and would instead like to generate that array from the already collected output rows.  For example, right before the recursive call, I’d like to select a column of the buffered output rows, cast it to an integer[], and pass it into the recursive call.  Is there an internal value I can access for this such as:

 

_children := array(SELECT connectee_node_id FROM $output);

 

Bonus question -  if I rewrite the first FOR loop as:

 

RETURN QUERY SELECT connection_id, connection_type_id, connector_node_id, connector_node_type_id, connectee_node_id,

                             connectee_node_type_id, current, timestamp, $2 + 1 FROM connections

                 WHERE connection_type_id = 1 AND connector_node_id = ANY($1);

 

I get “ERROR:  structure of query does not match function result type”, even though the type signatures of the returned columns match the “connection_generation” rowtype.  I am pretty sure this could be resolved by casting the resulting columns to that row type, but I am lost as to how the syntax to do such a thing would look.

 

Thanks in advance for the help, and keep up the great work.  PG8.3 is an amazing piece of software and it blows me away how much more advanced it gets with every release.

 

Bart Grantham

VP of R&D

Logicworks Inc. – Complex and Managed Hosting

[GENERAL] psql tutorial

Sir,
          Please get me PostgreSQL psql tutorial.

With regards,
P.Yesu

[GENERAL] Newbie [CentOS 5.2] service postgresql initdb

While going through
http://wiki.postgresql.org/wiki/Detailed_installation_guides
and typing
service postgresql start
as root I got
"/var/lib/pgsql/data is missing. Use "service postgresql initdb" to
initialize the cluster first."

When I run
service postgresql initdb
I get
"se: [FAILED]".
However, /var/lib/pqsql/data is created and user postgres owns it.

But then I run
service postgresql start
and the very same error occurs..

Daneel

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] Need help returning record set from a dynamic sql query

Please understand…

 

I know I have to use FOR … LOOP for my query. But it is not a normal one …I use to build that one dynamically.

 

 

From: Willy-Bas Loos [mailto:willybas@gmail.com]
Sent: Tuesday, August 12, 2008 5:46 PM
To: MuraliPD@GMail
Cc: Sathish Duraiswamy; pgsql-general@postgresql.org
Subject: Re: [GENERAL] Need help returning record set from a dynamic sql query

 

>Iam getting just the first record from the recordset
That's because you use SELECT INTO, you should use   FOR rec IN <query> LOOP

Here's sample code from http://www.postgresql.org/docs/8.1/interactive/plpgsql-control-structures.html

CREATE TABLE test (textcol varchar(10), intcol int);
INSERT INTO test VALUES ('a', 1);
INSERT INTO test VALUES ('a', 2);
INSERT INTO test VALUES ('b', 5);
INSERT INTO test VALUES ('b', 6);

CREATE OR REPLACE FUNCTION ReturnNexting(pText Text) RETURNS SETOF test AS $$
DECLARE
rec RECORD;
BEGIN
FOR rec IN SELECT * FROM test WHERE textcol = pText LOOP
RETURN NEXT rec;
END LOOP;
RETURN;
END;
$$
LANGUAGE plpgsql;

SELECT * FROM ReturnNexting('a');

On Tue, Aug 12, 2008 at 12:58 PM, MuraliPD@GMail <murali.pd@gmail.com> wrote:

Hi Sathish,

 

Thanks for your reply.

 

But I have created the type to return the record set from my join query using a stored function.

 

I cannot able to create a table with that details …. Since those details will be already available from different tables.

 

One more thing …. I am clear with your result set using FOR ..LOOP but mine is not a normal query… it was built Dynamic based on my Input Parameters.

 

Please look and tell me if you are not clear with my query.

 

 

Thanks,

MuraliDharan V

 

From: Sathish Duraiswamy [mailto:sathish@leatherlink.net]
Sent: Tuesday, August 12, 2008 4:10 PM
To: MuraliPD@GMail
Cc: pgsql-general@postgresql.org
Subject: Re: [GENERAL] Need help returning record set from a dynamic sql query

 

Dear murali,

We use psql for our ERP software .We found CREATE TYPE is useful in creating new data type similar to creating domain.
For eg
       CREATE TYPE date_condition (
                   condition_id int,
                   from_date  date,
                   to_date    date);                   

Instead , you can CREATE TABLE (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);

You can have result returning a set of records

Feel free to comment on it

Regrds
sathish

On Tue, Aug 12, 2008 at 3:08 PM, MuraliPD@GMail <murali.pd@gmail.com> wrote:

Hi,

Iam new to Postgresql, now i need to create a Dynamic SQL Query for returning the record set
based on my Input Parameters. I looked up some of the documents and worked out some more ...

MY Postgresql Version In Local: 7.4
MY Postgresql Version In Development: 8.2


-- DROP TYPE ORDERREPORT;
CREATE TYPE ORDERREPORT AS (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);


-- DROP FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER);
CREATE OR REPLACE FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER) RETURNS SETOF ORDERREPORT AS
'
DECLARE
vResult ORDERREPORT%ROWTYPE;
vSql TEXT = ''
SELECT
   ORDR.ORDERSID       AS OrderID,
   ORDR.INITIATED       AS Order_Date,
   COMP.COMPANYNAME    AS Company_Name,
   EVNT.EVENTNAME      AS Event_Name
FROM
   ORDERS ORDR
   INNER JOIN COMPANY COMP ON COMP.COMPANYID = ORDR.COMPANY
   INNER JOIN EVENT EVNT ON EVNT.COMPANY = COMP.COMPANYID
WHERE
   ORDR.EVENT = EVNT.EVENTID '';
BEGIN
   IF $1 IS NOT NULL THEN
      vSql = vSql ||'' AND ORDR.ORDERSID = ''|| $1;
   END IF;
        
   IF $2 IS NOT NULL THEN
      vSql = vSql ||'' AND COMP.COMPANYID = ''|| $2;
   END IF;

   IF $3 IS NOT NULL THEN
      vSql = vSql ||'' AND EVNT.EVENTID = ''|| $3;
   END IF;
   EXECUTE vSql INTO vResult;
   RETURN NEXT vResult;
END '
LANGUAGE 'PLPGSQL';

Result:

events=# SELECT * FROM FUN_ORDERREPORT(102881,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)

events=# SELECT * FROM FUN_ORDERREPORT(NULL,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)


Iam getting just the first record from the recordset.
Can someone help me how can i return all query results from a Dynamic SQL Query?


--
Thanks,
MuraliDharan V

 

 

Re: [PERFORM] Using PK value as a String

Bill Moran wrote:
The main reason to use UUID instead of sequences is if you want to be able to generate unique values across multiple systems. So, for example, if you want to be able to send these userids to another system which is taking registrations from lots of places. Of course that only works if that other system is already using UUIDs and you're all using good generators.     
 Note that in many circumstances, there are other options than UUIDs.  If you have control over all the systems generating values, you can prefix each generated value with a system ID (i.e. make the high 8 bits the system ID and the remaining bits come from a sequence)  This allows you to still use int4 or int8.  UUID is designed to be a universal solution.  But universal solutions are frequently less efficient than custom-tailored solutions.   

Other benefits include:
    - Reduced management cost. As described above, one would have to allocate keyspace in each system. By using a UUID, one can skip this step.
    - Increased keyspace. Even if keyspace allocation is performed, an int4 only has 32-bit of keyspace to allocate. The IPv4 address space is already over 85% allocated as an example of how this can happen. 128-bits has a LOT more keyspace than 32-bits or 64-bits.
    - Reduced sequence predictability. Certain forms of exploits when the surrogate key is exposed to the public, are rendered ineffective as guessing the "next" or "previous" generated key is far more difficult.
    - Used as the key into a cache or other lookup table. Multiple types of records can be cached to the same storage as the sequence is intended to be universally unique.
    - Flexibility to merge systems later, even if unplanned. For example, System A and System B are run independently for some time. Then, it is determined that they should be merged. If unique keys are specific to the system, this becomes far more difficult to implement than if the unique keys are universal.

That said, most uses of UUID do not require any of the above. It's a "just in case" measure, that suffers the performance cost, "just in case."

Cheers,
mark

--  Mark Mielke <mark@mielke.cc> 

Re: [pgsql-es-ayuda] Actualizar estructura de una BD en base a otra

El día 12 de agosto de 2008 8:59, el-PRiNCiPiTo
<el-PRiNCiPiTo@terra.es> escribió:
> Hola, no se ni que titulo poner en el post porque no se si esta forma de
> trabajo que tenemos es muy buena. Yo creo que no así que agradezco cualquier
> sugerencia.
>
> Os explico a que me refiero con la forma de trabajo:
> Estamos desarrollando un programa que almacena los datos en una base de
> datos postgresql (la versión es 8.2). El programa ya esta funcionando pero
> vamos añadiéndole funciones, lo que hace que tengamos que añadir tablas o
> campos a las tablas ya creadas en el base de datos.
> Entonces tenemos una "copia" de la base de datos que se usa en el programa
> en el equipo en que se desarrolla el programa. Yo añado lo que necesito a
> esta base de datos y cuando actualizo el programa añado a mano cada tabla o
> campo nuevo en la base de datos "verdadera".
> El problema de esto es que, ademas de ser muy laborioso, no es nada
> practico ya que es difícil saber si has añadido todo lo nuevo.
>
> Entonces mi pregunta es si hay alguna forma de "actualizar" la base de
> datos del programa usando la "nueva versión" y conservando los datos que ya
> hay en la base de datos ya que los datos que tengo en la nueva son sólo para
> pruebas y los de la antigua son datos reales que no deben modificarse.
>
> Espero haberme explicado, yo creo que todo este proceso que hacemos es
> demasiado complicado y que debe haber un sistema mejor para trabajar así
> alguien me sugiere otra forma de trabajo que solucione este problema me
> serviría igualmente.
>
> Muchas gracias a todos.

No creo serte de mucha ayuda, pero yo una vez ya plantee el mismo
problema y no llegamos a ninguna solución razonable, pero puedes
buscar en el archivo de la lista, ahora no puedo revisar y pasarte el
link pero creo que hay varias formas de "automatizar" el trabajo de
"parcheado" pero sigue siendo complicado...

Un abrazo
--
§~^Calabaza^~§ from Villa Elisa, Paraguay
----------------
A hendu hína: The Beatles - Three cool cats
http://foxytunes.com/artist/the+beatles/track/three+cool+cats
--
TIP 6: ¿Has buscado en los archivos de nuestra lista de correo?
http://archives.postgresql.org/pgsql-es-ayuda

Re: [PERFORM] Using PK value as a String

In response to Gregory Stark <stark@enterprisedb.com>:

> "Mario Weilguni" <mweilguni@sime.com> writes:
>
> > UUID is already a surrogate key not a natural key, in no aspect better than a
> > numeric key, just taking a lot more space.
> >
> > So why not use int4/int8?
>
> The main reason to use UUID instead of sequences is if you want to be able to
> generate unique values across multiple systems. So, for example, if you want
> to be able to send these userids to another system which is taking
> registrations from lots of places. Of course that only works if that other
> system is already using UUIDs and you're all using good generators.

Note that in many circumstances, there are other options than UUIDs. If
you have control over all the systems generating values, you can prefix
each generated value with a system ID (i.e. make the high 8 bits the
system ID and the remaining bits come from a sequence) This allows
you to still use int4 or int8.

UUID is designed to be a universal solution. But universal solutions
are frequently less efficient than custom-tailored solutions.

--
Bill Moran
Collaborative Fusion Inc.
http://people.collaborativefusion.com/~wmoran/

wmoran@collaborativefusion.com
Phone: 412-422-3463x4023

--
Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-performance

[pgsql-es-ayuda] Actualizar estructura de una BD en base a otra

Hola, no se ni que titulo poner en el post porque no se si esta
forma de trabajo que tenemos es muy buena. Yo creo que no así que
agradezco cualquier sugerencia.

Os explico a que me refiero con la forma de trabajo:
Estamos desarrollando un programa que almacena los datos en una base
de datos postgresql (la versión es 8.2). El programa ya esta funcionando
pero vamos añadiéndole funciones, lo que hace que tengamos que añadir
tablas o campos a las tablas ya creadas en el base de datos.
Entonces tenemos una "copia" de la base de datos que se usa en el
programa en el equipo en que se desarrolla el programa. Yo añado lo que
necesito a esta base de datos y cuando actualizo el programa añado a
mano cada tabla o campo nuevo en la base de datos "verdadera".
El problema de esto es que, ademas de ser muy laborioso, no es nada
practico ya que es difícil saber si has añadido todo lo nuevo.

Entonces mi pregunta es si hay alguna forma de "actualizar" la base
de datos del programa usando la "nueva versión" y conservando los datos
que ya hay en la base de datos ya que los datos que tengo en la nueva
son sólo para pruebas y los de la antigua son datos reales que no deben
modificarse.

Espero haberme explicado, yo creo que todo este proceso que hacemos
es demasiado complicado y que debe haber un sistema mejor para trabajar
así alguien me sugiere otra forma de trabajo que solucione este problema
me serviría igualmente.

Muchas gracias a todos.
--
TIP 5: ¿Has leído nuestro extenso FAQ?
http://www.postgresql.org/docs/faqs.FAQ.html

Re: [PERFORM] Using PK value as a String

"Mario Weilguni" <mweilguni@sime.com> writes:

> UUID is already a surrogate key not a natural key, in no aspect better than a
> numeric key, just taking a lot more space.
>
> So why not use int4/int8?

The main reason to use UUID instead of sequences is if you want to be able to
generate unique values across multiple systems. So, for example, if you want
to be able to send these userids to another system which is taking
registrations from lots of places. Of course that only works if that other
system is already using UUIDs and you're all using good generators.

You only need int8 if you might someday have more than 2 *billion* users...
Probably not an urgent issue.

--
Gregory Stark
EnterpriseDB http://www.enterprisedb.com
Ask me about EnterpriseDB's Slony Replication support!

--
Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-performance

Re: [GENERAL] pg crashing

Tom Lane wrote:
> Magnus Hagander <magnus@hagander.net> writes:
>> I'll see if I can repro a case like it to see if the syslogger prevents
>> the shared mem from going away when I get back to a dev box. Should be
>> enough to just stick a sleep preventing it from stopping, right?
>
> The syslogger isn't restarted at all during a crash --- this isn't
> a race-condition scenario.
>
> If there is a race condition here, it must be associated with cleanup
> for a process continuing to happen after win32_waitpid has already
> reported it dead. Hmm ... how much do we trust that bit of spaghetti
> around pgwin32_deadchild_callback? What condition is it really waiting
> for?

I looked that code over a bit again, and it still looks good to me :-)
The wait on the handle will fire when a process exits (according to the
API). When it does, we post that information to the queue and send
SIGCHLD. And the waitpid function pick off the top of the queue.

(It's not particularly spaghettified if you know your way around those
APIs :-P That's not to say it's impossible there's a bug there, of course)

//Magnus

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [HACKERS] Replay attack of query cancel

Tom Lane wrote:
> Magnus Hagander <magnus@hagander.net> writes:
>> The problem was (third IIRC here :-P) in other clients, such as the JDBC
>> driver (I think that one was checked specifically) which currently only
>> accept the BackendKeyData message during startup. All drivers not based
>> on libpq would have to be checked and potentially updated, but it's
>> sitll a lot easier than DHing or so.
>
> The other problem was getting the new cancel key from the postmaster to
> the backend and thence to the client (hopefully in a timely manner),
> recognizing that (a) we don't want the postmaster touching shared memory
> very much, and certainly not engaging in any locking behavior; (b)
> backends feel free to ignore SIGINT when they're not doing anything.

In EXEC_BACKEND, we already store this in shared memory. If we could
live with doing that for the non-exec case as well, it'd be a lot easier.

And we could then just have the backend update the array when it sends
out a "new key" message.


> Certainly the prospect of a de facto protocol change is the bigger
> problem, but there are nontrivial implementation issues in the server
> too.

Yeah.

> If we were going to make it a de jure protocol change (ie new version
> number) instead of just hoping nobody notices the behavioral difference,
> I'd be inclined to think about widening the cancel key, too. 32 bits
> ain't that much randomness anymore.

That, or rely on something that's not just a simple shared secret
(something like what Andrew Gierth suggested). And AFAICS, his
suggestion allows us to manage without having to update the cancel key
in shared memory at all - but it does require a protocol modification.

//Magnus


--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Re: [GENERAL] different results based solely on existence of index (no, seriously)

On Aug 12, 2008, at 3:53 AM, Willy-Bas Loos wrote:

> reproduced it on:
> "PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC)
> 4.2.3 (Ubuntu 4.2.3-2ubuntu7)"
> 3 rows with index, 2 rows without.
>
> can not reproduce it on:
> - "PostgreSQL 8.1.10 on i486-pc-linux-gnu, compiled by GCC cc (GCC)
> 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)"
> - "PostgreSQL 8.2.6 on i686-pc-mingw32, compiled by GCC gcc.exe
> (GCC) 3.4.2 (mingw-special)"
> - "PostgreSQL 8.2.7 on i486-pc-linux-gnu, compiled by GCC cc (GCC)
> 4.2.3 (Ubuntu 4.2.3-2ubuntu4)"
> they allways return 2 rows.
>
> hth
> WBL

reproduced on:
PostgreSQL 8.3.1 on i386-apple-darwin9.4.0, compiled by GCC i686-apple-
darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465)
3rows with index, 2 rows without

Ries

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] Need help returning record set from a dynamic sql query

>Iam getting just the first record from the recordset
That's because you use SELECT INTO, you should use   FOR rec IN <query> LOOP

Here's sample code from http://www.postgresql.org/docs/8.1/interactive/plpgsql-control-structures.html

CREATE TABLE test (textcol varchar(10), intcol int);
INSERT INTO test VALUES ('a', 1);
INSERT INTO test VALUES ('a', 2);
INSERT INTO test VALUES ('b', 5);
INSERT INTO test VALUES ('b', 6);

CREATE OR REPLACE FUNCTION ReturnNexting(pText Text) RETURNS SETOF test AS $$
DECLARE
rec RECORD;
BEGIN
FOR rec IN SELECT * FROM test WHERE textcol = pText LOOP
RETURN NEXT rec;
END LOOP;
RETURN;
END;
$$
LANGUAGE plpgsql;

SELECT * FROM ReturnNexting('a');


On Tue, Aug 12, 2008 at 12:58 PM, MuraliPD@GMail <murali.pd@gmail.com> wrote:

Hi Sathish,

 

Thanks for your reply.

 

But I have created the type to return the record set from my join query using a stored function.

 

I cannot able to create a table with that details …. Since those details will be already available from different tables.

 

One more thing …. I am clear with your result set using FOR ..LOOP but mine is not a normal query… it was built Dynamic based on my Input Parameters.

 

Please look and tell me if you are not clear with my query.

 

 

Thanks,

MuraliDharan V

 

From: Sathish Duraiswamy [mailto:sathish@leatherlink.net]
Sent: Tuesday, August 12, 2008 4:10 PM
To: MuraliPD@GMail
Cc: pgsql-general@postgresql.org
Subject: Re: [GENERAL] Need help returning record set from a dynamic sql query

 

Dear murali,

We use psql for our ERP software .We found CREATE TYPE is useful in creating new data type similar to creating domain.
For eg
       CREATE TYPE date_condition (
                   condition_id int,
                   from_date  date,
                   to_date    date);                   

Instead , you can CREATE TABLE (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);

You can have result returning a set of records

Feel free to comment on it

Regrds
sathish

On Tue, Aug 12, 2008 at 3:08 PM, MuraliPD@GMail <murali.pd@gmail.com> wrote:

Hi,

Iam new to Postgresql, now i need to create a Dynamic SQL Query for returning the record set
based on my Input Parameters. I looked up some of the documents and worked out some more ...

MY Postgresql Version In Local: 7.4
MY Postgresql Version In Development: 8.2


-- DROP TYPE ORDERREPORT;
CREATE TYPE ORDERREPORT AS (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);


-- DROP FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER);
CREATE OR REPLACE FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER) RETURNS SETOF ORDERREPORT AS
'
DECLARE
vResult ORDERREPORT%ROWTYPE;
vSql TEXT = ''
SELECT
   ORDR.ORDERSID       AS OrderID,
   ORDR.INITIATED       AS Order_Date,
   COMP.COMPANYNAME    AS Company_Name,
   EVNT.EVENTNAME      AS Event_Name
FROM
   ORDERS ORDR
   INNER JOIN COMPANY COMP ON COMP.COMPANYID = ORDR.COMPANY
   INNER JOIN EVENT EVNT ON EVNT.COMPANY = COMP.COMPANYID
WHERE
   ORDR.EVENT = EVNT.EVENTID '';
BEGIN
   IF $1 IS NOT NULL THEN
      vSql = vSql ||'' AND ORDR.ORDERSID = ''|| $1;
   END IF;
        
   IF $2 IS NOT NULL THEN
      vSql = vSql ||'' AND COMP.COMPANYID = ''|| $2;
   END IF;

   IF $3 IS NOT NULL THEN
      vSql = vSql ||'' AND EVNT.EVENTID = ''|| $3;
   END IF;
   EXECUTE vSql INTO vResult;
   RETURN NEXT vResult;
END '
LANGUAGE 'PLPGSQL';

Result:

events=# SELECT * FROM FUN_ORDERREPORT(102881,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)

events=# SELECT * FROM FUN_ORDERREPORT(NULL,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)


Iam getting just the first record from the recordset.
Can someone help me how can i return all query results from a Dynamic SQL Query?


--
Thanks,
MuraliDharan V

 


Re: [GENERAL] different results based solely on existence of index (no, seriously)

On Aug 12, 2008, at 3:53 AM, Willy-Bas Loos wrote:

> reproduced it on:
> "PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC)
> 4.2.3 (Ubuntu 4.2.3-2ubuntu7)"
> 3 rows with index, 2 rows without.
>
> can not reproduce it on:
> - "PostgreSQL 8.1.10 on i486-pc-linux-gnu, compiled by GCC cc (GCC)
> 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)"
> - "PostgreSQL 8.2.6 on i686-pc-mingw32, compiled by GCC gcc.exe
> (GCC) 3.4.2 (mingw-special)"
> - "PostgreSQL 8.2.7 on i486-pc-linux-gnu, compiled by GCC cc (GCC)
> 4.2.3 (Ubuntu 4.2.3-2ubuntu4)"
> they allways return 2 rows.
>
> hth
> WBL

reproduced on:
PostgreSQL 8.3.1 on i386-apple-darwin9.4.0, compiled by GCC i686-apple-
darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465)
3rows with index, 2 rows without

Ries

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[GENERAL] text .vs. varchar

Hello all,

I have a big database in which much information is stored in TEXT type
columns (I did this initially because I did not want to limit the
maximum size of the string to be stored)... but...

.. let's say I choose an upper limit (p.ex. 200) for the string sizes
and I start a fresh database with VARCHAR(200).

What tradeoffs can I expect ? disk usage ? query execution times ?

thx
Joao

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] big database with very small dump !?

Joao Ferreira gmail wrote:
> On Mon, 2008-08-11 at 10:58 -0600, Scott Marlowe wrote:
>
> If I try cluster, I'm guessing I'll choose the big index and forget
> about the smaller ones... is this right ?
>

CLUSTER will sort out all the indexes, even though you're just
clustering on on.


--
Tommy Gildseth
DBA, Gruppe for databasedrift
Universitetet i Oslo, USIT
m: +47 45 86 38 50
t: +47 22 85 29 39

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[pgsql-es-ayuda] Importar archivo XML

Alguien sabe si existe alguna función u orden especifica para importar
archivos XML a Postgres?

Gracias.


Javier Estévez
www.estirpe.net

--
TIP 10: no uses HTML en tu pregunta, seguro que quien responda no podrá leerlo

[pgsql-es-ayuda] Retornar un conjunto de registros (SQL DINAMICO)

Cordial Saludo.
 
Cómo sería la forma más óptima de que un Sp devuelva un conjunto de registros obtenidos de un SQL dinámico??
 
Existe algo así como: "RETURN QUERY EXECUTE"? ... parece que no.
 
Lo que he visto hasta ahora es que me tocaria hacer alfo como esto:
for record in execute 'query'
    return next record
return
 
Pero me parece MUY ineficiente ya que me toca iterar por todos los registros.
 
Cual es la mejor alternativa?
 
Atentamente,
 
RAUL DUQUE
Bogotá, Colombia
 

[pgsql-es-ayuda] Funcion retorna SETOF RECORD

Cordial Saludo.
 
He intentado definir una función que retorne un SETOF RECORD pero aunque compila correctamente, al ejecutarla me lanza el siguiente error:
 

ERROR:  a column definition list is required for functions returning "record"
 
********** Error **********
 
ERROR: a column definition list is required for functions returning "record"
SQL state: 42601
 
Tengo que definir un tipo para retornar un conjunto de registros?
 
Atentamente,
 
RAUL DUQUE
Bogotá, Colombia

Re: [GENERAL] big database with very small dump !?

On Mon, 2008-08-11 at 10:58 -0600, Scott Marlowe wrote:

> It's likely you've got index bloat. If you reload a pg_dump of the
> database in question into another server how much space does that take
> up?

right. just loaded the dump into a clean database and everything came
down about 10 times...
----------------------------------------------
NOW: (injected dump into fresh Pg):
relation | size
----------------------------------+--------
public.timeslots | 549 MB
public.timeslots_strs_var_ts_key | 482 MB
public.timeslots_var_index | 59 MB
public.timeslots_timeslot_index | 37 MB
public.timeslots_timestamp_index | 37 MB
(5 rows)


------------------------------------------------
BEFORE:
relation | size
----------------------------------+---------
public.timeslots_strs_var_ts_key | 5643 MB
public.timeslots | 2660 MB
public.timeslots_timestamp_index | 583 MB
public.timeslots_var_index | 314 MB
public.timeslots_timeslot_index | 275 MB


I'm confused here....

on the fresh database the whole set only takes 1.3G

on the original db, even after VACUUM FULL and REINDEX it takes 9G.

can I really do anything about it ?

If I try cluster, I'm guessing I'll choose the big index and forget
about the smaller ones... is this right ?

thanks
joao


thx


> Look into using CLUSTER or REINDEX to fix the space usage.
>


--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] big database with very small dump !?

In response to Joao Ferreira gmail <joao.miguel.c.ferreira@gmail.com>:
>
> On Mon, 2008-08-11 at 12:43 -0700, Vlad Kosilov wrote:
> > ./data/ you may want to exclude those. I find this query useful for
> > something like this as well:
> >
> > select datname,pg_size_pretty(pg_database_size(oid)) from pg_database ;
> >
>
> Hello Vlad,
>
> I ran your query and I got the 9Gigas!
>
> I guess it should be related to index bloating, then. Do you agree ?

No, the index size is included in pg_database_size().

Perhaps do a du -hd1 /var/pgsql/data to see which directories have all
the space. (or du -h --max-depth=1 /var/pgsql/data on Linux)

--
Bill Moran
Collaborative Fusion Inc.
http://people.collaborativefusion.com/~wmoran/

wmoran@collaborativefusion.com
Phone: 412-422-3463x4023

****************************************************************
IMPORTANT: This message contains confidential information and is
intended only for the individual named. If the reader of this
message is not an intended recipient (or the individual
responsible for the delivery of this message to an intended
recipient), please be advised that any re-use, dissemination,
distribution or copying of this message is prohibited. Please
notify the sender immediately by e-mail if you have received
this e-mail by mistake and delete this e-mail from your system.
E-mail transmission cannot be guaranteed to be secure or
error-free as information could be intercepted, corrupted, lost,
destroyed, arrive late or incomplete, or contain viruses. The
sender therefore does not accept liability for any errors or
omissions in the contents of this message, which arise as a
result of e-mail transmission.
****************************************************************

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] Need help returning record set from a dynamic sql query

Hi Sathish,

 

Thanks for your reply.

 

But I have created the type to return the record set from my join query using a stored function.

 

I cannot able to create a table with that details …. Since those details will be already available from different tables.

 

One more thing …. I am clear with your result set using FOR ..LOOP but mine is not a normal query… it was built Dynamic based on my Input Parameters.

 

Please look and tell me if you are not clear with my query.

 

 

Thanks,

MuraliDharan V

 

From: Sathish Duraiswamy [mailto:sathish@leatherlink.net]
Sent: Tuesday, August 12, 2008 4:10 PM
To: MuraliPD@GMail
Cc: pgsql-general@postgresql.org
Subject: Re: [GENERAL] Need help returning record set from a dynamic sql query

 

Dear murali,

We use psql for our ERP software .We found CREATE TYPE is useful in creating new data type similar to creating domain.
For eg
       CREATE TYPE date_condition (
                   condition_id int,
                   from_date  date,
                   to_date    date);                   

Instead , you can CREATE TABLE (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);

You can have result returning a set of records

Feel free to comment on it

Regrds
sathish

On Tue, Aug 12, 2008 at 3:08 PM, MuraliPD@GMail <murali.pd@gmail.com> wrote:

Hi,

Iam new to Postgresql, now i need to create a Dynamic SQL Query for returning the record set
based on my Input Parameters. I looked up some of the documents and worked out some more ...

MY Postgresql Version In Local: 7.4
MY Postgresql Version In Development: 8.2


-- DROP TYPE ORDERREPORT;
CREATE TYPE ORDERREPORT AS (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);


-- DROP FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER);
CREATE OR REPLACE FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER) RETURNS SETOF ORDERREPORT AS
'
DECLARE
vResult ORDERREPORT%ROWTYPE;
vSql TEXT = ''
SELECT
   ORDR.ORDERSID       AS OrderID,
   ORDR.INITIATED       AS Order_Date,
   COMP.COMPANYNAME    AS Company_Name,
   EVNT.EVENTNAME      AS Event_Name
FROM
   ORDERS ORDR
   INNER JOIN COMPANY COMP ON COMP.COMPANYID = ORDR.COMPANY
   INNER JOIN EVENT EVNT ON EVNT.COMPANY = COMP.COMPANYID
WHERE
   ORDR.EVENT = EVNT.EVENTID '';
BEGIN
   IF $1 IS NOT NULL THEN
      vSql = vSql ||'' AND ORDR.ORDERSID = ''|| $1;
   END IF;
        
   IF $2 IS NOT NULL THEN
      vSql = vSql ||'' AND COMP.COMPANYID = ''|| $2;
   END IF;

   IF $3 IS NOT NULL THEN
      vSql = vSql ||'' AND EVNT.EVENTID = ''|| $3;
   END IF;
   EXECUTE vSql INTO vResult;
   RETURN NEXT vResult;
END '
LANGUAGE 'PLPGSQL';

Result:

events=# SELECT * FROM FUN_ORDERREPORT(102881,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)

events=# SELECT * FROM FUN_ORDERREPORT(NULL,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)


Iam getting just the first record from the recordset.
Can someone help me how can i return all query results from a Dynamic SQL Query?


--
Thanks,
MuraliDharan V

 

Re: [GENERAL] big database with very small dump !?

Joao Ferreira gmail wrote:
> On Mon, 2008-08-11 at 12:45 -0400, Greg Smith wrote:
>> On Mon, 11 Aug 2008, Joao Ferreira gmail wrote:
>>
>>> I'm finding it very strange that my pg takes 9Giga on disk but
>>> pg_dumpall produces a 250Mega dump. 'VACUUM FULL' was executed
>>> yesterday.
>> If you've been running VACUUM FULL, it's probably so-called "index bloat".
>> Try running the query at http://wiki.postgresql.org/wiki/Disk_Usage to
>> figure out where all your space has gone inside the database.
>>
>
>
> egbert=# SELECT nspname || '.' || relname AS "relation",
> egbert-# pg_size_pretty(pg_relation_size(nspname || '.' || relname))
> AS "size"
> egbert-# FROM pg_class C
> egbert-# LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
> egbert-# WHERE nspname NOT IN ('pg_catalog', 'information_schema')
> egbert-# AND nspname !~ '^pg_toast'
> egbert-# AND pg_relation_size(nspname || '.' || relname)>0
> egbert-# ORDER BY pg_relation_size(nspname || '.' || relname) DESC
> egbert-# LIMIT 20;
>
> relation | size
> ----------------------------------+---------
> public.timeslots_strs_var_ts_key | 5643 MB #this is a UNIQUE clause
> public.timeslots | 2660 MB #this is the only table
> public.timeslots_timestamp_index | 583 MB #this is an index
> public.timeslots_var_index | 314 MB #this is an index
> public.timeslots_timeslot_index | 275 MB "this is an index
> (5 rows)
>
>
> so it seems that the UNIQUE clause is taking up more space than the data
> itself...
>
> stil I have 2660 MB of data but the dump is about 10x smaller !!!
>
> any hints ?


I would try running a cluster on the table. This will usually clean up
things and free diskspace both in the table and the indexes.
It does require quite extensive locking though, so might not be an
option if you can't afford having the database unavailable for a few
(10-15) minutes.


--
Tommy Gildseth


--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] Need help returning record set from a dynamic sql query

Dear murali,

We use psql for our ERP software .We found CREATE TYPE is useful in creating new data type similar to creating domain.
For eg
       CREATE TYPE date_condition (
                   condition_id int,
                   from_date  date,
                   to_date    date);                   

Instead , you can CREATE TABLE (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);

You can have result returning a set of records

Feel free to comment on it

Regrds
sathish

On Tue, Aug 12, 2008 at 3:08 PM, MuraliPD@GMail <murali.pd@gmail.com> wrote:
Hi,

Iam new to Postgresql, now i need to create a Dynamic SQL Query for returning the record set
based on my Input Parameters. I looked up some of the documents and worked out some more ...

MY Postgresql Version In Local: 7.4
MY Postgresql Version In Development: 8.2


-- DROP TYPE ORDERREPORT;
CREATE TYPE ORDERREPORT AS (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);


-- DROP FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER);
CREATE OR REPLACE FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER) RETURNS SETOF ORDERREPORT AS
'
DECLARE
vResult ORDERREPORT%ROWTYPE;
vSql TEXT = ''
SELECT
   ORDR.ORDERSID       AS OrderID,
   ORDR.INITIATED       AS Order_Date,
   COMP.COMPANYNAME    AS Company_Name,
   EVNT.EVENTNAME      AS Event_Name
FROM
   ORDERS ORDR
   INNER JOIN COMPANY COMP ON COMP.COMPANYID = ORDR.COMPANY
   INNER JOIN EVENT EVNT ON EVNT.COMPANY = COMP.COMPANYID
WHERE
   ORDR.EVENT = EVNT.EVENTID '';
BEGIN
   IF $1 IS NOT NULL THEN
      vSql = vSql ||'' AND ORDR.ORDERSID = ''|| $1;
   END IF;
        
   IF $2 IS NOT NULL THEN
      vSql = vSql ||'' AND COMP.COMPANYID = ''|| $2;
   END IF;

   IF $3 IS NOT NULL THEN
      vSql = vSql ||'' AND EVNT.EVENTID = ''|| $3;
   END IF;
   EXECUTE vSql INTO vResult;
   RETURN NEXT vResult;
END '
LANGUAGE 'PLPGSQL';

Result:

events=# SELECT * FROM FUN_ORDERREPORT(102881,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)

events=# SELECT * FROM FUN_ORDERREPORT(NULL,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)


Iam getting just the first record from the recordset.
Can someone help me how can i return all query results from a Dynamic SQL Query?


--
Thanks,
MuraliDharan V

Re: [GENERAL] big database with very small dump !?

On Mon, 2008-08-11 at 12:45 -0400, Greg Smith wrote:
> On Mon, 11 Aug 2008, Joao Ferreira gmail wrote:
>
> > I'm finding it very strange that my pg takes 9Giga on disk but
> > pg_dumpall produces a 250Mega dump. 'VACUUM FULL' was executed
> > yesterday.
>
> If you've been running VACUUM FULL, it's probably so-called "index bloat".
> Try running the query at http://wiki.postgresql.org/wiki/Disk_Usage to
> figure out where all your space has gone inside the database.
>


egbert=# SELECT nspname || '.' || relname AS "relation",
egbert-# pg_size_pretty(pg_relation_size(nspname || '.' || relname))
AS "size"
egbert-# FROM pg_class C
egbert-# LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
egbert-# WHERE nspname NOT IN ('pg_catalog', 'information_schema')
egbert-# AND nspname !~ '^pg_toast'
egbert-# AND pg_relation_size(nspname || '.' || relname)>0
egbert-# ORDER BY pg_relation_size(nspname || '.' || relname) DESC
egbert-# LIMIT 20;

relation | size
----------------------------------+---------
public.timeslots_strs_var_ts_key | 5643 MB #this is a UNIQUE clause
public.timeslots | 2660 MB #this is the only table
public.timeslots_timestamp_index | 583 MB #this is an index
public.timeslots_var_index | 314 MB #this is an index
public.timeslots_timeslot_index | 275 MB "this is an index
(5 rows)


so it seems that the UNIQUE clause is taking up more space than the data
itself...

stil I have 2660 MB of data but the dump is about 10x smaller !!!

any hints ?


> --
> * Greg Smith gsmith@gregsmith.com http://www.gregsmith.com Baltimore, MD
>


--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [HACKERS] Proposal of SE-PostgreSQL patches [try#2]

Josh Berkus wrote:
> KaiGai Kohei wrote:
>> On the WiKi of CommitFest:Sep,
>> http://wiki.postgresql.org/wiki/CommitFest:2008-09
>>
>> The entry of SE-PostgreSQL points a message when I submitted older
>> version
>> of our patch set. But the latest ones are listed on another message.
>>
>> Please add a link to the following message for our convenience:
>> http://archives.postgresql.org/pgsql-hackers/2008-07/msg01365.php
>
> Hey, given the amount of work still to go on this, don't you think you
> should get a wiki account so that you can add comments yourself?

Thanks for updating the wiki entry.
If possible, I want to apply my wiki account for a rapid status updating.

--
OSS Platform Development Division, NEC
KaiGai Kohei <kaigai@ak.jp.nec.com>

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Re: [PERFORM] Using PK value as a String

You guys totally rock!

I guess, bottom line, we should take that extra day to convert our PK and FK to a numerical value, using BIG INT to be on the save side. (Even though Wikipedia's UserID uses just an integer as data type)

To Gregory: Thank you for you valuable statement.
"But the real question here is what's the better design. If you use Username you'll be cursing if you ever want to provide a facility to allow people to change their usernames. You may not want such a facility now but one day" I think you hit the nail on the head with this comment. If a member really wants to change their username, IE: Choose to go with IloveUSara, only to be dumped on the alter, who am I to say no.

To Valentin: I wish someone would prove us both wrong or right. I still thought it wasn't a bad idea to use username a varchar(256) to interact with all the modules... Well thats what I thought when I first started writing the tables...

To Jay: Thanks for keeping it short and simple. "I'd like sequence, which is unique and just use 8 bytes(bigint) When it querying other tables, it will faster , and disk space smaller than UUID(40 bytes)." I'm taking your advice on this^^ Although wikipedia's postgresql database schema still stands.

To Craig: Yes, I agree. Please see my comment on IloveUSara.

To Mario: Let's go! I'm Mario... Sorry, I love Mario Kart. Especially on the old super famacon. Going with int8, thank you for the advice.


On Tue, Aug 12, 2008 at 6:58 PM, Mario Weilguni <mweilguni@sime.com> wrote:
Valentin Bogdanov schrieb:

--- On Mon, 11/8/08, Gregory Stark <stark@enterprisedb.com> wrote:

 
From: Gregory Stark <stark@enterprisedb.com>
Subject: Re: [PERFORM] Using PK value as a String
To: "Jay" <arrival123@gmail.com>
Cc: pgsql-performance@postgresql.org
Date: Monday, 11 August, 2008, 10:30 AM
"Jay" <arrival123@gmail.com> writes:

   
I have a table named table_Users:

CREATE TABLE table_Users (
  UserID       character(40)  NOT NULL default
     
'',
   
  Username   varchar(256)  NOT NULL default
     
'',
   
  Email          varchar(256) NOT NULL default
     
''
   
  etc...
);

The UserID is a character(40) and is generated using
     
UUID function. We
   
started making making other tables and ended up not
     
really using
   
UserID, but instead using Username as the unique
     
identifier for the
   
other tables. Now, we pass and insert the Username to
     
for discussions,
   
wikis, etc, for all the modules we have developed. I
     
was wondering if
   
it would be a performance improvement to use the 40
     
Character UserID
   
instead of Username when querying the other tables, or
     
if we should
   
change the UserID to a serial value and use that to
     
query the other
   
tables. Or just keep the way things are because it
     
doesn't really make
   
much a difference.
     
Username would not be any slower than UserID unless you
have a lot of
usernames longer than 40 characters.

However making UserID an integer would be quite a bit more
efficient. It would
take 4 bytes instead of as the length of the Username which
adds up when it's
in all your other tables... Also internationalized text
collations are quite a
bit more expensive than a simple integer comparison.

But the real question here is what's the better design.
If you use Username
you'll be cursing if you ever want to provide a
facility to allow people to
change their usernames. You may not want such a facility
now but one day...

   

I don't understand Gregory's suggestion about the design. I thought using natural primary keys as opposed to surrogate ones is a better design strategy, even when it comes to performance considerations and even more so if there are complex relationships within the database.

Regards,
Valentin

 
UUID is already a surrogate key not a natural key, in no aspect better than a numeric key, just taking a lot more space.

So why not use int4/int8?






--
Regards,
Jay Kang


This e-mail is intended only for the proper person to whom it is addressed and may contain legally privileged and/or confidential information. If you received this communication erroneously, please notify me by reply e-mail, delete this e-mail and all your copies of this e-mail and do not review, disseminate, redistribute, make other use of, rely upon, or copy this communication. Thank you.

Re: [HACKERS] Plugin system like Firefox

Am Tuesday, 12. August 2008 schrieb Bruce Momjian:
> I feel the above comment about Firefox is the crux of the plugin issue.

The difference is that Firefox is an interactive eye-candy system whereas
PostgreSQL is a functionality-based server system. A PostgreSQL database
system needs to have a set up method that is robust, reproducible, and
noninteractive. Easy of use and click & drool is all nice, but overall I
think the requirements profile for a PostgreSQL plugin system is quite
different from Firefox.

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

[DOCS] TODO build rule

I tried building TODO.html from TODO according to the description in
doc/src/FAQ/README, but saw the following kind of difference repeating:

@@ -24,7 +24,7 @@
<h1><a name="section_2">Administration</a></h1>

<ul>
- <li>-<em>Allow administrators to safely terminate individual sessions either</em>
+ <li>-Allow administrators to safely terminate individual sessions either
via an SQL function or SIGTERM
</li><li>Check for unreferenced table files created by transactions that were
in-progress when the server terminated abruptly

Apparently, there is a piece of code missing that adds these <em> tags around
the done items. Bruce, do you have this code, and can you add it to the README?

--
Sent via pgsql-docs mailing list (pgsql-docs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-docs

Re: [PERFORM] Using PK value as a String

Valentin Bogdanov schrieb:
> --- On Mon, 11/8/08, Gregory Stark <stark@enterprisedb.com> wrote:
>
>
>> From: Gregory Stark <stark@enterprisedb.com>
>> Subject: Re: [PERFORM] Using PK value as a String
>> To: "Jay" <arrival123@gmail.com>
>> Cc: pgsql-performance@postgresql.org
>> Date: Monday, 11 August, 2008, 10:30 AM
>> "Jay" <arrival123@gmail.com> writes:
>>
>>
>>> I have a table named table_Users:
>>>
>>> CREATE TABLE table_Users (
>>> UserID character(40) NOT NULL default
>>>
>> '',
>>
>>> Username varchar(256) NOT NULL default
>>>
>> '',
>>
>>> Email varchar(256) NOT NULL default
>>>
>> ''
>>
>>> etc...
>>> );
>>>
>>> The UserID is a character(40) and is generated using
>>>
>> UUID function. We
>>
>>> started making making other tables and ended up not
>>>
>> really using
>>
>>> UserID, but instead using Username as the unique
>>>
>> identifier for the
>>
>>> other tables. Now, we pass and insert the Username to
>>>
>> for discussions,
>>
>>> wikis, etc, for all the modules we have developed. I
>>>
>> was wondering if
>>
>>> it would be a performance improvement to use the 40
>>>
>> Character UserID
>>
>>> instead of Username when querying the other tables, or
>>>
>> if we should
>>
>>> change the UserID to a serial value and use that to
>>>
>> query the other
>>
>>> tables. Or just keep the way things are because it
>>>
>> doesn't really make
>>
>>> much a difference.
>>>
>> Username would not be any slower than UserID unless you
>> have a lot of
>> usernames longer than 40 characters.
>>
>> However making UserID an integer would be quite a bit more
>> efficient. It would
>> take 4 bytes instead of as the length of the Username which
>> adds up when it's
>> in all your other tables... Also internationalized text
>> collations are quite a
>> bit more expensive than a simple integer comparison.
>>
>> But the real question here is what's the better design.
>> If you use Username
>> you'll be cursing if you ever want to provide a
>> facility to allow people to
>> change their usernames. You may not want such a facility
>> now but one day...
>>
>>
>
> I don't understand Gregory's suggestion about the design. I thought using natural primary keys as opposed to surrogate ones is a better design strategy, even when it comes to performance considerations and even more so if there are complex relationships within the database.
>
> Regards,
> Valentin
>
>
UUID is already a surrogate key not a natural key, in no aspect better
than a numeric key, just taking a lot more space.

So why not use int4/int8?


--
Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-performance

[COMMITTERS] pgsql: Remove TODO item Allow XML to accept more liberal DOCTYPE

Log Message:
-----------
Remove TODO item

Allow XML to accept more liberal DOCTYPE specifications

Everything works correctly, per today's email to -general.

Modified Files:
--------------
pgsql/doc:
TODO (r1.2494 -> r1.2495)
(http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/doc/TODO?r1=1.2494&r2=1.2495)
pgsql/doc/src/FAQ:
TODO.html (r1.1000 -> r1.1001)
(http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/doc/src/FAQ/TODO.html?r1=1.1000&r2=1.1001)

--
Sent via pgsql-committers mailing list (pgsql-committers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-committers

Re: [HACKERS] WIP: New Page API

Hi Zdenek,

Zdenek Kotala wrote:
> It is not related to fork maps. The idea is to learn PostgreSQL process
> to read old data page structures. It is part of in-place upgrade and it
> was discussed on PGCon this year. You can see more info on
>
> http://wiki.postgresql.org/wiki/In-place_upgrade
> http://www.pgcon.org/2008/schedule/events/87.en.html

Ah, that's where the idea is coming from. Thanks for the pointers.

Regards

Markus Wanner


--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Re: [GENERAL] PostgreSQL 8.3 XML parser seems not to recognize the DOCTYPE element in XML files

Am Thursday, 7. February 2008 schrieb Lawrence Oluyede:
> PostgreSQL 8.3 instead doesn't allow the insertion of XML with doctype
> in its new native data type returning this error message:
>
> """
> ERROR: invalid XML content
> DETAIL: Entity: line 2: parser error : StartTag: invalid element name
> <!DOCTYPE foo>
> ^

It turns out that this behavior is entirely correct. It depends on the XML
option. If you set the XML option to DOCUMENT, you can parse documents
including DOCTYPE declarations. If you set the XML option to CONTENT, then
what you can parse is defined by the production

XMLDecl? content

which does not allow for a DOCTYPE.

The default XML option is CONTENT, which explains the behavior.

Now, the supercorrect way to parse XML values would be using the XMLPARSE()
function, which requires you to specify the XML option inline. That way,
everything works.

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[GENERAL] Need help returning record set from a dynamic sql query

Hi,

Iam new to Postgresql, now i need to create a Dynamic SQL Query for returning the record set
based on my Input Parameters. I looked up some of the documents and worked out some more ...

MY Postgresql Version In Local: 7.4
MY Postgresql Version In Development: 8.2


-- DROP TYPE ORDERREPORT;
CREATE TYPE ORDERREPORT AS (ORDERSID INTEGER,ORDERDATE TIMESTAMP,COMPANYNAME TEXT,EVENTNAME CHARACTER VARYING);


-- DROP FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER);
CREATE OR REPLACE FUNCTION FUN_ORDERREPORT(IN pmOrderId INTEGER,IN pmCompanyId INTEGER,IN pmEventId INTEGER) RETURNS SETOF ORDERREPORT AS
'
DECLARE
vResult ORDERREPORT%ROWTYPE;
vSql TEXT = ''
SELECT
   ORDR.ORDERSID       AS OrderID,
   ORDR.INITIATED       AS Order_Date,
   COMP.COMPANYNAME    AS Company_Name,
   EVNT.EVENTNAME      AS Event_Name
FROM
   ORDERS ORDR
   INNER JOIN COMPANY COMP ON COMP.COMPANYID = ORDR.COMPANY
   INNER JOIN EVENT EVNT ON EVNT.COMPANY = COMP.COMPANYID
WHERE
   ORDR.EVENT = EVNT.EVENTID '';
BEGIN
   IF $1 IS NOT NULL THEN
      vSql = vSql ||'' AND ORDR.ORDERSID = ''|| $1;
   END IF;
        
   IF $2 IS NOT NULL THEN
      vSql = vSql ||'' AND COMP.COMPANYID = ''|| $2;
   END IF;

   IF $3 IS NOT NULL THEN
      vSql = vSql ||'' AND EVNT.EVENTID = ''|| $3;
   END IF;
   EXECUTE vSql INTO vResult;
   RETURN NEXT vResult;
END '
LANGUAGE 'PLPGSQL';

Result:

events=# SELECT * FROM FUN_ORDERREPORT(102881,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)

events=# SELECT * FROM FUN_ORDERREPORT(NULL,NULL,NULL);
ordersid |         orderdate          | companyname |    eventname
----------+----------------------------+-------------+-----------------
   102881 | 2006-02-10 14:49:53.002653 | PhotoMania  | Photos
(1 row)


Iam getting just the first record from the recordset.
Can someone help me how can i return all query results from a Dynamic SQL Query?


--
Thanks,
MuraliDharan V

Re: [HACKERS] WIP: New Page API

Markus Wanner napsal(a):
> Hi,
>
> Zdenek Kotala wrote:
>> I finished first prototype of new page API.
>
> This might seem obvious to you, but could you please describe the
> problem you are trying to solve with this new page API? How does it
> relate to the relation forks, that have just been committed?
>

Hi Markus,

It is not related to fork maps. The idea is to learn PostgreSQL process to read
old data page structures. It is part of in-place upgrade and it was discussed on
PGCon this year. You can see more info on

http://wiki.postgresql.org/wiki/In-place_upgrade
http://www.pgcon.org/2008/schedule/events/87.en.html

This is prototype of first part. Multi versions tuple processing and tuple size
limits are next part.


Zdenek

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

Re: [GENERAL] big database with very small dump !?

Hello Greg, Vlad, Scott and all,

thanks for the feedback.

O forgot to mention that I execute REINDEX on all tables and INDEXes
every week (right after executing VACUUM FULL).

Is this enough to eliminate the possibility of "index bloat" ?

and, yes, my database has some crazy indexes. I use these indexes, and I
keep them REINDEXed to keep query execution time down. see bellow.

could these indexes be the real reason for taking up all that space ?

thanks
joao

egbert=# \d timeslots;
Table "public.timeslots"
Column | Type | Modifiers
-----------+---------+-----------
str1 | text |
str2 | text |
...
...
str20 | text |
val1 | real |
...
...
val6 | real |
var | text |
count | integer |
total | real |
timeslot | integer | not null
timestamp | integer | not null
tsws | integer | not null
tses | integer | not null
Indexes:
"timeslots_strs_var_ts_key" UNIQUE, btree (str1, str2, str3, str4,
str5, str6, str7, str8, str9, str10, str11, str12, str13, str14, str15,
str16, str17, str18, str19, str20, var, timeslot) CLUSTER
"timeslots_timeslot_index" btree (timeslot)
"timeslots_timestamp_index" btree ("timestamp")
"timeslots_var_index" btree (var)

egbert=#
------------------------------------------------------------


On Mon, 2008-08-11 at 12:45 -0400, Greg Smith wrote:
> On Mon, 11 Aug 2008, Joao Ferreira gmail wrote:
>
> > I'm finding it very strange that my pg takes 9Giga on disk but
> > pg_dumpall produces a 250Mega dump. 'VACUUM FULL' was executed
> > yesterday.
>
> If you've been running VACUUM FULL, it's probably so-called "index bloat".
> Try running the query at http://wiki.postgresql.org/wiki/Disk_Usage to
> figure out where all your space has gone inside the database.
>
> --
> * Greg Smith gsmith@gregsmith.com http://www.gregsmith.com Baltimore, M


--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] big database with very small dump !?

On Mon, 2008-08-11 at 12:43 -0700, Vlad Kosilov wrote:
> ./data/ you may want to exclude those. I find this query useful for
> something like this as well:
>
> select datname,pg_size_pretty(pg_database_size(oid)) from pg_database ;
>

Hello Vlad,

I ran your query and I got the 9Gigas!

I guess it should be related to index bloating, then. Do you agree ?

thx
Joao

postgres=# select datname,pg_size_pretty(pg_database_size(oid)) from
pg_database;
datname | pg_size_pretty
---------------+----------------
postgres | 3617 kB
egbert | 9585 MB
asterisk | 3993 kB
turba | 3673 kB
edgereporting | 3617 kB
template1 | 3617 kB
template0 | 3537 kB
(7 rows)

postgres=#


> V.
>
> Joao Ferreira gmail wrote:
> > Hello all,
> >
> > I'm finding it very strange that my pg takes 9Giga on disk but
> > pg_dumpall produces a 250Mega dump. 'VACUUM FULL' was executed
> > yesterday.
> >
> > Is this normal ? Should I be worried ?
> >
> >
> > details bellow:
> > ------------------------------------------
> > # pg_dumpall --oids --clean > pg_dumpall.sql
> > # ls -lh
> > total 232M
> > -rw-r--r-- 1 postgres postgres 231M Aug 11 15:46
> > pg_dumpall.sql
> > # du -sh /var/pgsql/data/
> > 9.4G /var/pgsql/data
> > ------------------------------------------
> >
> >
> > thx
> > joao
> >
> >
> >
> >
> >
>


--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

[HACKERS] psql bug -- using old variables and database connection

We're currently printing the warning about connecting to the wrong version of
the server *before* syncing variables. On reconnecting this results in using
the *old* server version before reconnecting. I'm not sure what happens for
the initial connection but it can't be good. connection_warnings also uses
pset.db which isn't set until a few lines later too which can't be good.

e.g.

postgres=# \c
psql (8.4devel)
You are now connected to database "postgres".
postgres=# select version();
version
-----------------------------------------------------------------------------------------
PostgreSQL 8.2.5 on i686-pc-linux-gnu, compiled by GCC gcc (GCC) 4.2.1 (Debian 4.2.1-5)
(1 row)

postgres=# \c
psql (8.4devel, server 8.2.5)
WARNING: psql version 8.4, server version 8.2.
Some psql features might not work.
You are now connected to database "postgres".


--- command.c 30 Jul 2008 21:57:07 +0100 1.192
+++ command.c 12 Aug 2008 10:05:52 +0100
@@ -1197,10 +1197,10 @@
* Replace the old connection with the new one, and update
* connection-dependent variables.
*/
- connection_warnings();
PQsetNoticeProcessor(n_conn, NoticeProcessor, NULL);
pset.db = n_conn;
SyncVariables();
+ connection_warnings(); /* Must be after SyncVariables */

/* Tell the user about the new connection */
if (!pset.quiet)


--
Gregory Stark
EnterpriseDB http://www.enterprisedb.com
Get trained by Bruce Momjian - ask me about EnterpriseDB's PostgreSQL training!

--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackers

[pgadmin-hackers] SVN Commit by dpage: r7400 - trunk/pgadmin3/pgadmin

Author: dpage

Date: 2008-08-12 10:09:34 +0100 (Tue, 12 Aug 2008)

New Revision: 7400

Revision summary: http://svn.pgadmin.org/cgi-bin/viewcvs.cgi/?rev=7400&view=rev

Log:
Add FTS code to VC++ project files.


Modified:
trunk/pgadmin3/pgadmin/pgAdmin3.vcproj

--
Sent via pgadmin-hackers mailing list (pgadmin-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgadmin-hackers

[GENERAL] test message --> Is this post getting to the list?

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] Can I search for text in a function?

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Try:

select * from pg_proc where lower(prosrc) like '%previous_charge%';

Sim

Rob Richardson wrote:
> Greetings!
>
> Sometimes I need to track down how something happens in the database our
> application relies on, but whatever's happening may be buried in some
> old function that everybody here has forgotten about long ago. IIRC,
> functions are stored internally merely as fields in a table owned by the
> system. Is there a query I can use to find what function contains the
> string "previous_charge"?
>
> Thank you very much.
>
> *Robert D. Richardson
> *Product Engineer Software
> *
> <file:///t:/Sales/Images/Marketing%20Pictures/Logos/LOGOs%20from%2010th%20Floor/RAD-CON%20Logo%20for%20Signature.jpg>
> **RAD-CON, Inc.
> **TECHNOLOGY: */Innovative & Proven
> /Phone : +1.216.706.8905
> Fax: +1.216.221.1135
> Website: www.RAD-CON.com <http://www.rad-con.com/>
> E-mail: rob.richardson@RAD-CON.com
>
>

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iEYEARECAAYFAkihT50ACgkQjDX6szCBa+pQ8ACbBTLLep4RoyBNTC+PGij7TO2F
Z4AAnA/UKoxyzzJYyK+6nePYp7S3AUN9
=2ntc
-----END PGP SIGNATURE-----

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

Re: [GENERAL] different results based solely on existence of index (no, seriously)

reproduced it on:
"PostgreSQL 8.3.3 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu7)"
3 rows with index, 2 rows without.

can not reproduce it on:
- "PostgreSQL 8.1.10 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.1.3 20070831 (prerelease) (Ubuntu 4.1.2-16ubuntu1)"
- "PostgreSQL 8.2.6 on i686-pc-mingw32, compiled by GCC gcc.exe (GCC) 3.4.2 (mingw-special)"
- "PostgreSQL 8.2.7 on i486-pc-linux-gnu, compiled by GCC cc (GCC) 4.2.3 (Ubuntu 4.2.3-2ubuntu4)"
they allways return 2 rows.

hth
WBL

Re: [GENERAL] Checkpoints writes

Greg Smith wrote:
> On Thu, 7 Aug 2008, Cyril SCETBON wrote:
>
>> What's the way to count the read/write bytes of the checkpoint
>> process before 8.3 (no pg_stat_bgwriter view :-[ ) I want to
>> distinguish bytes written by checkpoints and others written by the
>> background process
>
> The reason that view was added was because it's really hard to figure
> that out in earlier versions. Theoretically you could have some
> operating system level program that tracked I/O on a per-process
> basis, noting which one was the background writer process and counting
> those separately. I found it easier to work on adding the counters
> instead.
>
> It's not really complete, but I did have a functional prototype of a
> pg_stat_bgwriter implementation that worked against 8.2 if that helps
> you any: http://www.westnet.com/~gsmith/content/postgresql/perfmon82.htm
a really great job greg. I'll test it.

Thanks
>
> --
> * Greg Smith gsmith@gregsmith.com http://www.gregsmith.com Baltimore, MD
>

--
Cyril SCETBON

--
Sent via pgsql-general mailing list (pgsql-general@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general