Sunday, June 8, 2008

Re: [pgsql-es-ayuda] Procedure para actualizar secuencias

--------------------------------------------------
From: "Marcos Saldivar" <baron.rojo.cuerdas.de.acero@gmail.com>
Sent: Sunday, June 08, 2008 4:23 PM
To: "Raúl Andrés Duque Murillo" <ra_duque@yahoo.com.mx>
Cc: <pgsql-es-ayuda@postgresql.org>
Subject: Re: [pgsql-es-ayuda] Procedure para actualizar secuencias

> El día 8 de junio de 2008 1:41, Raúl Andrés Duque Murillo
> <ra_duque@yahoo.com.mx> escribió:
>> Cordial Saludo.
>>
>> Estoy pensando en hacer un procedure que actualice TODAS las secuencias a
>> los max(id_table) de las tablas correspondientes (para evitarme hacer
>> setvals de cada secuencia), lógicamente este procedimiento sólo lo
>
> pero no se supone esto siempre es así, a menos que asignes al campo un
> valor arbitrario y no un default ???
>

Exactamente ... cuando se hace el precargue se le asigna un valor y no se
usa el default, por lo que no se actualiza la secuencia. Esto es especifico
de la forma como realizó el precargue.ñ

Otra situación es que hago una serie de deletes y me debo quedar con el
max(id_table) de los que queden, yo sé que no es extrictamente necesario
pero es más por control y si puedo abarcar todas las situaciones con la
ejecucción de un Sp, mucho mejor.

Atentamente,

RAUL DUQUE
Bogotá, Colombia


>> utilizaría en el momento de inicializar la DB para una nueva instalación
>> ya
>> que algunas tablas tienen algunos datos "quemados" y estando fuera de
>> producción. Cómo creo que es una necesidad que pudieron tener algunos
>> compañeros en el pasado, de pronto ya alguien hizo este procedure y
>> quisiera
>> compartirlo.
>>
>> Agradezco su colaboración.
>>
>> Atentamente,
>>
>> RAUL DUQUE
>> Bogotá, Colombiaq
>
> __________ Information from ESET Smart Security, version of virus
> signature database 3165 (20080606) __________
>
> The message was checked by ESET Smart Security.
>
> http://www.eset.com
>
>
--
TIP 9: visita nuestro canal de IRC #postgresql-es en irc.freenode.net

Saturday, June 7, 2008

Re: [GENERAL] temporarily deactivate an index

On Sat, Jun 7, 2008 at 5:16 PM, Viktor Rosenfeld
<rosenfel@informatik.hu-berlin.de> wrote:
> Hi Scott,
>
> Am 07.06.2008 um 16:53 schrieb Scott Marlowe:
>>>
>>> I'm experimenting with different indexes to speed up my queries and I was
>>> wondering if it is possible to temporarily deactivate an index, so it
>>> won't
>>> be considered in the evaluation of query plans. The reason is that
>>> dropping
>>> and then rebuilding an index takes up time which I would rather not wait.
>>>
>>> I couldn't find a command to do that, but I'm guessing that it should be
>>> possible by manipulating a structure in the catalog?
>>
>> Try this:
>>
>> begin;
>> drop indexname;
>> explain analyze select ...;
>> rollback;
>
> That works, but I'm still looking for another way to deactivate the index.
> The reason being, that my query load is randomly generated by a Java
> program and I don't want to go and change the SQL compiler.

Sorry, I'm out of ideas. I mean, you can turn off all indexes with
set enable_indexscan=off but there's no other way to do it cheaply and
in such a fine grained way.

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

Re: [PERFORM] Optimizing AGE()

On Fri, Jun 6, 2008 at 7:20 AM, Volkan YAZICI <yazicivo@ttmail.com> wrote:
> Hi,
>
> Am I wrong or AGE() always gets directed to a sequential scan?
>
> # BEGIN;
> ] SET enable_seqscan TO off;
> ] EXPLAIN ANALYZE
> ] SELECT count(1)
> ] FROM incomingmessageslog
> ] WHERE AGE(time) < '1 year';
> ] ROLLBACK;
> BEGIN
> SET
> QUERY PLAN
> ----------------------------------------------------------------------------------------------------------------------------------------
> Aggregate (cost=100000528.33..100000528.34 rows=1 width=0) (actual time=13.789..13.790 rows=1 loops=1)
> -> Seq Scan on incomingmessageslog (cost=100000000.00..100000520.00 rows=3333 width=0) (actual time=13.783..13.783 rows=0 loops=1)
> Filter: (age((('now'::text)::date)::timestamp without time zone, "time") < '1 year'::interval)
> Total runtime: 13.852 ms
> (4 rows)
>
> ROLLBACK
>
> As far as I know, AGE() can take advantage of a very simple equation for
> constant comparisons:
>
> = AGE(field) < constant_criteria
> = AGE(field, constant_ts) < constant_criteria
> = AGE(field) < constant_criteria + constant_ts
> = AGE(field) < CONSTANT_CRITERIA
>
> How much does such a hack into optimizer cost? I don't know about its
> implications but I'll really appreciate such a functionality. At the
> moment, I'm trying replace every AGE() usage in my code and it really
> feels a PITA.

Yeah, age() isn't real performent in such situations. I generally
stick to simpler date math like:

where timestampvalue < now() - interval '2 year'

which can use an index on timestampvalue

The problem with age is it's always compared to now, so there's always
gonna be some math.

--
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] Comportamiento work_mem (windows)

Cordial Saludo.
 
Tengo una instalación de postgresql 8.3.1 sobre windows que se va a utilizar básicamente para Análisis de datos (OLAP) por lo tanto quiero optimizarla para este fin.
 
El procedimiento que he seguido es el siguiente:
 
1. Activé el "log_temp_files = 0" para monitorear el uso de archivos temporales. (excelente adición en la 8.3)
2. Mi supuesto es que una DB que este sirviendo para OLAP/DATAWAREHOUSE debe tener un valor de work_mem grande, pocos usuarios y un valor shared_buffers intermedio.
3. Arranque con work_mem = 1MB (valor por defecto), shared_buffers = 128MB y max_conections = 5. Tengo 2GB de memoria.
4. Realizo una consulta que en múltiples ejecuciones demora 27s. (es una consulta con múltiples joins y un order by, típica en OLAP)
5. Reviso el log e identifico que se utilizan VARIOS archivos temporales de cerca de 1.5MB (utilizados para joins) y al final un archivo de 35MB (para el order by).
6. Subo el work_mem = 5MB
7. Ejecuto de nuevo la consulta, y efectivamente se ha eliminado el uso de los archivos temporales de aprox. 1.5MB, pero sigue usándose el de 35MB. Vamos bien !!!
8. Subo el work_mem = 50MB
9. Ejecuto la consulta MULTIPLES VECES y SIGUE utilizándose el archivo temporal de 35MB pero creció el tiempo en 2s !!!
10. Sé que los 35MB se utilizan para el order by por que si lo quito ya no se usa ese archivo temporal.
11. Vuelvo a work_mem = 5MB y vuelvo a optener los valores de 2s por debajo.
 
Cual podría ser la razón de este comportamiento?
Estoy SEGURO que durante la consulta NO se esta utilizando memoria en disco por parte del SO, que sería una posible explicación de la lentitud.
 
Agradezco su colaboración.
 
Atentamente,
 
RAUL DUQUE
Bogotá, Colombia
 
 

[pgsql-es-ayuda] Procedure para actualizar secuencias

Cordial Saludo.
 
Estoy pensando en hacer un procedure que actualice TODAS las secuencias a los max(id_table) de las tablas correspondientes (para evitarme hacer setvals de cada secuencia), lógicamente este procedimiento sólo lo utilizaría en el momento de inicializar la DB para una nueva instalación ya que algunas tablas tienen algunos datos "quemados" y estando fuera de producción. Cómo creo que es una necesidad que pudieron tener algunos compañeros en el pasado, de pronto ya alguien hizo este procedure y quisiera compartirlo.
 
Agradezco su colaboración.
 
Atentamente,
 
RAUL DUQUE
Bogotá, Colombiaq 

Re: [HACKERS] TODO, FAQs to Wiki?

Actually, now that I try it, it seems that the MediaWiki markup is not
completely helpful here -- right now, on some items we have a one-line
"header" and then possibly a longer description, and it seems the only
way to do that in MediaWiki is like this:

* Set proper permissions on non-system schemas during db creation<br> Currently all schemas are owned by the super-user because they are copied from the template1 database. However, since all objects are inherited from the template database, it is not clear that setting schemas to the db owner is correct.

Note the dumb <br> thing in the middle.

Personally I find that ugly enough as to be unacceptable; what do others
think?

--
Alvaro Herrera

http://www.CommandPrompt.com/
PostgreSQL Replication, Consulting, Custom Development, 24x7 support

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

Re: [PATCHES] [HACKERS] TRUNCATE TABLE with IDENTITY

Tom Lane wrote:

> 2. I had first dismissed Neil's idea of transactional sequence updates
> as impossible, but on second look it could be done. Suppose RESTART
> IDENTITY does this for each sequence;
>
> * obtain AccessExclusiveLock;
> * assign a new relfilenode;
> * insert a sequence row with all parameters copied except
> last_value copies start_value;
> * hold AccessExclusiveLock till commit.

Hmm, this kills the idea of moving sequence data to a single
non-transactional catalog :-(

> So what I think we should do is leave the patch there, revise the
> warning per Neil's complaint, and add a TODO item to reimplement RESTART
> IDENTITY transactionally.

I think the TODO item did not make it, but the docs do seem updated.

--
Alvaro Herrera

http://www.CommandPrompt.com/
PostgreSQL Replication, Consulting, Custom Development, 24x7 support

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

Re: [pgsql-es-ayuda] Instalacion 8.3 y 8.2 en Windows XP

2008/6/7 Terry Yapt <yapt@technovell.com>:
> Hola a todos,
>
> he instalado 8.3 en win32 para un proyecto que tengo que realizar. Para
> ello, utilizo PostgresDAC (de MicroOlap), pero creo que, todavia, existe
> algún problema con la versión 8.3.1. Así que les he reportado el problema y
> voy a intentar, mientras lo solucionan, seguir preparando todo con la
> versión 8.2.7.
>
> El caso es que, en el mismo sistema donde estaba instalada la versión 8.3.1,
> intento instalar la versión 8.2.7 y nada. Cuando el servicio (win32) se va
> a iniciar, arroja un error de que el usuario no tiene permisos para iniciar
> servicios. Esto es falso, pues el usuario tiene esos permisos (los pone el
> instalador, PgInstaller, pero los he comprobado yo manualmente).
> Si intentas arrancar el servicio manualmente, entonces arroja un error 1068
> (de microsoft). El caso es que no puedo instalar postgreSQL en esta
> máquina.
>

podrias mostrar el error que registra el eventlog? si se esta grabando
algo en el log de postgres podriamos verlo tambien?

--
Atentamente,
Jaime Casanova
Soporte y capacitación de PostgreSQL
Guayaquil - Ecuador
Cel. (593) 87171157
--
TIP 4: No hagas 'kill -9' a postmaster

Re: [HACKERS] math error or rounding problem Money type

Justin wrote:
> yes. The question is why are the to sides not equal anymore
>
> Take this
>
> Select
> '2',
> round(sum( beginBalance ),6) as beginbalance,
> round(sum( negative ),6) as debit,
> round(sum( positive ),6) as credit,
> round(sum( difference ),6) as difference,
> round(sum( endbalance),6) as endbalance
> from trailbalance
> union
> Select
> '1',
> sum( round(beginBalance,6)) as beginbalance,
> sum( round(negative,6)) as debit,
> sum( round(positive,6)) as credit,
> sum( round(difference,6)) as difference,
> sum( round(endbalance,6)) as endbalance
> from trailbalance
>
> "1" -0.000006 -11250546.743752 11250546.743752 0.000000
> -0.000007
> "2" 0.000000 -11250546.743752 11250546.743752 0.000000
> 0.000000
>
> At the very least this show a clear warning when rounding do it after
> all the sum function is called not before.
>

IFAIK (dimly recalling numerical analysis courses at university) SUM and
ROUND can *never* be commuted. In general the recommended approach is to
round as late as possible and as few times are possible - so your 1st
query is the correct or best way to go.

Cheers

Mark

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

RE: [pgsql-es-ayuda] llamar a funcion

UIhmmm, tendriamos que entrar en la discusion de que si una estructura compuesta es UNO o VARIOS.
Eso me recuerda una vieja discusion de struct en C y records en Pascal.
Donde el struct lo podia enviar en un return y todo bien , en C mientras en Pasacal no podia enviar el record.
Cual seria el valor correcto?

*-------------------------------------------------------*
*-Edwin Quijada
*-Developer DataBase
*-JQ Microsistemas
*-809-849-8087

* " Si deseas lograr cosas excepcionales debes de hacer cosas fuera de lo comun"
*-------------------------------------------------------*


> Date: Sat, 7 Jun 2008 12:34:38 -0500
> From: systemguards@gmail.com
> To: listas_quijada@hotmail.com
> Subject: Re: [pgsql-es-ayuda] llamar a funcion
> CC: gergonvel@hotmail.com; luis.a.guevara@gmail.com; pgsql-es-ayuda@postgresql.org
>
> 2008/6/7 Edwin Quijada :
>>
>> Las funciones no retornan mas de un valor.
>>
>
> imagino que esto es relativo...
> Pero en la practica las funciones SI retornan mas de un valor, a
> traves de records
>
>
> --
> Atentamente,
> Jaime Casanova
> Soporte y capacitación de PostgreSQL
> Guayaquil - Ecuador
> Cel. (593) 87171157

_________________________________________________________________
Do more with your photos with Windows Live Photo Gallery.
http://www.windowslive.com/share.html?ocid=TXT_TAGLM_Wave2_photos_022008--
TIP 10: no uses HTML en tu pregunta, seguro que quien responda no podrá leerlo

Re: [GENERAL] temporarily deactivate an index

Hi Scott,

Am 07.06.2008 um 16:53 schrieb Scott Marlowe:
>> I'm experimenting with different indexes to speed up my queries and
>> I was
>> wondering if it is possible to temporarily deactivate an index, so
>> it won't
>> be considered in the evaluation of query plans. The reason is that
>> dropping
>> and then rebuilding an index takes up time which I would rather not
>> wait.
>>
>> I couldn't find a command to do that, but I'm guessing that it
>> should be
>> possible by manipulating a structure in the catalog?
>
> Try this:
>
> begin;
> drop indexname;
> explain analyze select ...;
> rollback;

That works, but I'm still looking for another way to deactivate the
index. The reason being, that my query load is randomly generated by
a Java program and I don't want to go and change the SQL compiler.

Cheers,
Viktor

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

[GENERAL] fitler database list

Is it a way to filter the database list on the tables containt in the
database ?

Thanks.

--
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] IN vs EXISTS

> -----Original Message-----
>
> Hi all,
>
> I have been using IN clause almost exclusively until recently I tried
> to use EXISTS and gained significant performance increase without
> changing/creating any indexes:
>
> SELECT ... FROM a WHERE a.ref IN (SELECT b.id WHERE ...)
>
> vs
>
> SELECT ... FROM a WHERE EXISTS (SELECT 1 FROM b WHERE a.ref=b.id ...)
>
> Performance is at least few times better when EXISTS is used. Is it
> just PostgreSQL specific?
>

IN should produce a different query plan than EXISTS. (You can run
"explain analyze" on your queries, to see the different plans).
Which one is faster depends on your data, and on your server. Also,
what's faster on one dbms my be different than another. I've found
that postgresql is usually slower than other databases for IN ()
queries, but handles EXISTS and inner joins (a third way of writing
your queries above) quite quickly.

SELECT a.foo
FROM a
INNER JOIN b on a.ref=b.id

--
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] hopefully a brain teaser, can't quite figure out query

> -----Original Message-----
> The small table is a listing of county fips codes, their name, and the
> geometry for the county. Each fips is only listed once. The big table
> is multiple emissions for each county, the parameter for the emission,
> and the source code for the emission (scc). Each county in big tbale
> has many entries, variable number of pollutant types, variable number
> of scc's.
>
>
> SELECT small.fips, small.name, sum(big.value)
> FROM small, big
> WHERE
> small.fips in (
> SELECT fips from big
> WHERE ((pollutant='co') AND
> (
> (scc LIKE '21%') OR (scc LIKE '2301%') OR (scc LIKE '2801000000%')
> )
> HAVING SUM(value > 2000)
> )
> GROUP BY small.fips, small.name;
>
> This is the query that isn't returning yet.
> If anyone has any questions, comments, or any suggestions at all, I'll
> do my best to respond ASAP.

This sounds like what you want:

SELECT small.fips, small.name, sum(big.value) as big_sum
FROM small
INNER JOIN big on small.fips = big.fips
WHERE pollutant = 'co'
AND (scc LIKE '21%' OR scc LIKE '2301%' OR scc LIKE '2801000000%')
GROUP BY small.fips, small.name

However, I'm not sure I understand this part:

> I would return the 123 fips ONLY if the value provided was less
> than the sum of the values for all scc's (500+550+1500+50 = 2600),
> as well as the sum for those values.

Can you clarify?

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

Re: [pgsql-www] Ask for Help on Improving the FreeBSD FAQ

Gabor PALI wrote:
> - whether you do have any project-specific modifications for DocBook
> - what other tools you do use for creating documentation

Most of our documentation building technology was actually inspired and/or
copied from the FreeBSD project. So I think chances are low you will find
anything here that you don't already have. The integration with the web site
and so on are different, but other people have already commented on that.

I suggest you take a look at the code (Makefile and so on) in doc/src/sgml.

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

Re: [GENERAL] Extracting data from deprecated MONEY fields

Hi,

Tino Wildenhain wrote:
> Hi,
>
> Shane Ambler wrote:
> ...
>> I think the steps Joshua is referring to are -
>>
>> 1. pg_dump -t mytable_with_money mydb > mytable_backup.sql
>> 2. edit table definition in backup file to use numeric
>> 3. remove $ and , from money column data
>> 4. DROP TABLE mytable_with_money
>> 5. psql < mytable_backup.sql
>>
>> While the data is in a text file regex tasks to remove the money
>> formatting become a lot simpler.
>
> to_char() and back to numeric shouldn't be a problem within the database
> and we have regex too if anything fails. I don't think you need to
> dump and edit the dump to achive that.

Ah sorry forget that... neither to_char nor cast to text works. Really a
horrible datatype :(

Tino

Re: [GENERAL] FW: make rows unique across db's without UUIP on windows?

Bill, thanks, that made me think a while.

But doesn't that just push the problem up the chain a notch?

Adding a table id makes the row unique in the database but not beyond.

Then you add a database id to the table/row id and you are unique across
databases?

But can you be universally unique without being universal?

I thought I needed to have an id that would mark any column that comes from
that row with its unique origin row.

With a GUID I'm pretty much home.

But no series of semi-unique keys will ever become as unique as a GUID, will
it? That is, until you add a service id to the database id and a server id
to the service id and a rack id to the server id and a floor id to the rack
id and a bldg id to the floor id and so forth up the chain until you get 64
values in your multi-valued index. And then also make sure none of the
combinations of 64 values repeats anywhere in your global enterprise.

At that point everyone using a system that doesn't have a GUID type changes
the subject and asks, 'you sure you need that?'

But I don't have to need it so much if I've got it. All I have to need it is
a little and I can use it. Then if I need it more later, I've already got
it.

It's only when I don't have it that people say, 'you sure you need it?'

Know what I mean?

Thanks,

Kimball

-----Original Message-----
From: Bill Moran [mailto:wmoran@collaborativefusion.com]
Sent: Tuesday, June 03, 2008 5:57 AM
To: kjohnson@voiceandnetworksystems.com
Cc: pgsql-general@postgresql.org
Subject: Re: [GENERAL] FW: make rows unique across db's without UUIP on
windows?

In response to "Kimball Johnson" <kjohnson@voiceandnetworksystems.com>:
>
> What is the normal solution in pgsql-land for making a serious number of
> rows unique across multiple databases?
>
>
>
> I mean particularly databases of different types (every type) used at
> various places (everywhere) on all platforms (even MS[TM])? You know. a
> UNIVERSAL id?

Just give each separate system it's own unique identifier and a sequence
to append to it.

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

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


--
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] Extracting data from deprecated MONEY fields

Hi,

Shane Ambler wrote:
...
> I think the steps Joshua is referring to are -
>
> 1. pg_dump -t mytable_with_money mydb > mytable_backup.sql
> 2. edit table definition in backup file to use numeric
> 3. remove $ and , from money column data
> 4. DROP TABLE mytable_with_money
> 5. psql < mytable_backup.sql
>
> While the data is in a text file regex tasks to remove the money
> formatting become a lot simpler.

to_char() and back to numeric shouldn't be a problem within the database
and we have regex too if anything fails. I don't think you need to
dump and edit the dump to achive that.

Regards
Tino

[BUGS] BUG #4229: Page header error

The following bug has been logged online:

Bug reference: 4229
Logged by: Valeriy
Email address: tester080606@rambler.ru
PostgreSQL version: 7.4.5
Operating system: Linux 2.6.17
Description: Page header error
Details:

We have PostgreSQL v. 7.4.5 and main application
working with PGSQL via libpq. Linux 2.6.17.

Page header error periodically occurs when
main application is working hard.
We repair it automatically using restore
from night dump, no problems.

There are some servers (among more than 20)
that are loaded much less, so this error doesn't occur at all.

Can we assume that this error is connected with
high load of hardware only?

I suppose that the upgrade up to version 8.x
will not exclude this error.

Thank You
Valeriy

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

[BUGS] Page header error in 8.x ?

We have PostgreSQL v. 7.4.5 and main application working with PGSQL via libpq.
 
Page header error periodically occurs when main application is working hard.
We repair it automatically using restore from night dump, no problems.
 
There are some servers (among more than 20)
that are loaded much less, so this error doesn't occur at all.
 
Can we assume that this error is connected with high load of hardware only?
I suppose that  the upgrade up to version 8.x will not exclude this error.
 
Thank You
Valeriy

Re: [GENERAL] strpos NOT doing what I'd expect

On Jun 7, 2008, at 2:58 AM, Ralph Smith wrote:

> CODE:
> ===============================
> CREATE OR REPLACE FUNCTION find_next_delim(invar varchar, delimlist
> varchar) RETURNS integer AS
> $$
>
> /* OVERLOADED Function. The other version takes a 3rd parameter
> as the
> starting position in invar.
> */
>
> DECLARE
>
> achar character := '' ;

It's because you're using character here instead of text. Character
collapses whitespace (it's usually used as char(<some length>). To
demonstrate:

development=> select ''''||CAST (' '::character AS text)||'''';
?column?
----------
''

So your comparison becomes:
development=> SELECT strpos('3', '');
strpos
--------
1

Now that's got to be a corner case of the use of strpos, I'm not
entirely sure that'd be the right behaviour, but if it isn't, what
would be? Does a non-empty string contain empty strings? And if so,
is it at position 1? The character at position 1 is actually '3'
after all... Maybe it should return NULL (unknown) or raise an error?

When using text instead of character, your function works as expected.

> j int := 0 ;
>
> BEGIN
>
> IF length(delimlist) = 0 THEN
> RAISE NOTICE 'In function \'find_next_delim\' the delimiter
> cannot be null.' ;

An empty string is not null. If someone would actually enter NULL for
delimlist your function would break:

development=> select find_next_delim(NULL,'3') ;
ERROR: upper bound of FOR loop cannot be NULL
CONTEXT: PL/pgSQL function "find_next_delim" line 18 at FOR with
integer loop variable


> END IF ;
>
>
> FOR i IN 1 .. length(invar)
> LOOP
>
> j := j + 1 ;
> achar := substring(invar from i for 1 ) ;
> RAISE NOTICE 'achar is R%S',achar ;
> IF strpos(delimlist,achar) <> 0 THEN
> RETURN j ;
> END IF ;
>
> END LOOP ;
>
> RETURN 0 ;
>
> END ;
> $$ LANGUAGE plpgsql ; /* find_next_delim */
>
>
>
>
> WHAT'S HAPPENING:
> ===============================
> airburst=# select find_next_delim('ralph smith','3') ;
>
> NOTICE: achar is RrS
> NOTICE: achar is RaS
> NOTICE: achar is RlS
> NOTICE: achar is RpS
> NOTICE: achar is RhS
> NOTICE: achar is R S
> find_next_delim
> -----------------
> 6
> (1 row)
>
>
> airburst=# select find_next_delim('ralph smith','') ; -- for the
> heck of it, that's a null
>
> NOTICE: In function 'find_next_delim' the delimiter cannot be null.
> NOTICE: achar is RrS
> NOTICE: achar is RaS
> NOTICE: achar is RlS
> NOTICE: achar is RpS
> NOTICE: achar is RhS
> NOTICE: achar is R S
> find_next_delim
> -----------------
> 6
> (1 row)
>
> WHY find a match on the space???
>
> Thanks!
>
>

Alban Hertroys

--
If you can't see the forest for the trees,
cut the trees and you'll see there is no forest.


!DSPAM:737,484a5f1e927662100280104!

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

Re: [pgadmin-support] pgAdmin 1.8.x hangs while tries to load XRC resources

On Sat, Jun 7, 2008 at 10:32 AM, Antonello Biancalana
<promindsd@gmail.com> wrote:
> Dave Page wrote:
>>
>> On Sat, Jun 7, 2008 at 9:35 AM, Antonello Biancalana
>> <promindsd@gmail.com> wrote:
>> Not offhand. Does the wxWidgets XRC sample work?
>
> Thank you for your reply and your help. Your suggestion was of terrific help
> to me. I compiled and run the wxWidgets XRC sample and it worked but it
> complained about some missing files (whereas pgadmin did not).
> The XRC sample complained about the following missing files in my system:
>
> usr/share/mimelnk/application/vnd.adobe.pdx.desktop
> usr/share/mimelnk/application/vnd.adobe.xdp+xml.desktop
> usr/share/mimelnk/application/vnd.adobe.xfdf.desktop
> usr/share/mimelnk/application/vnd.fdf.desktop
>
> which actually resulted to be missing links belonging to an old installation
> of Adobe Acrobat Reader 7. I deleted these missing links and now pgAdmin
> works.
> I hope this can help other pgAdmin users. Maybe it would be nice if pgAdmin
> would warn the user in case of these missing files like wxWidgtes XRC sample
> does.

Oh wow - I have no idea why those should break wxWidgets, but I wonder
if building wxWidgets with --enable-mimetype=no would have made any
difference.

Anyway, glad it's working now.

>
> Thank you very much indeed Dave for your support and help!

You're welcome.

--
Dave Page
EnterpriseDB UK:

http://www.enterprisedb.com

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

Re: [pgadmin-support] pgAdmin 1.8.x hangs while tries to load XRC resources

Dave Page wrote:
> On Sat, Jun 7, 2008 at 9:35 AM, Antonello Biancalana
> <promindsd@gmail.com> wrote:
>
> Not offhand. Does the wxWidgets XRC sample work?

Thank you for your reply and your help. Your suggestion was of terrific
help to me. I compiled and run the wxWidgets XRC sample and it worked
but it complained about some missing files (whereas pgadmin did not).
The XRC sample complained about the following missing files in my system:

usr/share/mimelnk/application/vnd.adobe.pdx.desktop
usr/share/mimelnk/application/vnd.adobe.xdp+xml.desktop
usr/share/mimelnk/application/vnd.adobe.xfdf.desktop
usr/share/mimelnk/application/vnd.fdf.desktop

which actually resulted to be missing links belonging to an old
installation of Adobe Acrobat Reader 7. I deleted these missing links
and now pgAdmin works.
I hope this can help other pgAdmin users. Maybe it would be nice if
pgAdmin would warn the user in case of these missing files like
wxWidgtes XRC sample does.

Thank you very much indeed Dave for your support and help!

--

Antonello Biancalana
ProMIND software development - Perugia (ITALY)
e-mail: promindsd@gmail.com
skype: antonello.biancalana

PGP key ID: D40B3BC3
PGP key fp: AC62 7264 4233 5ADD 5ADA D4D3 9B35 6051 D40B 3BC3


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

Re: [pgadmin-support] pgAdmin 1.8.x hangs while tries to load XRC resources

On Sat, Jun 7, 2008 at 9:35 AM, Antonello Biancalana
<promindsd@gmail.com> wrote:
> I have a problem in getting pgAdmin3 working since the 1.8.x series.
> I usually build pgAdmin from source (however also the binary releases give
> me the same problem) and whenever I try to run pgAdmin it shows the splash
> screen and then it always hangs. After having traced the exact point of
> hanging, I noticed it always hangs at file pgadmin/ui/xrcDialogs.cpp line
> 13760 (1.8.4 version) at the point of the first wxXmlResource::Get()->Load
> call.
> I also tried to disable EMBED_XRC define and to copy all the XRC files to
> [uiPath] with no success. I am currently using wxGTK 2.8.7 and all the other
> requirements (in particular libxml2, ver. 2.6.32) seem to be right. By the
> way: I am using Linux (Fedora 9). No problem if I use pgAdmin 1.6.3: it
> complies and runs smoothly and with no problem. I am having this problem
> since the release of pgAdmin 1.8.0
> Do you have any idea of what the problem can be?

Not offhand. Does the wxWidgets XRC sample work?


--
Dave Page
EnterpriseDB UK: http://www.enterprisedb.com

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

[pgadmin-support] pgAdmin 1.8.x hangs while tries to load XRC resources

I have a problem in getting pgAdmin3 working since the 1.8.x series.
I usually build pgAdmin from source (however also the binary releases
give me the same problem) and whenever I try to run pgAdmin it shows the
splash screen and then it always hangs. After having traced the exact
point of hanging, I noticed it always hangs at file
pgadmin/ui/xrcDialogs.cpp line 13760 (1.8.4 version) at the point of the
first wxXmlResource::Get()->Load call.
I also tried to disable EMBED_XRC define and to copy all the XRC files
to [uiPath] with no success. I am currently using wxGTK 2.8.7 and all
the other requirements (in particular libxml2, ver. 2.6.32) seem to be
right. By the way: I am using Linux (Fedora 9). No problem if I use
pgAdmin 1.6.3: it complies and runs smoothly and with no problem. I am
having this problem since the release of pgAdmin 1.8.0
Do you have any idea of what the problem can be?

Thank you for your support and help.

Best regards.

Antonello

Bug report information:

pgAdmin ver 1.8.4
configure with no options
OS: Fedora 9, Linux 2.6.25.4
wxWidgets: wxGTK 2.8.7, configure --with-gtk --enable-gtk2 --enable-unicode
postgreSQL ver 8.3.1, configure with no options


--

Antonello Biancalana
ProMIND software development - Perugia (ITALY)
e-mail: promindsd@gmail.com
skype: antonello.biancalana

PGP key ID: D40B3BC3
PGP key fp: AC62 7264 4233 5ADD 5ADA D4D3 9B35 6051 D40B 3BC3


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

Re: [pgadmin-support] Weird Popup Menus - pgAdmin 1.8.4

On Sat, Jun 7, 2008 at 8:55 AM, Guillaume Lelarge
<guillaume@lelarge.info> wrote:
>
> Actually, I do have the same issue (on the same distro). But I thought *I*
> was doing something wrong :)
>
> So, I need to take a serious look at this.

It's also been noted by our quality management team. I believe it's a
wxWidgets bug but I suspect we may not see a 2.8.8 version so may have
to work round this ourselves*. When we add options to the content
menu, perhaps we should just strip out the &'s (they prefix char that
should be underlined) on GTK - the bug isn't there on Windows/Mac.

* The next major version of wxWidgets is apparently going to be 3.0.0
which will be very different from what I hear, so we may not upgrade
immediately.

--
Dave Page
EnterpriseDB UK: http://www.enterprisedb.com

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

Re: [pgadmin-support] Weird Popup Menus - pgAdmin 1.8.4

Christos Vasilakis a écrit :
> [...]
> Although the application runs fine without any problems, the menus in
> the popups are garbaged with the _ character. I believe its used to
> characterize the shortcut character in the keyboard. For example if i
> right click in a table i get this
>
> Re_fresh
> _Count
> ...
> _Reports
> _Maintenance
>
> etc.
>
> In the top level menus File Edit View.. it is displayed correctly.
>

Actually, I do have the same issue (on the same distro). But I thought
*I* was doing something wrong :)

So, I need to take a serious look at this.


--
Guillaume.

http://www.postgresqlfr.org

http://dalibo.com

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

[pgadmin-support] Connecting from xp to linux server

Hi all,

this is the problem I am facing.

I have PG 8.3 running on a KUBUNTU installation running on a virtual
machine. From inside the virtual machine I can use PGADMIN to manage PG
but when I try to connect from the xp machine I have this error: "Error
connecting to the server:FATAL: missing or erroneous pg_hba.conf file" .

I set the permission in the pg_hba.conf on the server.

The machine talk each oher, I can ping and use telnet on the 5432 port.

The log on the server does not report any problem.

Ideas?

S.

--


Dr. Simone Gadenz

via P. Togliatti 69, 50051

Castelfiorentino (FI)

+39 339 6053660

*INFORMATIVA PRIVACY (ex D.lgs. 196/03)*

Le inormazioni contenute in questo documento e nei relativi allegato

possono essere riservate e sono destinate esclusivamente alla persona

od alla Società indicata come destinatario.

La diffusione e la distribuzione del presente documento a soggetti

diversi da quelli indicati, od in genere qualsivoglia utilizzo illecito

dei dati ivi contenuti, e proibita sia ai sensi dell'art. 616 del

Codice Penale che dal D.Lgs 196/03 in materia di protezione dei dati

personali (Privacy).

Se avete ricevuto per errore questo documento siete pregati di

distruggerlo e di comunicarcelo prontamente tramite e-mail o fax.


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

Friday, June 6, 2008

[ODBC] TIMEOUT attributes

Hi,

 

Does the ODBC driver for postgresql support the following timeout attributes (one way or around)?

 

  1. SQL_ATTR_CONNECTION_TIMEOUT
  2. SQL_ATTR_QUERY_TIMEOUT

 

With regards,

Vivek Gupta

[GENERAL] IN vs EXISTS

Hi all,

I have been using IN clause almost exclusively until recently I tried
to use EXISTS and gained significant performance increase without
changing/creating any indexes:

SELECT ... FROM a WHERE a.ref IN (SELECT b.id WHERE ...)

vs

SELECT ... FROM a WHERE EXISTS (SELECT 1 FROM b WHERE a.ref=b.id ...)

Performance is at least few times better when EXISTS is used. Is it
just PostgreSQL specific?

Cheers

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

Re: [pgsql-es-ayuda] por que SEQ SCAN Y NO INDEX SCAN

On Fri, Jun 6, 2008 at 4:39 PM, Alvaro Herrera
<alvherre@commandprompt.com> wrote:
> MIGUEL CANCHAS escribió:
>
>> ***********ESTE ES EL EXPLAIN ANALYZE **********************************+
>>
>> "Hash Left Join (cost=61680.50..68144.24 rows=3 width=122) (actual
>> time=32106.612..32344.086 rows=11 loops=1)"
>
> Hmm, este problema parece que lo pasamos por alto ... ¿lo resolviste?


mmm... tenés razón (como escribirian los amigos argentinos)...

vejecutado_tejeduria es una vista, verdad?
esa es la parte que demora, devuelve 595637 filas... que pasa si
quiebras la consulta en 2 partes?

--
Atentamente,
Jaime Casanova
Soporte y capacitación de PostgreSQL
Guayaquil - Ecuador
Cel. (593) 87171157
--
TIP 3: Si encontraste la respuesta a tu problema, publícala, otros te lo agradecerán

Re: [pgsql-advocacy] PostgreSQL derivatives

On Fri, Jun 6, 2008 at 8:14 PM, Joshua D. Drake <jd@commandprompt.com> wrote:
> Well GridSQL isn't even an extension to PostgreSQL is it? It is written
> in java and appears to be a userland application (or middleware if you
> prefer). I could be wrong.

Correct, sort of. GridSQL is not part of the core server, it is a
separate Java-based distributed database which front-ends a cluster of
Postgres servers.

Originally, GridSQL was written to be database independent. However,
over the last year, it has been specialized for Postgres. Some of
these specializations include support of the Postgres wire-level
protocol, an understanding of Postgres SQL syntax, etc. Coming
versions of GridSQL will support more native Postgres features and may
benefit from some of our internal changes to the database core.

Regardless, it is open source and should always run against standard PostgreSQL.

--
Jonah H. Harris, Sr. Software Architect | phone: 732.331.1324
EnterpriseDB Corporation | fax: 732.331.1301
499 Thornall Street, 2nd Floor | jonah.harris@enterprisedb.com
Edison, NJ 08837 | http://www.enterprisedb.com/

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

Re: [pgsql-advocacy] PostgreSQL derivatives

On Fri, 6 Jun 2008, Robert Treat wrote:

> But there isn't any floss software actually being shipped right? License/code
> wise truviso and netezza are basically the same in that respect, even if
> technologically truviso values postgres compatability higher, but there is no
> floss distributing occuring, right?

It's complicated and not something I'm at liberty to discuss. Suffice it
to say that there's a large list of FLOSS credits for the software stack
that Truviso provides to customers. But a look at the web site will note
the lack of the usual "Download" tab for the world at large, and the exact
details of how the FLOSS software distributed fits together isn't public
info yet at this point.

Tell you any more I'd have to kill you, etc.

> Oh, I understand that, but I even with the other ways, I don't know
> where Truvisio draws that line. Granted even if thier corporate policy
> is "never work on postgres during business hours"...

We're a startup--it's always business hours. The line you hypothesize
isn't really drawn too brightly. It may materialize further once I talk
with management about whether the days I spend at OSCON next month are
work or vacation time. If there's a BWPUG meeting next week (note subtle
hint that it's not clear yet whether there is or not) and I'm in town this
time I have a good story for you about that.

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

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

[SQL] Need some magic with alternative rows

Hi,
I need some magic with alternative rows.

I've got a table with rows relating another table.
mytab (id, name, group_nr, class_nr, fk)

SELECT * FROM mytab
WHERE (fk = 994010)
OR ((class_fk = 40) AND (fk = 0))

994001, Tick, 1, 40, 994010
4001, Reporting, 1, 40, 0
4002, LEADS, 2, 40, 0
994003, Track, 3, 40, 994010
4003, Details, 3, 40, 0

The rows with fk=0 are defaults that should only be used when there is
no specific reference to the other table.

Is there a way to remove the default-rows if there exists a fk<>0 row
that has the same group_nr ?
I'd like to get just:

994001, Tick, 1, 40, 994010
4002, LEADS, 2, 40, 0
994003, Track, 3, 40, 994010


Regards
Andreas


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

Re: [GENERAL] strpos NOT doing what I'd expect

Ralph Smith <smithrn@washington.edu> writes:
> DECLARE
> achar character := '' ;

Use varchar or text. character is weird about trailing spaces.

regards, tom lane

--
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] Overhauling GUCS

"Joshua D. Drake" <jd@commandprompt.com> writes:
> Not surprising really. It is a simple adjustment to make and it also is
> easy to spot when its a problem. However it is not trivial to test for
> (in terms of time and effort). I know 10 is wrong and so do you.

Sure. But what is right? I'm afraid to just push it to (say) 100
because of the possibility of O(N^2) behavior in eqjoinsel. Somebody
needs to do some measurements on somewhat realistic scenarios.

regards, tom lane

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

Re: [pgsql-www] Ask for Help on Improving the FreeBSD FAQ

On Sat, 2008-06-07 at 03:46 +0200, Gabor PALI wrote:
> > Oh I apologize :). PeterE is pretty much lead doc dude around here:

> Yes, I would like to know more about:
> - how you do implement the user comments on your web pages,

Ahh yes this is not actually a doc question, so you are in the right
place. These are stored in a PostgreSQL database and sent through a
moderation queue. If the comment is appropriate we include the
information in the next version of the docs.

The website svn is available here:

https://pgweb.postgresql.org/

> - whether you do have any schedule for merging these comments,

Per each major release.

> - how you do build and mark up the different versions (e.g. static and
> interactive per versions) of the documentation,

That I can't answer.

> - whether you do have any project-specific modifications for DocBook

We have specific stylesheet changes yes, you can find them in our
src/doc if you download a tarball.

> - what other tools you do use for creating documentation

Just docbook and jade :) (and dsssl)

Sincerely,

Joshua D. Drake

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

Re: [GENERAL] PL/pgSQL graph enumeration function hangs

"Charles F. Munat" <chas@munat.com> writes:
> Using pseudocode from Celko's "SQL for Smarties" book, I wrote the
> following function that builds a path enumeration table. I hope to
> trigger this function on the rare occasions that the organizations table
> is updated. But when I run this function, it hangs.

I think there might be something wrong with this query:

> INSERT INTO organizations_path_enum
> SELECT o1.parent_id, r1.child_id, (o1.depth + 1)
> FROM organizations_path_enum o1, relationships r1
> -- advance existing paths by one level
> WHERE EXISTS (SELECT * FROM organizations_path_enum AS o2
> WHERE r1.parent_id = o2.child_id)
> -- insert only new rows into the table
> AND NOT EXISTS (SELECT * FROM organizations_path_enum AS o3
> WHERE o1.parent_id = o3.parent_id AND r1.child_id = o3.child_id);

I'm not totally clear on what this is supposed to accomplish, but
it seems like there should be some join clause between o1 and r1.

regards, tom lane

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

Re: [pgsql-www] Ask for Help on Improving the FreeBSD FAQ

> Oh I apologize :). PeterE is pretty much lead doc dude around here:

Thank you, I will also contact him, but I think he will got all these mails.


> But I might be able to help you as well. Do you have a specific are of
> interest besides the fact that we use Docbook?

Yes, I would like to know more about:
- how you do implement the user comments on your web pages,
- whether you do have any schedule for merging these comments,
- how you do build and mark up the different versions (e.g. static and
interactive per versions) of the documentation,
- whether you do have any project-specific modifications for DocBook
- what other tools you do use for creating documentation


Thank you for your answers in advance,
:g

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

Re: [pgsql-www] Git access?

On Fri, 2008-06-06 at 13:54 +0200, Peter Eisentraut wrote:
> Am Donnerstag, 5. Juni 2008 schrieb David Fetter:
> > How do I get access to create git repositories on git.postgresql.org?

> The plan is to try out gitosis for account management. I have no experience
> with this, so we'd need to play around with it first.

Peter,

Just FYI if you find you don't like that direction, let me know and I
would gladly show you how I did it for pgweb with SVN... I believe it
would work out of the box for the git stuff.

Sincerely,

Joshua D. Drake


>


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

Re: [pgsql-www] Ask for Help on Improving the FreeBSD FAQ

On Sat, 2008-06-07 at 03:35 +0200, Gabor PALI wrote:
> Hello Joshua,

> I got this advice from Bruce Momjian, because we are mainly interested
> in the implementation, not in the documentation itself :) As far as I
> know, this list is for developers, and -doc is for users. Do you know
> who is responsible for the implementation of the documentation?

Oh I apologize :). PeterE is pretty much lead doc dude around here:

Peter Eisentraut <peter_e@gmx.net>

But I might be able to help you as well. Do you have a specific are of
interest besides the fact that we use Docbook?

Sincerely,

Joshua D. Drake

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

Re: [pgsql-es-ayuda] Pasar datos de una tabla a un archivo

frank wrote:
>
> Saludos lista,
>
>
>
> No se si a alguno le halla sucedido, pero tengo el siguiente dilema:
>
>
>
> Estoy desarrollando una aplicación que interactúa con Linux y más
> concretamente con el squid.
>
>
>
> Es para una empresa que tiene políticas de suspensiones temporales del
> servicio de Internet. El squid tiene un archivo de texto en el cual
> están todas las IPs que tienen permiso para navegar pero dicho archivo
> constantemente está editándose: añadiendo, modificando, borrando, etc.
>
>
>
> Mi intensión es que todos datos, incluyendo las IPs de los usuarios se
> guarden en la BD de Postgre. Luego hacer que mediante la web puedan
> modificar el archivo del squid de las IPs. Esto lo puedo hacer cuando
> son una o dos líneas las que tengo que añadir ya que ahí solo
> interviene la consulta obtenida de la base y el resto lo hace el Mono
> con el cual edito el archivo de Linux.
>
>
>
> Pero mi problema es cuando sean 100 o 200 líneas para borrar o para
> añadir. Actualmente lo hago con un script en Linux que edita el
> archivo línea por línea. Pero esto no lo voy a hacer para eliminar 100
> líneas o para añadir 50.
>
>
>
> La solución que se me ocurre es volver a generar el archivo solo con
> las IPs válidas y por esto acudo a Uds. Alguno sabe si se puede pasar
> los datos de una tabla o consulta sql directamente hacia un archivo de
> texto ¿? O alguno tiene alguna otra idea ¿?
>
>
>
> Disculpen lo largo del cuento pero es por si alguno me puede orientar
> mejor.
>
>
>
Porque no accesar a la base de datos con un script de perl que forme el
archivo de texto que necesitas?

--
Saludos,

Julio Cesar Sánchez González.

--
Ahora me he convertido en la muerte, destructora de mundos.
Soy la Muerte que se lleva todo, la fuente de las cosas que vendran.

www.sistemasyconectividad.com.mx

http://darkavngr.blogspot.com/

--
TIP 8: explain analyze es tu amigo

Re: [pgsql-www] Ask for Help on Improving the FreeBSD FAQ

Hello Joshua,

Joshua D. Drake wrote:
>
> On Fri, 2008-06-06 at 19:02 +0200, Gabor PALI wrote:
>> Dear PostgreSQL Developers,
>
>> Thank you for your help in advance.
>
> I think you may want to be at pgsql-docs
>

I got this advice from Bruce Momjian, because we are mainly interested
in the implementation, not in the documentation itself :) As far as I
know, this list is for developers, and -doc is for users. Do you know
who is responsible for the implementation of the documentation?


Thank you,
:g


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

Re: [HACKERS] Overhauling GUCS

On Fri, 2008-06-06 at 20:19 -0400, Tom Lane wrote:
> Robert Treat <xzilla@users.sourceforge.net> writes:

> Actually, the reason it's still 10 is that the effort expended to get it
> changed has been *ZERO*. I keep asking for someone to make some
> measurements, do some benchmarking, anything to make a plausible case
> for a specific higher value as being a reasonable place to set it.

> The silence has been deafening.

Not surprising really. It is a simple adjustment to make and it also is
easy to spot when its a problem. However it is not trivial to test for
(in terms of time and effort). I know 10 is wrong and so do you. If you
don't I am curious why I see so many posts from you saying, "Your
estimates are off, what is your default_statistics_target?" with yet
even more responses saying, "Uhh 10."


Sincerely,

Joshua D. Drake


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

Re: [HACKERS] Overhauling GUCS

On Fri, 6 Jun 2008, Tom Lane wrote:

> Well, you can't see the default or reset values in pg_settings, only the
> current value. However, I fail to see the use of either of those for
> a configure wizard.

I'm under the impression that the primary reason to put the default in
there is to make it easier for a file generator program to be decoupled a
bit from the internal representation. Regardless, these values should be
exposed for tool writers. If you build a prototype interface for an
interactive settings changing tool, you quickly discover that showing the
default, range, and recommended setting are all valuable things people
would like to see when deciding what the change a setting to. And there's
no reason accumulating all that info should be the responsibility of a
tool writer when it's easy to expose and keep up to date inside the
database itself.

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

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

[GENERAL] strpos NOT doing what I'd expect

CODE:
===============================
CREATE OR REPLACE FUNCTION find_next_delim(invar varchar, delimlist varchar) RETURNS integer AS
$$

/*   OVERLOADED Function.  The other version takes a 3rd parameter as the
                starting position in invar.
*/

DECLARE
  
  achar  character := '' ;
  j      int       := 0  ;
  
BEGIN

  IF length(delimlist) = 0 THEN
    RAISE NOTICE 'In function \'find_next_delim\' the delimiter cannot be null.' ;
  END IF ;

  
  FOR i IN 1 .. length(invar) 
  LOOP

    j := j + 1 ;
    achar := substring(invar from i for 1 ) ;
    RAISE NOTICE 'achar is R%S',achar ;
    IF strpos(delimlist,achar) <> 0 THEN
      RETURN j ;
    END IF ;
    
  END LOOP ;
  
  RETURN 0 ;
  
END ;
$$ LANGUAGE plpgsql ;  /*   find_next_delim   */




WHAT'S HAPPENING:
===============================
airburst=# select find_next_delim('ralph smith','3') ;

NOTICE:  achar is RrS
NOTICE:  achar is RaS
NOTICE:  achar is RlS
NOTICE:  achar is RpS
NOTICE:  achar is RhS
NOTICE:  achar is R S
 find_next_delim 
-----------------
               6
(1 row)


airburst=# select find_next_delim('ralph smith','') ;  -- for the heck of it, that's a null

NOTICE:  In function 'find_next_delim' the delimiter cannot be null.
NOTICE:  achar is RrS
NOTICE:  achar is RaS
NOTICE:  achar is RlS
NOTICE:  achar is RpS
NOTICE:  achar is RhS
NOTICE:  achar is R S
 find_next_delim 
-----------------
               6
(1 row)

WHY find a match on the space???

Thanks!

Re: [HACKERS] Overhauling GUCS

Greg Smith <gsmith@gregsmith.com> writes:
> On Fri, 6 Jun 2008, Gregory Stark wrote:
>> "Greg Smith" <gsmith@gregsmith.com> writes:
>>> 1) Is it worthwhile to expand the information stored in the GUC structure to
>>> make it better capable of supporting machine generation and to provide more
>>> information for tool authors via pg_settings? The exact fields that should or
>>> shouldn't be included remains controversial; consider "default value",
>>> "per-session/runtime/restart", and "enum lists" as the list of things that are
>>> most needed there.
>>
>> Isn't that a list of what's *already* there?

> I should have been clearer there. Some of the items suggested are already
> in the structure, but aren't visible via pg_settings.

Well, you can't see the default or reset values in pg_settings, only the
current value. However, I fail to see the use of either of those for
a configure wizard. It'll presumably be attached to a fresh connection
so the reset value is not different from the current; and any decent
wizard is going to know perfectly well what the defaults are.

> ... In others (like the
> suggestion to add a URL to the documentation) it is actually a new field
> being added as well as its corresponding entry in the settings view.

Offhand I would argue that we should choose the URLs in such a way that
they can be derived automatically if you know the PG version number and
GUC variable name. (We're almost there already, except that you have
to know which section of the chapter it's in.) So the need to have a
pg_settings column seems questionable --- seems like it would mostly
be clutter. Perhaps instead of a view column, it would be useful to
encapsulate the algorithm as a function? pg_variable_help_url(name)

regards, tom lane

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

Re: [HACKERS] Overhauling GUCS

Robert Treat <xzilla@users.sourceforge.net> writes:
> There is a saying, something like "The accumulation of annecdotes is not
> data". Well, we seem to have a high bar on what proof we need to actually
> change a default GUC settings. default_statistics_target is a prime example,
> where almost no one i know has ever recommended 10 as a default, or suggests
> setting it to 10 as an way to improve performance, but the effort to get it
> changed to something more reasonable has been monumental.

Actually, the reason it's still 10 is that the effort expended to get it
changed has been *ZERO*. I keep asking for someone to make some
measurements, do some benchmarking, anything to make a plausible case
for a specific higher value as being a reasonable place to set it.

The silence has been deafening.

regards, tom lane

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

Re: [pgsql-advocacy] PostgreSQL derivatives

On Fri, 2008-06-06 at 19:58 -0400, Robert Treat wrote:
> On Friday 06 June 2008 18:32:23 Jonah H. Harris wrote:
> > We make closed-source changes related to the Postgres core related to
> > performance and Oracle compatibility. But, while these changes are
> > fairly significant, they do not prevent us from laying over a newer
> > version of Postgres. Similarly, as you mentioned, GridSQL is fully
> > open source.
> >
>
> Note that GridSQL, while it works with postgres, was developed completely
> seperate and independently from postgresql.

Well GridSQL isn't even an extension to PostgreSQL is it? It is written
in java and appears to be a userland application (or middleware if you
prefer). I could be wrong.

Sincerely,

Joshua D. Drake

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

Re: [SQL] crosstab functions in postgres 8.1

"Chris Preston" <chris@thetrafalgartravel.com> writes:
> I am almost a newbie to postgres and only recently found out about one of
> the greatest function crosstab in postgres. The problem is that I am using
> 8.1 and when I run the function I am getting an error relating to
> $libdir/tablefunc.. someone mentioned that it might be because I am using
> ver 8.1 and not 8.3

Well, since you didn't supply the exact error message, this is just a
guess; but it sounds like you haven't got the contrib/tablefunc module
installed in your 8.1 database, or at least haven't got it installed
correctly. You need a tablefunc.so file that is compiled for 8.1
(copying the 8.3 version will almost certainly NOT work).

regards, tom lane

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

[GENERAL] array column and b-tree index allowing only 8191 bytes

Hi all,

I'm checking out some features in pgsql and found out about an array
datatype. As I'm curious to find out how well it performs, I've created
a table that contains an integer[] column and a script to insert about
500K rows in it. The length for the integer[] column is random (can be
10, can be 5000, can be more than that), as are the values in it.

When trying to insert a row, I get the following error:

index row requires 9796 bytes, maximum size is 8191

If I understood correctly, this is a limit of the b-tree index. Usually
you'd want to use another type of index but, again if I understood
correctly, those are meant mostly for full-text indexing.

Remember, I'm doing this for recreational purposes (the array type is
there, wanted to check out it's performance so why not? :-) ).

So my questions are: is this at all possible? If so, is is possible to
increate that maximum size?

Regards,
Celso


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

Re: [pgsql-advocacy] PostgreSQL derivatives

On Friday 06 June 2008 18:32:23 Jonah H. Harris wrote:
> On Fri, Jun 6, 2008 at 6:26 PM, Seth Grimes <grimes@altaplana.com> wrote:
> > My understanding is that the MPP vendors using PostgreSQL and Ingres are
> > not *significantly* altering the software other than to, essentially,
> > turn off reliance on indexes. They're then adding extensions that are
> > proprietary and not, except in the case of GridSQL, open source. Is my
> > understanding correct?
>
> We make closed-source changes related to the Postgres core related to
> performance and Oracle compatibility. But, while these changes are
> fairly significant, they do not prevent us from laying over a newer
> version of Postgres. Similarly, as you mentioned, GridSQL is fully
> open source.
>

Note that GridSQL, while it works with postgres, was developed completely
seperate and independently from postgresql.

--
Robert Treat
Build A Brighter LAMP :: Linux Apache {middleware} PostgreSQL

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

Re: [BUGS] BUG #4116: Cannot create tablespace: could not set permissions on directory

Alvaro Herrera <alvherre@commandprompt.com> writes:
> Graham Leggett wrote:
>> This code makes the incorrect assumption that the platform will allow the
>> postgres user to set the permissions using chmod.

> Is this something we should do anything about?

IMHO, no. The reason for actually doing the chmod is to verify that we
own the directory. If it fails, we don't own the directory in any
meaningful sense. I think the complainant's real problem is that he's
misconfigured his SELinux permissions.

regards, tom lane

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

Re: [HACKERS] Overhauling GUCS

On Sat, 2008-06-07 at 01:30 +0200, Andreas Pflug wrote:
> Gregory Stark wrote:
> > "Andreas Pflug" <pgadmin@pse-consulting.de> writes:

> I think I made my point very clear when stating "not a file, but via
> SQL". Though I'm not a native English speaker, and I'm sure you
> understood. I must assume you're polluting this thread deliberately in
> order to sabotage the original intention of this thread. I find this
> disgusting.
>
> Ok, trying to contribute gui tools for pgsql is for masochists. We have
> vi, sed and grep, no more tools required, right?

Hold on guys, let's not get all out of whack. No one in their right mind
is going to suggest that vi, sed and grep are the only tools we need to
do this.

However a GUI wizard isn't really a way to go either. SQL? Yes it would
be very nice to be able to:

BEGIN;
SET shared_buffers to 65536 COMMENT IS 'Since I have 4G of ram I want
512 megs of shared buffers';
SET effective_cache_size to 262144 COMMENT IS 'Since I have 4G of ram I
want 1 gig of effective_cache';
COMMIT;

When that is done, it would write out the postgresql.conf.

Regardless of all of this, this thread is way out of hand. We went from
overhauling the configuration file to wizards, sample postgresql.conf
files and possibly even half of us migrating to MySQL :P.

Can we refine the topic a bit?

Joshua D. Drake


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

Re: [HACKERS] Overhauling GUCS

Gregory Stark wrote:
> "Andreas Pflug" <pgadmin@pse-consulting.de> writes:
>
>> I personally wouldn't even think about starting such a wizard, unless I have an
>> idea how to push the result into the database. No, not a file, but via SQL! So
>> your statement you won't react unless a wizard is almost ready is prohibitive,
>> apart from the fact that not only wizards (featuring AI) are interesting, but
>> simple config tools as well.
>
> Well there's a perfectly good place to start today. Dump out a config file

I think I made my point very clear when stating "not a file, but via
SQL". Though I'm not a native English speaker, and I'm sure you
understood. I must assume you're polluting this thread deliberately in
order to sabotage the original intention of this thread. I find this
disgusting.

Ok, trying to contribute gui tools for pgsql is for masochists. We have
vi, sed and grep, no more tools required, right?

Regards,
Andreas

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

Re: [COMMITTERS] pgsql: Translation updates.

Alvaro Herrera <alvherre@commandprompt.com> writes:
> Tom Lane wrote:
>> Hmm, you're right, the es/postgres.po file in the pgtranslation
>> repository has an unexpanded $PostgreSQL$ tag. Which is unsurprising
>> since pgfoundry's CVS is probably not set to recognize that tag.

> Well, my intention was that $Id$ should be expanded in pgfoundry, and
> $PostgreSQL$ should be expanded when the file is imported from pgfoundry
> into the main CVS repo. I'm not sure why it hasn't.

Right, but the copy in pgfoundry has never been imported into the main
CVS repo ...

regards, tom lane

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

[PATCHES] Patch for dependency traversal during DROP

The attached patch rewrites DROP recursion according to my sketch here:
http://archives.postgresql.org/pgsql-hackers/2008-05/msg00301.php

It gets rid of a lot of unwanted NOTICE messages during drop, specifically
by ensuring that AUTO/INTERNAL drops are silent even when they cascade
from other cascaded objects. (In an unexpected side benefit, the messages
seem to come out in a more logical order, too.) See the regression test
diffs for examples. Also, it takes locks on objects before searching for
their dependencies, which fixes all of the concurrent-deletion problem
cases that I linked to in the above message.

I have not done anything about folding cascaded-drop NOTICEs into a
single long message, as was discussed a couple days ago. That would be
easy to do from here, but it seems like it should be a separate patch.

I was afraid while writing the patch that it might be too slow due to
reliance on simple linear list searching in ObjectAddresses lists ---
that means that deleting N objects is O(N^2), albeit with a constant
factor that's pretty tiny compared to the catalog-update work involved.
While this could be fixed by replacing ObjectAddresses with a more complex
data structure, I didn't want to have to do that in a first-generation
patch either. So I was pleased to find out that it actually seems to
be faster than CVS HEAD. I tested by timing "DROP SCHEMA public"
after running the regression tests. In CVS HEAD this involves dropping
1177 distinguishable objects (ie, there are that many entries in the
targetObjects list at completion of the scan phase). I get these timings
on a pretty-slow HPPA machine:

CVS HEAD:

$ time psql -c 'drop schema public restrict' regression 2>/dev/null

real 0m2.53s
user 0m0.04s
sys 0m0.03s
$ time psql -c 'drop schema public cascade' regression 2>/dev/null
DROP SCHEMA

real 0m8.06s
user 0m0.05s
sys 0m0.03s

With patch:

$ time psql -c 'drop schema public restrict' regression 2>/dev/null

real 0m0.74s
user 0m0.03s
sys 0m0.02s
$ time psql -c 'drop schema public cascade' regression 2>/dev/null
DROP SCHEMA

real 0m6.83s
user 0m0.03s
sys 0m0.02s

The speedup in RESTRICT timing was expected, but not so much CASCADE.
(BTW, I wonder why aren't the RESTRICT and CASCADE timings about the same
in CVS HEAD? The old implementation does all the same work in both cases,
and only fails at the end...)

It might be that with many thousand objects to be dropped, we'd
start to hit the O(N^2) behavior, but I suspect that CVS HEAD is
none too pleasant in such a case either. Anyone want to run some
experiments?

Another possible objection to this patch is that it takes an awful lot
of locks on things that we never locked before; a large DROP operation
could easily run out of locktable shared memory when it did not before.
That's fixable by increasing max_locks_per_transaction, but I wonder
whether there will be any push-back about it.

A couple of stylistic issues:

* After obtaining lock on an object-to-be-deleted, we need to check
whether it's already been deleted. This could have been done with
a pile of object-type-specific SearchSysCache tests, but I chose to
do it by checking to see if the pg_depend tuple we are traversing
has been marked dead; aside from being object-type-independent,
that should be a lot cheaper. This required sticking a little bit
of a wart into genam.c, since only at that level do we know which
buffer the tuple is in. This seemed cleaner than the alternative,
but I wonder if anyone has a better idea?

* The DROP code now requires more per-target-object state than just
the object's identity. However the ObjectAddresses struct it was
using is also shared with various dependency-adding functionality
that doesn't need any more than that. I chose to deal with that
by having the ObjectAddresses support routines handle ObjectAddresses
with or without a secondary "extra data" array. This is pretty ugly
IMHO, but duplicating most of that support code seemed no better.
Anybody have a strong aversion to that, or a better idea? (The
whole area might have to be revisited anyway, if we decide we need
something smarter than a linear list.)

If there are no objections I'll apply this in a day or two.

regards, tom lane

Re: [pgus-board] It's time for final review

On Fri, 2008-06-06 at 15:29 -0700, Selena Deckelmann wrote:

> On Fri, Jun 6, 2008 at 3:03 PM, Joshua D. Drake <jd@commandprompt.com> wrote:
>
> > 1. No elections, only appointees -- would be a publicity nightmare but
> > it is certainly not unheard of and in fact has shown that it works very
> > well in certain circumstances.
>
> I think if we chose a different name - like "Pg'R'Us" (with the US not
> meaning United States), or "Cmte for the Advancement of PostgreSQL" we
> could do that.

Well I wasn't actually suggesting it but as a note, Core is not
elected :P

> > 2. Hold off elections of the new board until March and have that board
> > term be 2 years. That means that every other year we would potentially
> > replace 3 or 4 depending on the year.
>
> Apologies to you both, but I would like Portland to be the place that
> these elections take place. And I would like the fall conference to
> continue to be on the West coast.

No reason to apologize, its what has been discussed and agreed upon. Its
just an issue of resolving the problem at this point. The fall
conference, considering its called West will likely always be on the
west coast (unless we somehow re-define the term west) but that isn't
really relevant to this discussion :P

>
> > 3. Have elections twice a year once the founder terms are up. Which
> > means twice a year we could lose 3 or 4.
>
> I think this is excessive.

Right. Which is why I documented my perfect world.

Sincerely,

Joshua D. Drake

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

[BUGS] BUG #4226: PG_CTL fails to strip admin rights before running postgres

The following bug has been logged online:

Bug reference: 4226
Logged by: Austin Lee
Email address: Austin_Lee@rapid7.com
PostgreSQL version: 8.2.7
Operating system: Win2k3R2SP2
Description: PG_CTL fails to strip admin rights before running
postgres
Details:

I am trying to run pg_ctl.exe as admin when I get this error.
"FATAL: postgres: could not locate matching postgres executable."

I know there was a fix in 8.2.7 to fix this permission admin rights issue.
I've observed the fix in initdb.exe. In 8.2.1 initdb fails because it can't
find postgres. In 8.2.7 initdb success.

I assumed pg_ctl would have the same behaivor since I see the same calls to
AddUserDacl that I saw for initdb. However, I am still coming up error for
pg_ctl which I believe might be a windows permission issue.

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

[GENERAL] accessing table in LIFO order

I have got a table that holds 2 columns: date_id and info. date_id is bigint, created as, for eg. 17 May 2008, 19:05 hrs => 200805171905. This table is populated with {date, info} pair that I receive frequently. AND there can be mltiple such entries with a single date_id but varying info, for eg. 20 entries with same date_id but different info. I haven't created any primary key or index.

I use query that looks like this:
SELECT date_id, info FROM netproto_entries ORDER BY date_id DESC LIMIT <limit_val>;

Questions:
- For higher values of limit_val (say 70/75/..), when I change it, the order
  in which I get the entries changes. Eg. it shows me one info at the top at
  one time, and another on the next time with a different value of limit_val.

- My intent is to fetch the entries from the database in LIFO order, most
  recently entered entry at the top. For the elements with the date_id being
  the same, they are not in LIFO order. I understand that I can add another
  incrementing index column and sort the table based on that. But, without adding this,
  does postgresql have any method/configuration to get me output in LIFO order ?
  And are there any better methods available compared to adding another index
  column (as mentioned above) ?

Thanks,
Ethan

[GENERAL] accessing table in LIFO order

I have got a table that holds 2 columns: date_id and info. date_id is bigint, created as, for eg. 17 May 2008, 19:05 hrs => 200805171905. This table is populated with {date, info} pair that I receive frequently. AND there can be mltiple such entries with a single date_id but varying info, for eg. 20 entries with same date_id but different info. I haven't created any primary key or index.

I use query that looks like this:
SELECT date_id, info FROM netproto_entries ORDER BY date_id DESC LIMIT <limit_val>;

Questions:
- For higher values of limit_val (say 70/75/..), when I change it, the order
  in which I get the entries changes. Eg. it shows me one info at the top at
  one time, and another on the next time with a different value of limit_val.

- My intent is to fetch the entries from the database in LIFO order, most
  recently entered entry at the top. For the elements with the date_id being
  the same, they are not in LIFO order. I understand that I can add another
  incrementing index column and sort the table based on that. But, without adding this,
  does postgresql have any method/configuration to get me output in LIFO order ?
  And are there any better methods available compared to adding another index
  column (as mentioned above) ?

Thanks,
Ethan

[GENERAL] hopefully a brain teaser, can't quite figure out query

Hi guys, maybe this is just a teaser for me, but any help would be
awesome. My best crack at the solution is not returning yet after a
good ten minutes. I'll post the explain analyze if it ever comes
back. I have no indexing, which is probably embarrassing, I'm just
not quite sure what to index or really how.

So, I've got two tables, which I'm going to try to simplify and still
get across:

The small table is a listing of county fips codes, their name, and the
geometry for the county. Each fips is only listed once. The big table
is multiple emissions for each county, the parameter for the emission,
and the source code for the emission (scc). Each county in big tbale
has many entries, variable number of pollutant types, variable number
of scc's.

small table:
fips (int), name(string), geom(geometry)
123, "some county", "some geometry"
124, "some other county", "some other geometry"
etc.

big table:
fips (int), pollutant(string), value(double), scc(int)
123, "co", 1000, 1000
123, "co", 1500, 1000
123, "co", 500, 1001
123, "co", 550, 1001
123, "co", 1500, 1002
123, "co", 50, 1002

123, "so2", 1100, 1000
123, "so2", 510, 1001
123, "so2", 1510, 1002
etc.

So the user supplies the pollutant, a number of scc's, and a minimum
value.
I need to select all the fips from the small table, as well as the sum
of values in the big table (for that pollutant and scc codes) WHERE
the sum of the values in the big table (for that pollutant and those
scc codes) are larger than the given value.

So, for the above, say the user picked "CO" for pollutant, 1001 and
1002 for SCC.
the rows in big table with 1001 OR 1002 for scc AND "co" for pollutant
are:
123, "co", 500, 1001
123, "co", 550, 1001
123, "co", 1500, 1002
123, "co", 50, 1002

I would return the 123 fips ONLY if the value provided was less than
the sum of the values for all scc's (500+550+1500+50 = 2600), as well
as the sum for those values.

so, return set would be
fips, name, value
123, "some county", 2600

for each fips in small table...

Boy I wonder if that makes sense, maybe some pseudo SQL speak would be
better:

SELECT small.fips, small.name, sum(big.value)
FROM small, big
WHERE
small.fips in (
SELECT fips from big
WHERE ((pollutant='co') AND
(
(scc LIKE '21%') OR (scc LIKE '2301%') OR (scc LIKE '2801000000%')
)
HAVING SUM(value > 2000)
)
GROUP BY small.fips, small.name;

This is the query that isn't returning yet.
If anyone has any questions, comments, or any suggestions at all, I'll
do my best to respond ASAP.
Any help is extremely appreciated!
-Ed

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

Thursday, June 5, 2008

Re: [pgsql-es-ayuda] Leer ficheros con postgres

On Thu, Jun 5, 2008 at 11:28 AM, Alvaro Herrera
<alvherre@commandprompt.com> wrote:
> Jaime Casanova escribió:
>
>> oops, disculpen el top-posting pero estaba en una ipaq y no veia a
>> donde iba a parar el texto del mensaje que se estaba contestando
>
> Está bueno el trabajo de soporte y capacitación de PG en Ecuador parece,
> que andas probando juguetitos nuevos? ;-)
>

Te dire que me estoy enterando que hay algunas empresas usando
postgres aqui en Ecuador asi que se ven buenas perspectivas... pero la
ipaq me la mando de chile mi hermano (les va bien a los medicos
ecuatorianos en chile :)


--
Atentamente,
Jaime Casanova
Soporte y capacitación de PostgreSQL
Guayaquil - Ecuador
Cel. (593) 87171157
--
TIP 3: Si encontraste la respuesta a tu problema, publícala, otros te lo agradecerán

[PATCHES] array_fill function

*** ./src/backend/utils/adt/arrayfuncs.c.orig 2008-06-05 08:16:09.000000000 +0200
--- ./src/backend/utils/adt/arrayfuncs.c 2008-06-06 05:56:56.000000000 +0200
***************
*** 95,100 ****
--- 95,105 ----
int *st, int *endp,
int typlen, bool typbyval, char typalign);
static int array_cmp(FunctionCallInfo fcinfo);
+ static ArrayType *create_array_envelope(int ndims, int *dimv, int *lbv, int nbytes,
+ Oid elmtype, int dataoffset);
+ static ArrayType *array_fill_internal(ArrayType *dims, ArrayType *lbs, Datum value,
+ Oid elmtype, bool isnull,
+ FunctionCallInfo fcinfo);


/*
***************
*** 4314,4316 ****
--- 4319,4590 ----
/* just call the other one -- it can handle both cases */
return generate_subscripts(fcinfo);
}
+
+ /*
+ * array_fill_with_lower_bounds
+ * Create and fill array with defined lower bounds.
+ */
+ Datum
+ array_fill_with_lower_bounds(PG_FUNCTION_ARGS)
+ {
+ ArrayType *dims;
+ ArrayType *lbs;
+ ArrayType *result;
+ Oid elmtype;
+ Datum value;
+ bool isnull;
+
+ if (PG_ARGISNULL(1) || PG_ARGISNULL(2))
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("dimension array or low bound array cannot be NULL")));
+
+ dims = PG_GETARG_ARRAYTYPE_P(1);
+ lbs = PG_GETARG_ARRAYTYPE_P(2);
+
+ if (!PG_ARGISNULL(0))
+ {
+ value = PG_GETARG_DATUM(0);
+ isnull = false;
+ }
+ else
+ {
+ value = 0;
+ isnull = true;
+ }
+
+ elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
+ if (!OidIsValid(elmtype))
+ elog(ERROR, "could not determine data type of input");
+
+ result = array_fill_internal(dims, lbs, value, elmtype, isnull, fcinfo);
+ PG_RETURN_ARRAYTYPE_P(result);
+ }
+
+ /*
+ * array_fill
+ * Create and fill array with default lower bounds.
+ */
+ Datum
+ array_fill(PG_FUNCTION_ARGS)
+ {
+ ArrayType *dims;
+ ArrayType *result;
+ Oid elmtype;
+ Datum value;
+ bool isnull;
+
+ if (PG_ARGISNULL(1))
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("dimension array or low bound array cannot be NULL")));
+
+ dims = PG_GETARG_ARRAYTYPE_P(1);
+
+ if (!PG_ARGISNULL(0))
+ {
+ value = PG_GETARG_DATUM(0);
+ isnull = false;
+ }
+ else
+ {
+ value = 0;
+ isnull = true;
+ }
+
+ elmtype = get_fn_expr_argtype(fcinfo->flinfo, 0);
+ if (!OidIsValid(elmtype))
+ elog(ERROR, "could not determine data type of input");
+
+ result = array_fill_internal(dims, NULL, value, elmtype, isnull, fcinfo);
+ PG_RETURN_ARRAYTYPE_P(result);
+ }
+
+ static ArrayType *
+ create_array_envelope(int ndims, int *dimv, int *lbsv, int nbytes,
+ Oid elmtype, int dataoffset)
+ {
+ ArrayType *result;
+
+ result = (ArrayType *) palloc0(nbytes);
+ SET_VARSIZE(result, nbytes);
+ result->ndim = ndims;
+ result->dataoffset = dataoffset;
+ result->elemtype = elmtype;
+ memcpy(ARR_DIMS(result), dimv, ndims * sizeof(int));
+ memcpy(ARR_LBOUND(result), lbsv, ndims * sizeof(int));
+
+ return result;
+ }
+
+ static ArrayType *
+ array_fill_internal(ArrayType *dims, ArrayType *lbs, Datum value,
+ Oid elmtype, bool isnull,
+ FunctionCallInfo fcinfo)
+ {
+ ArrayType *result;
+ int *dimv;
+ int *lbsv;
+ int ndims;
+ int nitems;
+ int deflbs[MAXDIM];
+ int16 elmlen;
+ bool elmbyval;
+ char elmalign;
+ ArrayMetaState *my_extra;
+
+ /*
+ * Params checks
+ */
+ if (ARR_NDIM(dims) != 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+ errmsg("wrong number of array subscripts"),
+ errhint("dimension array should be one dimensional")));
+
+ if (ARR_LBOUND(dims)[0] != 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+ errmsg("wrong range of array_subscripts"),
+ errhint("lbound of dimension array is different than one")));
+
+ if (ARR_HASNULL(dims))
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("dimension values cannot be null")));
+
+ dimv = (int *) ARR_DATA_PTR(dims);
+ ndims = ARR_DIMS(dims)[0];
+
+ if (ndims < 0) /* we do allow zero-dimension arrays */
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("invalid number of dimensions: %d", ndims)));
+ if (ndims > MAXDIM)
+ ereport(ERROR,
+ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
+ ndims, MAXDIM)));
+
+ if (lbs != NULL)
+ {
+ if (ARR_NDIM(lbs) != 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+ errmsg("wrong number of array subscripts"),
+ errhint("dimension array should be one dimensional")));
+
+ if (ARR_LBOUND(lbs)[0] != 1)
+ ereport(ERROR,
+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+ errmsg("wrong range of array_subscripts"),
+ errhint("lbound of dimension array is different than one")));
+
+ if (ARR_HASNULL(lbs))
+ ereport(ERROR,
+ (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
+ errmsg("dimension values cannot be null")));
+
+ if (ARR_DIMS(lbs)[0] != ndims)
+ ereport(ERROR,
+ (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
+ errmsg("wrong number of array_subscripts"),
+ errhint("Low bound array has different size than dimensions array.")));
+
+ lbsv = (int *) ARR_DATA_PTR(lbs);
+ }
+ else
+ {
+ int i;
+
+ for (i = 0; i < MAXDIM; i++)
+ deflbs[i] = 1;
+
+ lbsv = deflbs;
+ }
+
+ /* fast track for empty array */
+ if (ndims == 0)
+ return construct_empty_array(elmtype);
+
+ nitems = ArrayGetNItems(ndims, dimv);
+
+
+ /*
+ * We arrange to look up info about element type only once per series of
+ * calls, assuming the element type doesn't change underneath us.
+ */
+ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
+ if (my_extra == NULL)
+ {
+ fcinfo->flinfo->fn_extra = MemoryContextAlloc(fcinfo->flinfo->fn_mcxt,
+ sizeof(ArrayMetaState));
+ my_extra = (ArrayMetaState *) fcinfo->flinfo->fn_extra;
+ my_extra->element_type = InvalidOid;
+ }
+
+ if (my_extra->element_type != elmtype)
+ {
+ /* Get info about element type */
+ get_typlenbyvalalign(elmtype,
+ &my_extra->typlen,
+ &my_extra->typbyval,
+ &my_extra->typalign);
+ my_extra->element_type = elmtype;
+ }
+
+ elmlen = my_extra->typlen;
+ elmbyval = my_extra->typbyval;
+ elmalign = my_extra->typalign;
+
+ /* compute required space */
+ if (!isnull)
+ {
+ int i;
+ char *p;
+ int nbytes;
+ Datum aux_value = value;
+
+ /* make sure data is not toasted */
+ if (elmlen == -1)
+ value = PointerGetDatum(PG_DETOAST_DATUM(value));
+
+ nbytes = att_addlength_datum(0, elmlen, value);
+ nbytes = att_align_nominal(nbytes, elmalign);
+
+ nbytes *= nitems;
+ /* check for overflow of total request */
+ if (!AllocSizeIsValid(nbytes))
+ ereport(ERROR,
+ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+ errmsg("array size exceeds the maximum allowed (%d)",
+ (int) MaxAllocSize)));
+
+ nbytes += ARR_OVERHEAD_NONULLS(ndims);
+ result = create_array_envelope(ndims, dimv, lbsv, nbytes,
+ elmtype, 0);
+ p = ARR_DATA_PTR(result);
+ for (i = 0; i < nitems; i++)
+ p += ArrayCastAndSet(value, elmlen, elmbyval, elmalign, p);
+
+ /* cleaning up detoasted copies of datum */
+ if (aux_value != value)
+ pfree((Pointer) value);
+ }
+ else
+ {
+ int nbytes;
+ int dataoffset;
+ bits8 *bitmap;
+
+ dataoffset = ARR_OVERHEAD_WITHNULLS(ndims, nitems);
+ nbytes = dataoffset;
+
+ result = create_array_envelope(ndims, dimv, lbsv, nbytes,
+ elmtype, dataoffset);
+ bitmap = ARR_NULLBITMAP(result);
+ MemSet(bitmap, 0, (nitems + 7) / 8);
+ }
+
+ return result;
+ }
*** ./src/include/catalog/pg_proc.h.orig 2008-06-05 08:39:47.000000000 +0200
--- ./src/include/catalog/pg_proc.h 2008-06-06 05:32:06.000000000 +0200
***************
*** 1014,1021 ****
DESCR("array subscripts generator");
DATA(insert OID = 1192 ( generate_subscripts PGNSP PGUID 12 1 1000 f f t t i 2 23 "2277 23" _null_ _null_ _null_ generate_subscripts_nodir - _null_ _null_ ));
DESCR("array subscripts generator");
!
!
DATA(insert OID = 760 ( smgrin PGNSP PGUID 12 1 0 f f t f s 1 210 "2275" _null_ _null_ _null_ smgrin - _null_ _null_ ));
DESCR("I/O");
DATA(insert OID = 761 ( smgrout PGNSP PGUID 12 1 0 f f t f s 1 2275 "210" _null_ _null_ _null_ smgrout - _null_ _null_ ));
--- 1014,1023 ----
DESCR("array subscripts generator");
DATA(insert OID = 1192 ( generate_subscripts PGNSP PGUID 12 1 1000 f f t t i 2 23 "2277 23" _null_ _null_ _null_ generate_subscripts_nodir - _null_ _null_ ));
DESCR("array subscripts generator");
! DATA(insert OID = 1193 ( array_fill PGNSP PGUID 12 1 0 f f f f i 2 2277 "2283 1007" _null_ _null_ _null_ array_fill - _null_ _null_ ));
! DESCR("array constructor with value");
! DATA(insert OID = 1286 ( array_fill PGNSP PGUID 12 1 0 f f f f i 3 2277 "2283 1007 1007" _null_ _null_ _null_ array_fill_with_lower_bounds - _null_ _null_ ));
! DESCR("array constructor with value");
DATA(insert OID = 760 ( smgrin PGNSP PGUID 12 1 0 f f t f s 1 210 "2275" _null_ _null_ _null_ smgrin - _null_ _null_ ));
DESCR("I/O");
DATA(insert OID = 761 ( smgrout PGNSP PGUID 12 1 0 f f t f s 1 2275 "210" _null_ _null_ _null_ smgrout - _null_ _null_ ));
*** ./src/include/utils/array.h.orig 2008-06-05 08:33:30.000000000 +0200
--- ./src/include/utils/array.h 2008-06-05 08:34:55.000000000 +0200
***************
*** 202,207 ****
--- 202,209 ----
extern Datum array_smaller(PG_FUNCTION_ARGS);
extern Datum generate_subscripts(PG_FUNCTION_ARGS);
extern Datum generate_subscripts_nodir(PG_FUNCTION_ARGS);
+ extern Datum array_fill(PG_FUNCTION_ARGS);
+ extern Datum array_fill_with_lower_bounds(PG_FUNCTION_ARGS);

extern Datum array_ref(ArrayType *array, int nSubscripts, int *indx,
int arraytyplen, int elmlen, bool elmbyval, char elmalign,
*** ./src/test/regress/expected/arrays.out.orig 2008-06-06 06:05:05.000000000 +0200
--- ./src/test/regress/expected/arrays.out 2008-06-06 06:03:32.000000000 +0200
***************
*** 933,935 ****
--- 933,993 ----

drop function unnest1(anyarray);
drop function unnest2(anyarray);
+ select array_fill(null::integer, array[3,3],array[2,2]);
+ array_fill
+ -----------------------------------------------------------------
+ [2:4][2:4]={{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
+ (1 row)
+
+ select array_fill(null::integer, array[3,3]);
+ array_fill
+ ------------------------------------------------------
+ {{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
+ (1 row)
+
+ select array_fill(null::text, array[3,3],array[2,2]);
+ array_fill
+ -----------------------------------------------------------------
+ [2:4][2:4]={{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
+ (1 row)
+
+ select array_fill(null::text, array[3,3]);
+ array_fill
+ ------------------------------------------------------
+ {{NULL,NULL,NULL},{NULL,NULL,NULL},{NULL,NULL,NULL}}
+ (1 row)
+
+ select array_fill(7, array[3,3],array[2,2]);
+ array_fill
+ --------------------------------------
+ [2:4][2:4]={{7,7,7},{7,7,7},{7,7,7}}
+ (1 row)
+
+ select array_fill(7, array[3,3]);
+ array_fill
+ ---------------------------
+ {{7,7,7},{7,7,7},{7,7,7}}
+ (1 row)
+
+ select array_fill('juhu'::text, array[3,3],array[2,2]);
+ array_fill
+ -----------------------------------------------------------------
+ [2:4][2:4]={{juhu,juhu,juhu},{juhu,juhu,juhu},{juhu,juhu,juhu}}
+ (1 row)
+
+ select array_fill('juhu'::text, array[3,3]);
+ array_fill
+ ------------------------------------------------------
+ {{juhu,juhu,juhu},{juhu,juhu,juhu},{juhu,juhu,juhu}}
+ (1 row)
+
+ -- raise exception
+ select array_fill(1, null, array[2,2]);
+ ERROR: dimension array or low bound array cannot be NULL
+ select array_fill(1, array[2,2], null);
+ ERROR: dimension array or low bound array cannot be NULL
+ select array_fill(1, array[3,3], array[1,1,1]);
+ ERROR: wrong number of array_subscripts
+ HINT: Low bound array has different size than dimensions array.
+ select array_fill(1, array[1,2,null]);
+ ERROR: dimension values cannot be null
*** ./src/test/regress/sql/arrays.sql.orig 2008-06-06 05:59:32.000000000 +0200
--- ./src/test/regress/sql/arrays.sql 2008-06-06 06:02:32.000000000 +0200
***************
*** 357,359 ****
--- 357,373 ----

drop function unnest1(anyarray);
drop function unnest2(anyarray);
+
+ select array_fill(null::integer, array[3,3],array[2,2]);
+ select array_fill(null::integer, array[3,3]);
+ select array_fill(null::text, array[3,3],array[2,2]);
+ select array_fill(null::text, array[3,3]);
+ select array_fill(7, array[3,3],array[2,2]);
+ select array_fill(7, array[3,3]);
+ select array_fill('juhu'::text, array[3,3],array[2,2]);
+ select array_fill('juhu'::text, array[3,3]);
+ -- raise exception
+ select array_fill(1, null, array[2,2]);
+ select array_fill(1, array[2,2], null);
+ select array_fill(1, array[3,3], array[1,1,1]);
+ select array_fill(1, array[1,2,null]);
Hello

Proposal: http://archives.postgresql.org/pgsql-hackers/2008-06/msg00057.php

I changed name to array_fill and order of arguments.

postgres=# SELECT array_fill(0, ARRAY[2,3]);
array_fill
-------------------
{{0,0,0},{0,0,0}}
(1 row)

postgres=# SELECT array_fill(0, ARRAY[2,3], ARRAY[1,2]);
array_fill
------------------------------
[1:2][2:4]={{0,0,0},{0,0,0}}
(1 row)

postgres=# SELECT array_fill(0, ARRAY[4], ARRAY[2]);
array_fill
-----------------
[2:5]={0,0,0,0}
(1 row)

postgres=# SELECT array_fill(NULL::int, ARRAY[4]);
array_fill
-----------------------
{NULL,NULL,NULL,NULL}
(1 row)

Regards
Pavel Stehule