Sunday, August 31, 2008

Re: [pgsql-fr-generale] ERREUR: "$3" is declared CONSTANT

Très intéressant !

Cette liste est une source de bonheur ! :D

Merci :)

Le dimanche 31 août 2008 à 23:10 +0200, Guillaume Lelarge a écrit :
> Samuel ROZE a écrit :
> > [...]
> > Maintenant, voici le code de ma fonction "contact" :
> >
> > -------------------------
> > CREATE OR REPLACE FUNCTION clients.contact (p_nom text, p_email text,
> > p_t integer) RETURNS integer AS $contact$
> > DECLARE
> > v_id integer DEFAULT 0;
> > BEGIN
> > IF (p_t != 0) THEN
> > p_t := 1;
> > END IF;
> > SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> > email = p_email LIMIT 1;
> > IF NOT FOUND THEN
> > INSERT INTO clients.contacts (nom, email, _trigger) VALUES
> > (p_nom, p_email, p_t);
> > SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> > email = p_email LIMIT 1;
> > END IF;
> > RETURN v_id;
> > END;
> > $contact$ language plpgsql;
> > -------------------------
> >
>
> Rien à voir avec ta question, mais juste pour infos, si tu utilises une
> version 8.2 ou supérieure, tu peux remplacer :
>
> INSERT INTO clients.contacts (nom, email, _trigger) VALUES (p_nom,
> p_email, p_t);
> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> email = p_email LIMIT 1;
>
> par
>
> INSERT INTO clients.contacts (nom, email, _trigger) VALUES (p_nom,
> p_email, p_t) RETURNING id INTO v_id;
>
>


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

Re: [GENERAL] Oracle and Postgresql

On Sun, Aug 31, 2008 at 1:50 PM, Kevin Hunter <hunteke@earlham.edu> wrote:

> 7. Though I don't personally buy it, I have heard others complain
> loudly that there is no print-version of Postgres documentation.


This one should be taken off the list. The postgresql online
reference manual is in print( volumes 1 - 3)
http://www.amazon.com/PostgreSQL-Reference-Manual-SQL-Language/dp/0954612027/ref=pd_sim_b_1


--
Regards,
Richard Broersma Jr.

Visit the Los Angeles PostgreSQL Users Group (LAPUG)
http://pugs.postgresql.org/lapug

--
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-fr-generale] ERREUR: "$3" is declared CONSTANT

Samuel ROZE a écrit :
> [...]
> Maintenant, voici le code de ma fonction "contact" :
>
> -------------------------
> CREATE OR REPLACE FUNCTION clients.contact (p_nom text, p_email text,
> p_t integer) RETURNS integer AS $contact$
> DECLARE
> v_id integer DEFAULT 0;
> BEGIN
> IF (p_t != 0) THEN
> p_t := 1;
> END IF;
> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> email = p_email LIMIT 1;
> IF NOT FOUND THEN
> INSERT INTO clients.contacts (nom, email, _trigger) VALUES
> (p_nom, p_email, p_t);
> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> email = p_email LIMIT 1;
> END IF;
> RETURN v_id;
> END;
> $contact$ language plpgsql;
> -------------------------
>

Rien à voir avec ta question, mais juste pour infos, si tu utilises une
version 8.2 ou supérieure, tu peux remplacer :

INSERT INTO clients.contacts (nom, email, _trigger) VALUES (p_nom,
p_email, p_t);
SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
email = p_email LIMIT 1;

par

INSERT INTO clients.contacts (nom, email, _trigger) VALUES (p_nom,
p_email, p_t) RETURNING id INTO v_id;


--
Guillaume.
http://www.postgresqlfr.org
http://dalibo.com

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

[PATCHES] [PgFoundry] Unsigned Data Types [2 of 2]

Attached are the regression tests for the Unsigned integer data type.

Thanks,

- Ryan


Re: [GENERAL] Oracle and Postgresql

At 2:29pm -0400 on Sun, 31 Aug 2008, Srinivas wrote:
> I want to compare both of them in terms of functionality, performance,
> advantages and disadvantages.

If you publish anything, watch out for the Oracle licensing no-nos.
Specifically, I believe they disallow certain comparisons. I believe
performance is one of them.

> Why most enterprises prefer Oracle than Postgres even though it is
> free and has a decent enough user community.

Many reasons, some legit, some not. I expect a Greg or two will
seriously add to and correct this list, but:

1. Oracle was "first", and has vendor lock-in momentum.
2. Oracle is still the "de facto" in terms of
speed/performance/concurrency (but that gap is closing fast)
3. Oracle has application lock-in as well. There've more than a few
threads on this list regarding which applications.
4. Oracle is company-backed, so there is ostensibly "someone to blame"
or sue if something goes wrong. Don't underestimate the managerial
"need" for blame.
5. Influencing individuals within a company may prefer it *because* it's
expensive, as it helps "justify" their higher salary.
6. Mucho better advertising to the right people. Much harder for an
open source project to fund advertising to the same level.
7. Though I don't personally buy it, I have heard others complain
loudly that there is no print-version of Postgres documentation.

There's a starting list.

Kevin

--
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] Oracle and Postgresql

On Sun, Aug 31, 2008 at 12:29 PM, M2Y <mailtoyahoo@gmail.com> wrote:
> Hello,
>
> I am a CS graduate and I have a brief idea of Postgres and Oracle.
> But, I dont have an in-depth knowledge in any of them. I have a couple
> of questions and
>
> I want to compare both of them in terms of functionality, performance,
> advantages and disadvantages.
>
> Why most enterprises prefer Oracle than Postgres even though it is
> free and has a decent enough user community.

I got started using PostgreSQL for a "throw away" project. One that
needed to be done fast and cheap and if it didn't work out it was ok,
because we were only gonna spend a week or so setting it up. After
setting up pgsql to handle the single project, we started building
more things for that server, and it eventually grew into the corporate
intranet server, backending other apaches behind it, handling LDAP
auth for all the major apps in the company, storing files for
different groups, especially files that needed to be on the corporate
intranet, and running postgresql in the background too.

With that kind of project, free often wins out because it lowers your
cost of ownership on a low budget project.

When you get into the multi-million dollar integration projects
involving every sub group in an organization the budget is often huge,
and the bosses want something they've heard of / seen in action and
know can handle the load. A bad db choice could sink the whole
multi-million dollar project. A $200k insurance policy (I.e. Oracle)
is a small price to pay.

I think some of it is inertia. We've always used Oracle, let's just
keep on using it. The more conservative the IT department is, the
less likely they are to take chances with new technology.

It used to be there was about an 80/20 split between what things you
could do with either postgresql or oracle, and the other 20% was
oracle only land. I think that number is dropping quickly, and we're
into the 1 or 2% club of what Oracle can do that PostgreSQL isn't fast
enough for.

The other thing that holds back PostgreSQL right now is a lack of
experienced pgsql DBAs and application developers. That will change
over time.

As more people become familiar with using and maintaining pg servers,
and the usage starts to take up, there will be a multiplying effect as
more PHBs hear the name with good things said about it.

--
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] Oracle and Postgresql

On Sun, Aug 31, 2008 at 11:29:32AM -0700, M2Y wrote:
> Hello,
>
> I am a CS graduate and I have a brief idea of Postgres and Oracle.
> But, I dont have an in-depth knowledge in any of them. I have a
> couple of questions and
>
> I want to compare both of them in terms of functionality,
> performance, advantages and disadvantages.
>
> Why most enterprises prefer Oracle than Postgres even though it is
> free and has a decent enough user community.

That depends which enterprises. At the moment, people who know
Postgres are not common, which gives them advantages in negotiations.

Cheers,
David.
--
David Fetter <david@fetter.org> http://fetter.org/
Phone: +1 415 235 3778 AIM: dfetter666 Yahoo!: dfetter
Skype: davidfetter XMPP: david.fetter@gmail.com

Remember to vote!
Consider donating to Postgres: http://www.postgresql.org/about/donate

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

[PATCHES] [PgFoundry] Unsigned Data Types [1 of 2]

Hello all,


I have attempted to send this email 3 times over the last 24 hours.
I am not sure what is blocking it, so I am going to break it up into two parts:

   uint-base.tar.bz2  -- The core of the unsigned integer type.
   uint-tests.tar.bz2  -- The regression tests.

I am suspecting a size limit problem, so I am including the uint-tests.tar.bz2 in a separate email.

I have attached version 2 of the Unsigned Data Types patch.

ChangeLog:
   * Converted build system to use PGXS (more portable).
   * Added an uninstall script.
   * Miscellaneous code cleanups.
   * Folded my unit testing into the PGXS regression test suite.
   * Added support for HASH indexes.
   * Added support for bit operations.

I will update the commit-fest wiki to point to this new patch (assuming this message gets through).

Thanks!

- Ryan


Re: [PATCHES] [HACKERS] Infrastructure changes for recovery

Index: src/backend/access/transam/xlog.c
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/backend/access/transam/xlog.c,v
retrieving revision 1.317
diff -c -r1.317 xlog.c
*** src/backend/access/transam/xlog.c 11 Aug 2008 11:05:10 -0000 1.317
--- src/backend/access/transam/xlog.c 31 Aug 2008 19:07:40 -0000
***************
*** 131,137 ****
static bool recoveryTarget = false;
static bool recoveryTargetExact = false;
static bool recoveryTargetInclusive = true;
- static bool recoveryLogRestartpoints = false;
static TransactionId recoveryTargetXid;
static TimestampTz recoveryTargetTime;
static TimestampTz recoveryLastXTime = 0;
--- 131,136 ----
***************
*** 386,392 ****
static XLogRecord *nextRecord = NULL;
static TimeLineID lastPageTLI = 0;

! static bool InRedo = false;


static void XLogArchiveNotify(const char *xlog);
--- 385,391 ----
static XLogRecord *nextRecord = NULL;
static TimeLineID lastPageTLI = 0;

! bool InRedo = false;


static void XLogArchiveNotify(const char *xlog);
***************
*** 480,485 ****
--- 479,488 ----
bool doPageWrites;
bool isLogSwitch = (rmid == RM_XLOG_ID && info == XLOG_SWITCH);

+ /* cross-check on whether we should be here or not */
+ if (InRedo)
+ elog(FATAL, "cannot write new WAL data during recovery mode");
+
/* info's high bits are reserved for use by me */
if (info & XLR_INFO_MASK)
elog(PANIC, "invalid xlog info mask %02X", info);
***************
*** 2051,2057 ****
unlink(tmppath);
}

! elog(DEBUG2, "done creating and filling new WAL file");

/* Set flag to tell caller there was no existent file */
*use_existent = false;
--- 2054,2061 ----
unlink(tmppath);
}

! XLogFileName(tmppath, ThisTimeLineID, log, seg);
! elog(DEBUG2, "done creating and filling new WAL file %s", tmppath);

/* Set flag to tell caller there was no existent file */
*use_existent = false;
***************
*** 4532,4546 ****
}
else if (strcmp(tok1, "log_restartpoints") == 0)
{
- /*
- * does nothing if a recovery_target is not also set
- */
- if (!parse_bool(tok2, &recoveryLogRestartpoints))
- ereport(ERROR,
- (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
- errmsg("parameter \"log_restartpoints\" requires a Boolean value")));
ereport(LOG,
! (errmsg("log_restartpoints = %s", tok2)));
}
else
ereport(FATAL,
--- 4536,4544 ----
}
else if (strcmp(tok1, "log_restartpoints") == 0)
{
ereport(LOG,
! (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
! errmsg("parameter \"log_restartpoints\" has been deprecated")));
}
else
ereport(FATAL,
***************
*** 4811,4816 ****
--- 4809,4815 ----
CheckPoint checkPoint;
bool wasShutdown;
bool reachedStopPoint = false;
+ bool reachedSafeStopPoint = false;
bool haveBackupLabel = false;
XLogRecPtr RecPtr,
LastRec,
***************
*** 5039,5044 ****
--- 5038,5048 ----
UpdateControlFile();

/*
+ * Reset pgstat data, because it may be invalid after recovery.
+ */
+ pgstat_reset_all();
+
+ /*
* If there was a backup label file, it's done its job and the info
* has now been propagated into pg_control. We must get rid of the
* label file so that if we crash during recovery, we'll pick up at
***************
*** 5148,5153 ****
--- 5152,5172 ----

LastRec = ReadRecPtr;

+ /*
+ * Have we reached our safe stopping point? If so, we can
+ * signal Postmaster to enter consistent recovery mode
+ */
+ if (!reachedSafeStopPoint &&
+ XLByteLE(ControlFile->minRecoveryPoint, EndRecPtr))
+ {
+ reachedSafeStopPoint = true;
+ ereport(LOG,
+ (errmsg("consistent recovery state reached at %X/%X",
+ EndRecPtr.xlogid, EndRecPtr.xrecoff)));
+ if (IsUnderPostmaster)
+ SendPostmasterSignal(PMSIGNAL_RECOVERY_START);
+ }
+
record = ReadRecord(NULL, LOG);
} while (record != NULL && recoveryContinue);

***************
*** 5169,5174 ****
--- 5188,5194 ----
/* there are no WAL records following the checkpoint */
ereport(LOG,
(errmsg("redo is not required")));
+ reachedSafeStopPoint = true;
}
}

***************
*** 5184,5190 ****
* Complain if we did not roll forward far enough to render the backup
* dump consistent.
*/
! if (XLByteLT(EndOfLog, ControlFile->minRecoveryPoint))
{
if (reachedStopPoint) /* stopped because of stop request */
ereport(FATAL,
--- 5204,5210 ----
* Complain if we did not roll forward far enough to render the backup
* dump consistent.
*/
! if (InRecovery && !reachedSafeStopPoint)
{
if (reachedStopPoint) /* stopped because of stop request */
ereport(FATAL,
***************
*** 5305,5314 ****
*/
XLogCheckInvalidPages();

! /*
! * Reset pgstat data, because it may be invalid after recovery.
! */
! pgstat_reset_all();

/*
* Perform a checkpoint to update all our recovery activity to disk.
--- 5325,5332 ----
*/
XLogCheckInvalidPages();

! if (IsUnderPostmaster)
! BgWriterCompleteRestartPointImmediately();

/*
* Perform a checkpoint to update all our recovery activity to disk.
***************
*** 5318,5323 ****
--- 5336,5344 ----
* assigning a new TLI, using a shutdown checkpoint allows us to have
* the rule that TLI only changes in shutdown checkpoints, which
* allows some extra error checking in xlog_redo.
+ *
+ * Note that this will wait behind any restartpoint that the bgwriter
+ * is currently performing, though will be much faster as a result.
*/
CreateCheckPoint(CHECKPOINT_IS_SHUTDOWN | CHECKPOINT_IMMEDIATE);
}
***************
*** 5372,5377 ****
--- 5393,5401 ----
readRecordBuf = NULL;
readRecordBufSize = 0;
}
+
+ if (IsUnderPostmaster)
+ BgWriterRecoveryComplete();
}

/*
***************
*** 5642,5648 ****
* Log end of a checkpoint.
*/
static void
! LogCheckpointEnd(void)
{
long write_secs,
sync_secs,
--- 5666,5672 ----
* Log end of a checkpoint.
*/
static void
! LogCheckpointEnd(bool checkpoint)
{
long write_secs,
sync_secs,
***************
*** 5665,5673 ****
CheckpointStats.ckpt_sync_end_t,
&sync_secs, &sync_usecs);

! elog(LOG, "checkpoint complete: wrote %d buffers (%.1f%%); "
"%d transaction log file(s) added, %d removed, %d recycled; "
"write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
CheckpointStats.ckpt_bufs_written,
(double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
CheckpointStats.ckpt_segs_added,
--- 5689,5698 ----
CheckpointStats.ckpt_sync_end_t,
&sync_secs, &sync_usecs);

! elog(LOG, "%s complete: wrote %d buffers (%.1f%%); "
"%d transaction log file(s) added, %d removed, %d recycled; "
"write=%ld.%03d s, sync=%ld.%03d s, total=%ld.%03d s",
+ (checkpoint ? " checkpoint" : "restartpoint"),
CheckpointStats.ckpt_bufs_written,
(double) CheckpointStats.ckpt_bufs_written * 100 / NBuffers,
CheckpointStats.ckpt_segs_added,
***************
*** 6002,6008 ****

/* All real work is done, but log before releasing lock. */
if (log_checkpoints)
! LogCheckpointEnd();

LWLockRelease(CheckpointLock);
}
--- 6027,6033 ----

/* All real work is done, but log before releasing lock. */
if (log_checkpoints)
! LogCheckpointEnd(true);

LWLockRelease(CheckpointLock);
}
***************
*** 6071,6099 ****
}
}

/*
! * OK, force data out to disk
! */
! CheckPointGuts(checkPoint->redo, CHECKPOINT_IMMEDIATE);
!
! /*
! * Update pg_control so that any subsequent crash will restart from this
! * checkpoint. Note: ReadRecPtr gives the XLOG address of the checkpoint
! * record itself.
*/
ControlFile->prevCheckPoint = ControlFile->checkPoint;
ControlFile->checkPoint = ReadRecPtr;
ControlFile->checkPointCopy = *checkPoint;
ControlFile->time = (pg_time_t) time(NULL);
UpdateControlFile();

! ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
(errmsg("recovery restart point at %X/%X",
checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
! if (recoveryLastXTime)
! ereport((recoveryLogRestartpoints ? LOG : DEBUG2),
! (errmsg("last completed transaction was at log time %s",
! timestamptz_to_str(recoveryLastXTime))));
}

/*
--- 6096,6164 ----
}
}

+ if (recoveryLastXTime)
+ ereport((log_checkpoints ? LOG : DEBUG2),
+ (errmsg("last completed transaction was at log time %s",
+ timestamptz_to_str(recoveryLastXTime))));
/*
! * Update ControlFile data in shared memory.
! * Note: ReadRecPtr gives the XLOG address of the checkpoint record itself.
*/
+ LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
ControlFile->prevCheckPoint = ControlFile->checkPoint;
ControlFile->checkPoint = ReadRecPtr;
ControlFile->checkPointCopy = *checkPoint;
+ RequestRestartPoint();
+ LWLockRelease(ControlFileLock);
+ }
+
+ /*
+ * As of 8.4, RestartPoints are always created by the bgwriter
+ */
+ void
+ CreateRestartPoint(void)
+ {
+ CheckPoint *checkPoint;
+
+ if (log_checkpoints)
+ {
+ /*
+ * Prepare to accumulate statistics.
+ */
+
+ MemSet(&CheckpointStats, 0, sizeof(CheckpointStats));
+ CheckpointStats.ckpt_start_t = GetCurrentTimestamp();
+
+ elog(LOG, "restartpoint starting:");
+ }
+
+ LWLockAcquire(CheckpointLock, LW_EXCLUSIVE);
+
+ checkPoint = &ControlFile->checkPointCopy;
+
+ /*
+ * OK, write out dirty blocks smoothly
+ */
+ CheckPointGuts(checkPoint->redo, 0);
+
+ /*
+ * Update pg_control, using current time
+ */
+ LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);
ControlFile->time = (pg_time_t) time(NULL);
UpdateControlFile();
+ LWLockRelease(ControlFileLock);
+
+ /* All real work is done, but log before releasing lock. */
+ if (log_checkpoints)
+ LogCheckpointEnd(true);

! ereport((log_checkpoints ? LOG : DEBUG2),
(errmsg("recovery restart point at %X/%X",
checkPoint->redo.xlogid, checkPoint->redo.xrecoff)));
!
! LWLockRelease(CheckpointLock);
!
}

/*
Index: src/backend/postmaster/bgwriter.c
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/backend/postmaster/bgwriter.c,v
retrieving revision 1.51
diff -c -r1.51 bgwriter.c
*** src/backend/postmaster/bgwriter.c 11 Aug 2008 11:05:11 -0000 1.51
--- src/backend/postmaster/bgwriter.c 31 Aug 2008 19:45:39 -0000
***************
*** 122,127 ****
--- 122,129 ----
{
pid_t bgwriter_pid; /* PID of bgwriter (0 if not started) */

+ bool InRedo;
+
slock_t ckpt_lck; /* protects all the ckpt_* fields */

int ckpt_started; /* advances when checkpoint starts */
***************
*** 166,172 ****

/* these values are valid when ckpt_active is true: */
static pg_time_t ckpt_start_time;
! static XLogRecPtr ckpt_start_recptr;
static double ckpt_cached_elapsed;

static pg_time_t last_checkpoint_time;
--- 168,174 ----

/* these values are valid when ckpt_active is true: */
static pg_time_t ckpt_start_time;
! static XLogRecPtr ckpt_start_recptr; /* not used if InRedo */
static double ckpt_cached_elapsed;

static pg_time_t last_checkpoint_time;
***************
*** 186,191 ****
--- 188,208 ----
static void ReqCheckpointHandler(SIGNAL_ARGS);
static void ReqShutdownHandler(SIGNAL_ARGS);

+ /* notify bgwriter of change in mode */
+ void
+ BgWriterRecoveryComplete(void)
+ {
+ BgWriterShmem->InRedo = false;
+ elog(DEBUG1, "recovery complete");
+ }
+
+ /* ask bgwriter to complete any restartpoint, if any, with zero delay */
+ void
+ BgWriterCompleteRestartPointImmediately(void)
+ {
+ BgWriterShmem->ckpt_flags = CHECKPOINT_IMMEDIATE;
+ elog(DEBUG2, "asking bgwriter to complete any restartpoint with zero delay");
+ }

/*
* Main entry point for bgwriter process
***************
*** 202,207 ****
--- 219,230 ----
BgWriterShmem->bgwriter_pid = MyProcPid;
am_bg_writer = true;

+ /*
+ * Follow the postmaster's current mode at startup. If we are InRedo then
+ * the startup process will later tell us when it is complete.
+ */
+ BgWriterShmem->InRedo = InRedo;
+
/*
* If possible, make this process a group leader, so that the postmaster
* can signal any child processes too. (bgwriter probably never has any
***************
*** 356,371 ****
*/
PG_SETMASK(&UnBlockSig);

/*
* Loop forever
*/
for (;;)
{
- bool do_checkpoint = false;
- int flags = 0;
- pg_time_t now;
- int elapsed_secs;
-
/*
* Emergency bailout if postmaster has died. This is to avoid the
* necessity for manual cleanup of all postmaster children.
--- 379,393 ----
*/
PG_SETMASK(&UnBlockSig);

+ if (InRedo)
+ elog(DEBUG1, "bgwriter starting in recovery mode, pid = %u",
+ BgWriterShmem->bgwriter_pid);
+
/*
* Loop forever
*/
for (;;)
{
/*
* Emergency bailout if postmaster has died. This is to avoid the
* necessity for manual cleanup of all postmaster children.
***************
*** 383,501 ****
got_SIGHUP = false;
ProcessConfigFile(PGC_SIGHUP);
}
- if (checkpoint_requested)
- {
- checkpoint_requested = false;
- do_checkpoint = true;
- BgWriterStats.m_requested_checkpoints++;
- }
- if (shutdown_requested)
- {
- /*
- * From here on, elog(ERROR) should end with exit(1), not send
- * control back to the sigsetjmp block above
- */
- ExitOnAnyError = true;
- /* Close down the database */
- ShutdownXLOG(0, 0);
- DumpFreeSpaceMap(0, 0);
- /* Normal exit from the bgwriter is here */
- proc_exit(0); /* done */
- }
-
- /*
- * Force a checkpoint if too much time has elapsed since the last one.
- * Note that we count a timed checkpoint in stats only when this
- * occurs without an external request, but we set the CAUSE_TIME flag
- * bit even if there is also an external request.
- */
- now = (pg_time_t) time(NULL);
- elapsed_secs = now - last_checkpoint_time;
- if (elapsed_secs >= CheckPointTimeout)
- {
- if (!do_checkpoint)
- BgWriterStats.m_timed_checkpoints++;
- do_checkpoint = true;
- flags |= CHECKPOINT_CAUSE_TIME;
- }

! /*
! * Do a checkpoint if requested, otherwise do one cycle of
! * dirty-buffer writing.
! */
! if (do_checkpoint)
{
- /* use volatile pointer to prevent code rearrangement */
- volatile BgWriterShmemStruct *bgs = BgWriterShmem;
-
/*
! * Atomically fetch the request flags to figure out what kind of a
! * checkpoint we should perform, and increase the started-counter
! * to acknowledge that we've started a new checkpoint.
*/
! SpinLockAcquire(&bgs->ckpt_lck);
! flags |= bgs->ckpt_flags;
! bgs->ckpt_flags = 0;
! bgs->ckpt_started++;
! SpinLockRelease(&bgs->ckpt_lck);

! /*
! * We will warn if (a) too soon since last checkpoint (whatever
! * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
! * since the last checkpoint start. Note in particular that this
! * implementation will not generate warnings caused by
! * CheckPointTimeout < CheckPointWarning.
! */
! if ((flags & CHECKPOINT_CAUSE_XLOG) &&
! elapsed_secs < CheckPointWarning)
! ereport(LOG,
! (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
! elapsed_secs),
! errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));

! /*
! * Initialize bgwriter-private variables used during checkpoint.
! */
! ckpt_active = true;
! ckpt_start_recptr = GetInsertRecPtr();
! ckpt_start_time = now;
! ckpt_cached_elapsed = 0;

! /*
! * Do the checkpoint.
! */
! CreateCheckPoint(flags);

/*
! * After any checkpoint, close all smgr files. This is so we
! * won't hang onto smgr references to deleted files indefinitely.
*/
! smgrcloseall();

/*
! * Indicate checkpoint completion to any waiting backends.
*/
! SpinLockAcquire(&bgs->ckpt_lck);
! bgs->ckpt_done = bgs->ckpt_started;
! SpinLockRelease(&bgs->ckpt_lck);
!
! ckpt_active = false;

/*
! * Note we record the checkpoint start time not end time as
! * last_checkpoint_time. This is so that time-driven checkpoints
! * happen at a predictable spacing.
*/
! last_checkpoint_time = now;
! }
! else
! BgBufferSync();

! /* Check for archive_timeout and switch xlog files if necessary. */
! CheckArchiveTimeout();

! /* Nap for the configured time. */
! BgWriterNap();
}
}

--- 405,610 ----
got_SIGHUP = false;
ProcessConfigFile(PGC_SIGHUP);
}

! if (InRedo)
{
/*
! * Check to see whether startup process has completed redo.
! * If so, we can permanently change out of recovery mode.
*/
! if (BgWriterShmem->InRedo == false)
! {

! elog(LOG, "changing to InRedo = false");

! InitXLOGAccess();
! InRedo = false;

! /*
! * Start time-driven events from now
! */
! last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL);
! }
!
! if (checkpoint_requested)
! {
! /*
! * Initialize bgwriter-private variables used during checkpoint.
! */
! ckpt_active = true;
! ckpt_start_time = (pg_time_t) time(NULL);
! ckpt_cached_elapsed = 0;
!
! CreateRestartPoint();
!
! ckpt_active = false;
! checkpoint_requested = false;
! /*
! * Reset any flags if we requested immediate completion part
! * way through the restart point
! */
! BgWriterShmem->ckpt_flags = 0;
! }
! else
! {
! /* Clean buffers dirtied by recovery */
! BgBufferSync();
!
! /* Nap for the configured time. */
! BgWriterNap();
! }
!
! if (shutdown_requested)
! {
! /*
! * From here on, elog(ERROR) should end with exit(1), not send
! * control back to the sigsetjmp block above
! */
! ExitOnAnyError = true;
! /* Normal exit from the bgwriter is here */
! proc_exit(0); /* done */
! }

/*
! * Check to see whether startup process has completed redo.
! * If so, we can permanently change out of recovery mode.
*/
! if (BgWriterShmem->InRedo == false)
! {
! elog(DEBUG2, "changing to InRedo = false");
!
! InitXLOGAccess();
! InRedo = false;
!
! /*
! * Start time-driven events from now
! */
! last_checkpoint_time = last_xlog_switch_time = (pg_time_t) time(NULL);
! }
! }
! else /* Normal processing */
! {
! bool do_checkpoint = false;
! int flags = 0;
! pg_time_t now;
! int elapsed_secs;
!
! Assert(!InRedo);
!
! if (checkpoint_requested)
! {
! checkpoint_requested = false;
! do_checkpoint = true;
! BgWriterStats.m_requested_checkpoints++;
! }
! if (shutdown_requested)
! {
! /*
! * From here on, elog(ERROR) should end with exit(1), not send
! * control back to the sigsetjmp block above
! */
! ExitOnAnyError = true;
! /* Close down the database */
! ShutdownXLOG(0, 0);
! DumpFreeSpaceMap(0, 0);
! /* Normal exit from the bgwriter is here */
! proc_exit(0); /* done */
! }

/*
! * Force a checkpoint if too much time has elapsed since the last one.
! * Note that we count a timed checkpoint in stats only when this
! * occurs without an external request, but we set the CAUSE_TIME flag
! * bit even if there is also an external request.
*/
! now = (pg_time_t) time(NULL);
! elapsed_secs = now - last_checkpoint_time;
! if (elapsed_secs >= CheckPointTimeout)
! {
! if (!do_checkpoint)
! BgWriterStats.m_timed_checkpoints++;
! do_checkpoint = true;
! flags |= CHECKPOINT_CAUSE_TIME;
! }

/*
! * Do a checkpoint if requested, otherwise do one cycle of
! * dirty-buffer writing.
*/
! if (do_checkpoint)
! {
! /* use volatile pointer to prevent code rearrangement */
! volatile BgWriterShmemStruct *bgs = BgWriterShmem;
!
! /*
! * Atomically fetch the request flags to figure out what kind of a
! * checkpoint we should perform, and increase the started-counter
! * to acknowledge that we've started a new checkpoint.
! */
! SpinLockAcquire(&bgs->ckpt_lck);
! flags |= bgs->ckpt_flags;
! bgs->ckpt_flags = 0;
! bgs->ckpt_started++;
! SpinLockRelease(&bgs->ckpt_lck);
!
! /*
! * We will warn if (a) too soon since last checkpoint (whatever
! * caused it) and (b) somebody set the CHECKPOINT_CAUSE_XLOG flag
! * since the last checkpoint start. Note in particular that this
! * implementation will not generate warnings caused by
! * CheckPointTimeout < CheckPointWarning.
! */
! if ((flags & CHECKPOINT_CAUSE_XLOG) &&
! elapsed_secs < CheckPointWarning)
! ereport(LOG,
! (errmsg("checkpoints are occurring too frequently (%d seconds apart)",
! elapsed_secs),
! errhint("Consider increasing the configuration parameter \"checkpoint_segments\".")));
!
! /*
! * Initialize bgwriter-private variables used during checkpoint.
! */
! ckpt_active = true;
! ckpt_start_recptr = GetInsertRecPtr();
! ckpt_start_time = now;
! ckpt_cached_elapsed = 0;
!
! /*
! * Do the checkpoint.
! */
! CreateCheckPoint(flags);
!
! /*
! * After any checkpoint, close all smgr files. This is so we
! * won't hang onto smgr references to deleted files indefinitely.
! */
! smgrcloseall();
!
! /*
! * Indicate checkpoint completion to any waiting backends.
! */
! SpinLockAcquire(&bgs->ckpt_lck);
! bgs->ckpt_done = bgs->ckpt_started;
! SpinLockRelease(&bgs->ckpt_lck);
!
! ckpt_active = false;
!
! /*
! * Note we record the checkpoint start time not end time as
! * last_checkpoint_time. This is so that time-driven checkpoints
! * happen at a predictable spacing.
! */
! last_checkpoint_time = now;
! }
! else
! BgBufferSync();

! /* Check for archive_timeout and switch xlog files if necessary. */
! CheckArchiveTimeout();

! /* Nap for the configured time. */
! BgWriterNap();
! }
}
}

***************
*** 588,594 ****
(ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested))
break;
pg_usleep(1000000L);
! AbsorbFsyncRequests();
udelay -= 1000000L;
}

--- 697,704 ----
(ckpt_active ? ImmediateCheckpointRequested() : checkpoint_requested))
break;
pg_usleep(1000000L);
! if (!InRedo)
! AbsorbFsyncRequests();
udelay -= 1000000L;
}

***************
*** 642,647 ****
--- 752,770 ----
if (!am_bg_writer)
return;

+ /* Perform minimal duties during recovery and skip wait if requested */
+ if (InRedo)
+ {
+ BgBufferSync();
+
+ if (!ImmediateCheckpointRequested() &&
+ !shutdown_requested &&
+ IsCheckpointOnSchedule(progress))
+ BgWriterNap();
+
+ return;
+ }
+
/*
* Perform the usual bgwriter duties and take a nap, unless we're behind
* schedule, in which case we just try to catch up as quickly as possible.
***************
*** 716,731 ****
* However, it's good enough for our purposes, we're only calculating an
* estimate anyway.
*/
! recptr = GetInsertRecPtr();
! elapsed_xlogs =
! (((double) (int32) (recptr.xlogid - ckpt_start_recptr.xlogid)) * XLogSegsPerFile +
! ((double) recptr.xrecoff - (double) ckpt_start_recptr.xrecoff) / XLogSegSize) /
! CheckPointSegments;
!
! if (progress < elapsed_xlogs)
{
! ckpt_cached_elapsed = elapsed_xlogs;
! return false;
}

/*
--- 839,857 ----
* However, it's good enough for our purposes, we're only calculating an
* estimate anyway.
*/
! if (!InRedo)
{
! recptr = GetInsertRecPtr();
! elapsed_xlogs =
! (((double) (int32) (recptr.xlogid - ckpt_start_recptr.xlogid)) * XLogSegsPerFile +
! ((double) recptr.xrecoff - (double) ckpt_start_recptr.xrecoff) / XLogSegSize) /
! CheckPointSegments;
!
! if (progress < elapsed_xlogs)
! {
! ckpt_cached_elapsed = elapsed_xlogs;
! return false;
! }
}

/*
***************
*** 966,971 ****
--- 1092,1118 ----
}
}

+ void
+ RequestRestartPoint(void)
+ {
+ /*
+ * If in a standalone backend, just do it ourselves.
+ */
+ if (!IsPostmasterEnvironment)
+ {
+ CreateRestartPoint();
+ return;
+ }
+
+ /*
+ * Send signal to request restartpoint.
+ */
+ if (BgWriterShmem->bgwriter_pid == 0)
+ elog(LOG, "could not request restartpoint because bgwriter not running");
+ if (kill(BgWriterShmem->bgwriter_pid, SIGINT) != 0)
+ elog(LOG, "could not signal for restartpoint: %m");
+ }
+
/*
* ForwardFsyncRequest
* Forward a file-fsync request from a backend to the bgwriter
Index: src/backend/postmaster/postmaster.c
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/backend/postmaster/postmaster.c,v
retrieving revision 1.561
diff -c -r1.561 postmaster.c
*** src/backend/postmaster/postmaster.c 26 Jun 2008 02:47:19 -0000 1.561
--- src/backend/postmaster/postmaster.c 31 Aug 2008 17:10:31 -0000
***************
*** 254,259 ****
--- 254,264 ----
{
PM_INIT, /* postmaster starting */
PM_STARTUP, /* waiting for startup subprocess */
+ PM_RECOVERY, /* consistent recovery mode; state only
+ * entered for archive and streaming recovery,
+ * and only after the point where the
+ * all data is in consistent state.
+ */
PM_RUN, /* normal "database is alive" state */
PM_WAIT_BACKUP, /* waiting for online backup mode to end */
PM_WAIT_BACKENDS, /* waiting for live backends to exit */
***************
*** 2104,2110 ****
if (pid == StartupPID)
{
StartupPID = 0;
! Assert(pmState == PM_STARTUP);

/* FATAL exit of startup is treated as catastrophic */
if (!EXIT_STATUS_0(exitstatus))
--- 2109,2115 ----
if (pid == StartupPID)
{
StartupPID = 0;
! Assert(pmState == PM_STARTUP || pmState == PM_RECOVERY);

/* FATAL exit of startup is treated as catastrophic */
if (!EXIT_STATUS_0(exitstatus))
***************
*** 2136,2141 ****
--- 2141,2147 ----
* Otherwise, commence normal operations.
*/
pmState = PM_RUN;
+ InRedo = false;

/*
* Load the flat authorization file into postmaster's cache. The
***************
*** 2148,2155 ****
* Crank up the background writer. It doesn't matter if this
* fails, we'll just try again later.
*/
! Assert(BgWriterPID == 0);
! BgWriterPID = StartBackgroundWriter();

/*
* Likewise, start other special children as needed. In a restart
--- 2154,2161 ----
* Crank up the background writer. It doesn't matter if this
* fails, we'll just try again later.
*/
! if (BgWriterPID == 0)
! BgWriterPID = StartBackgroundWriter();

/*
* Likewise, start other special children as needed. In a restart
***************
*** 2812,2817 ****
--- 2818,2825 ----
*/
MyCancelKey = PostmasterRandom();

+ InRedo = (pmState != PM_RUN);
+
/*
* Make room for backend data structure. Better before the fork() so we
* can handle failure cleanly.
***************
*** 3821,3826 ****
--- 3829,3880 ----

PG_SETMASK(&BlockSig);

+ if (CheckPostmasterSignal(PMSIGNAL_RECOVERY_START))
+ {
+ Assert(pmState == PM_STARTUP);
+
+ /*
+ * Go to shutdown mode if a shutdown request was pending.
+ */
+ if (Shutdown > NoShutdown)
+ {
+ pmState = PM_WAIT_BACKENDS;
+ /* PostmasterStateMachine logic does the rest */
+ }
+ else
+ {
+ /*
+ * Startup process has entered recovery
+ */
+ pmState = PM_RECOVERY;
+ InRedo = true;
+
+ /*
+ * Load the flat authorization file into postmaster's cache. The
+ * startup process won't have recomputed this from the database yet,
+ * so we it may change following recovery.
+ */
+ load_role();
+
+ /*
+ * Crank up the background writer. It doesn't matter if this
+ * fails, we'll just try again later.
+ */
+ Assert(BgWriterPID == 0);
+ BgWriterPID = StartBackgroundWriter();
+
+ /*
+ * Likewise, start other special children as needed.
+ */
+ Assert(PgStatPID == 0);
+ PgStatPID = pgstat_start();
+
+ /* XXX at this point we could accept read-only connections */
+ ereport(DEBUG1,
+ (errmsg("database system is in consistent recovery mode")));
+ }
+ }
+
if (CheckPostmasterSignal(PMSIGNAL_PASSWORD_CHANGE))
{
/*
Index: src/include/miscadmin.h
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/include/miscadmin.h,v
retrieving revision 1.202
diff -c -r1.202 miscadmin.h
*** src/include/miscadmin.h 23 Apr 2008 13:44:59 -0000 1.202
--- src/include/miscadmin.h 31 Aug 2008 11:23:45 -0000
***************
*** 64,69 ****
--- 64,71 ----
*
*****************************************************************************/

+ extern bool InRedo;
+
/* in globals.c */
/* these are marked volatile because they are set by signal handlers: */
extern PGDLLIMPORT volatile bool InterruptPending;
Index: src/include/access/xlog.h
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/include/access/xlog.h,v
retrieving revision 1.88
diff -c -r1.88 xlog.h
*** src/include/access/xlog.h 12 May 2008 08:35:05 -0000 1.88
--- src/include/access/xlog.h 31 Aug 2008 13:33:43 -0000
***************
*** 205,210 ****
--- 205,211 ----
extern void ShutdownXLOG(int code, Datum arg);
extern void InitXLOGAccess(void);
extern void CreateCheckPoint(int flags);
+ extern void CreateRestartPoint(void);
extern void XLogPutNextOid(Oid nextOid);
extern XLogRecPtr GetRedoRecPtr(void);
extern XLogRecPtr GetInsertRecPtr(void);
Index: src/include/postmaster/bgwriter.h
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/include/postmaster/bgwriter.h,v
retrieving revision 1.12
diff -c -r1.12 bgwriter.h
*** src/include/postmaster/bgwriter.h 11 Aug 2008 11:05:11 -0000 1.12
--- src/include/postmaster/bgwriter.h 31 Aug 2008 15:35:30 -0000
***************
*** 25,36 ****
--- 25,40 ----
extern void BackgroundWriterMain(void);

extern void RequestCheckpoint(int flags);
+ extern void RequestRestartPoint(void);
extern void CheckpointWriteDelay(int flags, double progress);

extern bool ForwardFsyncRequest(RelFileNode rnode, ForkNumber forknum,
BlockNumber segno);
extern void AbsorbFsyncRequests(void);

+ extern void BgWriterRecoveryComplete(void);
+ extern void BgWriterCompleteRestartPointImmediately(void);
+
extern Size BgWriterShmemSize(void);
extern void BgWriterShmemInit(void);

Index: src/include/storage/pmsignal.h
===================================================================
RCS file: /home/sriggs/pg/REPOSITORY/pgsql/src/include/storage/pmsignal.h,v
retrieving revision 1.20
diff -c -r1.20 pmsignal.h
*** src/include/storage/pmsignal.h 19 Jun 2008 21:32:56 -0000 1.20
--- src/include/storage/pmsignal.h 31 Aug 2008 11:26:40 -0000
***************
*** 22,27 ****
--- 22,28 ----
*/
typedef enum
{
+ PMSIGNAL_RECOVERY_START, /* move to PM_RECOVERY state */
PMSIGNAL_PASSWORD_CHANGE, /* pg_auth file has changed */
PMSIGNAL_WAKEN_ARCHIVER, /* send a NOTIFY signal to xlog archiver */
PMSIGNAL_ROTATE_LOGFILE, /* send SIGUSR1 to syslogger to rotate logfile */
On Thu, 2008-08-07 at 12:44 +0100, Simon Riggs wrote:
> I would like to propose some changes to the infrastructure for recovery.
> These changes are beneficial in themselves, but also form the basis for
> other work we might later contemplate.
>
> Currently
> * the startup process performs restartpoints during recovery
> * the death of the startup process is tied directly to the change of
> state in the postmaster following recovery
>
> I propose to
> * have startup process signal postmaster when it starts Redo phase (if
> it starts it)

> Decoupling things in this way allows us to
> 1. arrange for the bgwriter to start during Redo, so it can:
> i) clean dirty blocks for the startup process
> ii) perform restartpoints in background
> Both of these aspects will increase performance of recovery

Taking into account comments from Tom and Alvaro

Included patch with the following changes:

* new postmaster mode known as consistent recovery, entered only when
recovery passes safe/consistent point. InRedo is now set in all
processes when started/connected in consistent recovery mode.

* bgwriter and stats process starts in consistent recovery mode.
bgwriter changes mode when startup process completes.

* bgwriter now performs restartpoints and also cleans shared_buffers
while the startup process performs redo apply

* recovery.conf parameter log_restartpoints is now deprecated, since
function overlaps with log_checkpoints too much. I've kept the
distinction between restartpoints and checkpoints in code, to avoid
convoluted code. Minor change, not critical.

[Replying to one of Alvaro's other comments: Startup process still uses
XLogReadBuffer. I'm not planning on changing that either, at least not
in this patch.]

Patch doesn't conflict with rmgr plugin patch.

Passes make check, but that's easy.
Various other tests all seem to be working.

--
Simon Riggs www.2ndQuadrant.com
PostgreSQL Training, Services and Support

Re: [GENERAL] query with offset stops using index scan

Stanislav Raskin wrote:

> Now, if I increase OFFSET slowly, it works all the same way, until OFFSET
> reaches the value of 750. Then, the planner refuses to use an index scan and
> does a plain seq scan+sort, which makes the query about 10-20 times slower:

You may want to try setting enable_seqscan to off before that query (and
making sure you turn it back on; preferably use SET LOCAL inside a
transaction block) so that it gives more preference to the indexscan.

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

--
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] slow update of index during insert/copy

Scott Carey wrote:
> You may want to investigate pg_bulkload.
>
> http://pgbulkload.projects.postgresql.org/
>
> One major enhancement over COPY is that it does an index merge, rather
> than modify the index one row at a time.

This is a command line tool, right? I need a jdbc driver tool, is that
possible?

regards

thomas


--
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] Manual Postgresql 8.x

Hola! acabo de registrarme en la lista.

Hace algunos días busco un manual reciente de Postgresql en español, todo lo que he conseguido es de versiones anteriores a la 8. Podrían recomendarme o indicarme algo para empezar ? no quiero entrar a leer la documentación oficial sin antes tener una base.

Gracias. Matías.

Re: [PERFORM] slow update of index during insert/copy

You may want to investigate pg_bulkload.

http://pgbulkload.projects.postgresql.org/

One major enhancement over COPY is that it does an index merge, rather than modify the index one row at a time. 
http://pgfoundry.org/docman/view.php/1000261/456/20060709_pg_bulkload.pdf



On Sun, Aug 31, 2008 at 6:32 AM, Thomas Finneid <tfinneid@student.matnat.uio.no> wrote:
Hi

I am working on a table which stores up to 125K rows per second and I find that the inserts are a little bit slow. The insert is in reality a COPY of a chunk of rows, up to 125K. A COPY og 25K rows, without an index, is fast enough, about 150ms. With the index, the insert takes about 500ms. The read though, is lightning fast, because of the index. It takes only 10ms to retrieve 1000 rows from a 15M row table. As the table grows to several billion rows, that might change though.

I would like the insert, with an index, to be a lot faster than 500ms, preferrably closer to 150ms. Any advice on what to do?
Additionally, I dont enough about pg configuring to be sure I have included all the important directives and given them proportional values, so any help on that as well would be appreciated.

Here are the details:

postgres 8.2.7 on latest kubuntu, running on dual Opteron quad cores, with 8GB memory and 8 sata disks on a raid controller (no raid config)

table:

create table v1
(
       id_s            integer,
       id_f            integer,
       id_st           integer,
       id_t            integer,
       value1          real,
       value2          real,
       value3          real,
       value4          real,
       value5          real,
       ...
       value20         real
);

create index idx_v1 on v1 (id_s, id_st, id_t);

- insert is a COPY into the 5-8 first columns. the rest are unused so
 far.

postgres config:

autovacuum = off
checkpoint_segments = 96
commit_delay = 5
effective_cache_size = 128000
fsync = on
max_fsm_pages = 208000
max_fsm_relations = 10000
max_connections = 20
shared_buffers = 128000
wal_sync_method = fdatasync
wal_buffers = 256
work_mem = 512000
maintenance_work_mem = 2000000

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

[GENERAL] Oracle and Postgresql

Hello,

I am a CS graduate and I have a brief idea of Postgres and Oracle.
But, I dont have an in-depth knowledge in any of them. I have a couple
of questions and

I want to compare both of them in terms of functionality, performance,
advantages and disadvantages.

Why most enterprises prefer Oracle than Postgres even though it is
free and has a decent enough user community.

--
Thanks,
Srinivas

--
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] Cause of occasional buildfarm failures in sequence test

Hannu Krosing <hannu@2ndQuadrant.com> writes:
> On Sun, 2008-08-31 at 13:17 -0400, Tom Lane wrote:
>> So unless we want to just live with this test failing occasionally,
>> it seems we have two choices: redesign the behavior of nextval()
>> to be insensitive to checkpoint timing, or provide an alternate
>> regression "expected" file that matches the result with log_cnt = 31.
>> I favor the second answer --- I don't want to touch the nextval
>> logic, which has been stable for over six years.

> Maybe you get consistent result by just changing the test thus:

> checkpoint;
> create sequence foo;
> select nextval('foo');
> select nextval('foo');
> select * from foo;

Actually I think we'd need to put the checkpoint after the create,
but yeah we could do that. Or we could leave log_cnt out of the
set of columns displayed. I don't really favor either of those
answers though. They amount to avoiding testing of some code
paths ...

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-fr-generale] ERREUR: "$3" is declared CONSTANT

Très intérressant !

Merci beaucoup, je vais mettre ça en place, le code sera un peu plus
clair :)

Merci !

Le dimanche 31 août 2008 à 19:22 +0200, Christophe Chauvet a écrit :
> Bonsoir
>
> Si vous vouliez reutiliser la variable que vous avez passer en argument
> a votre fonction, il aurait fallu la déclaré comme ceci
>
> CREATE OR REPLACE FUNCTION clients.contact (p_nom text, p_email text,
> inout p_t integer) RETURNS integer AS $contact$
>
> l'utilisation de INOUT permet de passer la variable en argument de la
> fonction, mais également de changer sa valeur pour la recupérer après le
> retour de la fonction
>
> ex schématique
>
> a = 5
>
> x = client.contact('toto', 'toto@toto.com', a)
>
> print a
> (dans votre exemple ici a vaudrait 1)
>
> OUT et INOUT sont disponible depuis PostgreSQL 8.1
>
> Cordialement,
>
> Christophe Chauvet.
>
> Samuel ROZE a écrit :
> > Re-Bonjour,
> >
> > Une erreur très bête et en fait, très explicite :
> >
> > C'était cette portion du code qui posait problème :
> >
> >
> >> IF (p_t != 0) THEN
> >> p_t := 1;
> >> END IF;
> >>
> >
> > En fait, la variable "p_t" est une constante donc je n'ai pas le droit
> > de la modifier, il faut donc que je passe par une autre variable.
> >
> > A bientôt.
> > Samuel.
> >
> > Le dimanche 31 août 2008 à 11:48 +0200, Samuel ROZE a écrit :
> >
> >> Bonjour à tous,
> >>
> >> J'ai crééer une fonction appelée "contact" dans ma base de données, qui,
> >> quand on l'appelle, renvoi l'ID du contact avec les noms et email donnés
> >> en paramètre. Si il n'y a pas de contact de ce nom/email, elle le créé
> >> et retourne à nouveau l'ID.
> >>
> >> Voici la structure de la table "contacts" :
> >> +-----------------+
> >> | contacts |
> >> +-----------------+
> >> | id SERIAL |
> >> | nom text |
> >> | email text |
> >> | actif integer |
> >> | maj timestamptz |
> >> | _trigger integer|
> >> +-----------------+
> >>
> >> Le dernier champ, "_trigger" sert à dire ou non si on veut que le
> >> trigger s'éxécute pour l'enregistrement.
> >>
> >> Maintenant, voici le code de ma fonction "contact" :
> >>
> >> -------------------------
> >> CREATE OR REPLACE FUNCTION clients.contact (p_nom text, p_email text,
> >> p_t integer) RETURNS integer AS $contact$
> >> DECLARE
> >> v_id integer DEFAULT 0;
> >> BEGIN
> >> IF (p_t != 0) THEN
> >> p_t := 1;
> >> END IF;
> >> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> >> email = p_email LIMIT 1;
> >> IF NOT FOUND THEN
> >> INSERT INTO clients.contacts (nom, email, _trigger) VALUES
> >> (p_nom, p_email, p_t);
> >> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
> >> email = p_email LIMIT 1;
> >> END IF;
> >> RETURN v_id;
> >> END;
> >> $contact$ language plpgsql;
> >> -------------------------
> >>
> >> Lorsque j'essaye de créer cette fonction, le compilateur plpgsql me sort
> >> cette erreur :
> >>
> >> -------------------------
> >> 5-clients-fonctions.sql:21: ERREUR: "$3" is declared CONSTANT
> >> CONTEXT: compile of PL/pgSQL function "contact" near line 10
> >> -------------------------
> >>
> >> La ligne 21 correspond à la ligne où il y as la requête "INSERT" dans la
> >> fonction "contact".
> >>
> >> Auriez-vous une idée sur le pourquoi de cette erreur ?
> >>
> >> Merci d'avance !
> >> Cordialement, Samuel ROZE.
> >>
> >>
> >>
> >
> >
> >
>
>


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

Re: [HACKERS] Cause of occasional buildfarm failures in sequence test

On Sun, 2008-08-31 at 13:17 -0400, Tom Lane wrote:
> The current result from buildfarm member pigeon
> http://www.pgbuildfarm.org/cgi-bin/show_log.pl?nm=pigeon&dt=2008-08-31%2008:04:54
> shows a symptom I've noticed a few times before: everything is fine
> except that one "select * from sequence" shows log_cnt = 31 instead
> of the expected 32. This is a bit odd since no other backend is
> touching that sequence, so you'd expect perfectly reproducible results.
>
> I finally got around to looking through the sequence code to see if I
> could figure out what was happening, and indeed I did. The relevant
> parts of the test are basically
> create sequence foo;
> select nextval('foo');
> select nextval('foo');
> select * from foo;
> and you can reproduce the unexpected result if you insert a checkpoint
> command between the create and the first nextval. So the buildfarm
> failures are due to chance occurrences of a bgwriter-driven checkpoint
> occurring just there during the test.
>
> In the normal execution of this test, the CREATE SEQUENCE leaves the
> sequence in a state where one nextval() can be done "for free", without
> emitting a new WAL record. So the second nextval() is the one that
> emits a WAL record and pushes log_cnt up to 32. But if a checkpoint
> intervenes, then the first nextval() decides it'd better emit the WAL
> record (cf lines 500ff in sequence.c as of CVS HEAD), so it pushes
> log_cnt up to 32, and then the second one decreases it to 31.
>
> So unless we want to just live with this test failing occasionally,
> it seems we have two choices: redesign the behavior of nextval()
> to be insensitive to checkpoint timing, or provide an alternate
> regression "expected" file that matches the result with log_cnt = 31.
> I favor the second answer --- I don't want to touch the nextval
> logic, which has been stable for over six years.
>
> Comments?

Maybe you get consistent result by just changing the test thus:

checkpoint;
create sequence foo;
select nextval('foo');
select nextval('foo');
select * from foo;

--------------
Hannu


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

Re: [NOVICE] Converting a table from SQL Server

Bob McConnell <rmcconne@lightlink.com> writes:
> But I have only found articles on how to convert from MySQL to Postgres
> and a few on how to convert from SQL Server to MySQL. So how do I
> translate this without leaving the bad taste of MySQL in my mouth? Or is
> there a similar recommended practice for Postgres?

I believe the main thing you need to know is that the brackets are
a nonstandard spelling for quoted identifiers. That is
[MajorReleaseNumber] converts to "MajorReleaseNumber".

(You might be better off translating to MajorReleaseNumber without the
quotes, which will really mean majorreleasenumber. Depends whether you
want to double-quote every use of the name in your applications.)

The IDENTITY business probably equates to SERIAL, and there are some
other nonstandard things here like the CLUSTERED adjective.

regards, tom lane

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

Re: [pgsql-fr-generale] ERREUR: "$3" is declared CONSTANT

Bonsoir

Si vous vouliez reutiliser la variable que vous avez passer en argument
a votre fonction, il aurait fallu la déclaré comme ceci

CREATE OR REPLACE FUNCTION clients.contact (p_nom text, p_email text,
inout p_t integer) RETURNS integer AS $contact$

l'utilisation de INOUT permet de passer la variable en argument de la
fonction, mais également de changer sa valeur pour la recupérer après le
retour de la fonction

ex schématique

a = 5

x = client.contact('toto', 'toto@toto.com', a)

print a
(dans votre exemple ici a vaudrait 1)

OUT et INOUT sont disponible depuis PostgreSQL 8.1

Cordialement,

Christophe Chauvet.

Samuel ROZE a écrit :
> Re-Bonjour,
>
> Une erreur très bête et en fait, très explicite :
>
> C'était cette portion du code qui posait problème :
>
>
>> IF (p_t != 0) THEN
>> p_t := 1;
>> END IF;
>>
>
> En fait, la variable "p_t" est une constante donc je n'ai pas le droit
> de la modifier, il faut donc que je passe par une autre variable.
>
> A bientôt.
> Samuel.
>
> Le dimanche 31 août 2008 à 11:48 +0200, Samuel ROZE a écrit :
>
>> Bonjour à tous,
>>
>> J'ai crééer une fonction appelée "contact" dans ma base de données, qui,
>> quand on l'appelle, renvoi l'ID du contact avec les noms et email donnés
>> en paramètre. Si il n'y a pas de contact de ce nom/email, elle le créé
>> et retourne à nouveau l'ID.
>>
>> Voici la structure de la table "contacts" :
>> +-----------------+
>> | contacts |
>> +-----------------+
>> | id SERIAL |
>> | nom text |
>> | email text |
>> | actif integer |
>> | maj timestamptz |
>> | _trigger integer|
>> +-----------------+
>>
>> Le dernier champ, "_trigger" sert à dire ou non si on veut que le
>> trigger s'éxécute pour l'enregistrement.
>>
>> Maintenant, voici le code de ma fonction "contact" :
>>
>> -------------------------
>> CREATE OR REPLACE FUNCTION clients.contact (p_nom text, p_email text,
>> p_t integer) RETURNS integer AS $contact$
>> DECLARE
>> v_id integer DEFAULT 0;
>> BEGIN
>> IF (p_t != 0) THEN
>> p_t := 1;
>> END IF;
>> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
>> email = p_email LIMIT 1;
>> IF NOT FOUND THEN
>> INSERT INTO clients.contacts (nom, email, _trigger) VALUES
>> (p_nom, p_email, p_t);
>> SELECT id INTO v_id FROM clients.contacts WHERE nom = p_nom AND
>> email = p_email LIMIT 1;
>> END IF;
>> RETURN v_id;
>> END;
>> $contact$ language plpgsql;
>> -------------------------
>>
>> Lorsque j'essaye de créer cette fonction, le compilateur plpgsql me sort
>> cette erreur :
>>
>> -------------------------
>> 5-clients-fonctions.sql:21: ERREUR: "$3" is declared CONSTANT
>> CONTEXT: compile of PL/pgSQL function "contact" near line 10
>> -------------------------
>>
>> La ligne 21 correspond à la ligne où il y as la requête "INSERT" dans la
>> fonction "contact".
>>
>> Auriez-vous une idée sur le pourquoi de cette erreur ?
>>
>> Merci d'avance !
>> Cordialement, Samuel ROZE.
>>
>>
>>
>
>
>


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

Re: [GENERAL] integer values in conf file

Thomas Finneid <tfinneid@student.matnat.uio.no> writes:
> A quick question, In the doc on the net for miscellaneous config
> options, e.g. maintenance_work_mem, the doc states the argument is an
> integer, but it does not state whether the number should be in Bytes,
> KB, MB. From examples I have seen, I conclude its in KB, but is that
> correct?

Yeah, if you don't put a unit on it it'll be taken as kB. See the
'unit' column in pg_settings when in doubt on such matters.

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

[HACKERS] Cause of occasional buildfarm failures in sequence test

The current result from buildfarm member pigeon
http://www.pgbuildfarm.org/cgi-bin/show_log.pl?nm=pigeon&dt=2008-08-31%2008:04:54
shows a symptom I've noticed a few times before: everything is fine
except that one "select * from sequence" shows log_cnt = 31 instead
of the expected 32. This is a bit odd since no other backend is
touching that sequence, so you'd expect perfectly reproducible results.

I finally got around to looking through the sequence code to see if I
could figure out what was happening, and indeed I did. The relevant
parts of the test are basically
create sequence foo;
select nextval('foo');
select nextval('foo');
select * from foo;
and you can reproduce the unexpected result if you insert a checkpoint
command between the create and the first nextval. So the buildfarm
failures are due to chance occurrences of a bgwriter-driven checkpoint
occurring just there during the test.

In the normal execution of this test, the CREATE SEQUENCE leaves the
sequence in a state where one nextval() can be done "for free", without
emitting a new WAL record. So the second nextval() is the one that
emits a WAL record and pushes log_cnt up to 32. But if a checkpoint
intervenes, then the first nextval() decides it'd better emit the WAL
record (cf lines 500ff in sequence.c as of CVS HEAD), so it pushes
log_cnt up to 32, and then the second one decreases it to 31.

So unless we want to just live with this test failing occasionally,
it seems we have two choices: redesign the behavior of nextval()
to be insensitive to checkpoint timing, or provide an alternate
regression "expected" file that matches the result with log_cnt = 31.
I favor the second answer --- I don't want to touch the nextval
logic, which has been stable for over six years.

Comments?

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: [ADMIN] vacuum verbose relations reporting

On Sun, 31 Aug 2008, Alvaro Herrera wrote:

> Jeff Frost wrote:
>
>> I guess this isn't entirely accurate, as the above script returns 35883,
>> but vacuum verbose returns:
>>
>> INFO: free space map contains 111435 pages in 10005 relations
>
> Well, what this means is that not every single table has useful free
> space ...

Ohh...naturally. So, max_fsm_relations only cares about relations that have
free space to track, and not all relations. So, is there a way to compute
the number of relatinos with useful free space?


--
Jeff Frost, Owner <jeff@frostconsultingllc.com>
Frost Consulting, LLC http://www.frostconsultingllc.com/
Phone: 916-647-6411 FAX: 916-405-4032

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

Re: [ADMIN] vacuum verbose relations reporting

Jeff Frost wrote:

> I guess this isn't entirely accurate, as the above script returns 35883,
> but vacuum verbose returns:
>
> INFO: free space map contains 111435 pages in 10005 relations

Well, what this means is that not every single table has useful free
space ...

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

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

Re: [ADMIN] vacuum verbose relations reporting



Jeff Frost wrote:
Alvaro Herrera wrote:
Jeff Frost wrote:    
Tom, is there an easy (or hard) way to count relations from all DBs by  using the system catalogs?     
 Just do a count(*) from pg_class where relkind in ('r', 't', 'i'), and sum across all databases (you need to connect to each one).  (Actually you only need to count indexes that are btrees, if you need such a distinction.  Other indexes do not use the FSM as far as I know).   
Perfect, so here's a little script that does the trick then:

#!/bin/sh

PSQL=/usr/bin/psql
DATABASES=$($PSQL -lt |  awk {'print $1'} | grep -v template0 )
RELATIONS=0

for DB in $DATABASES; do
    RELATIONS=$(($RELATIONS + $($PSQL --tuples-only --command "select count(*) from pg_class where relkind IN ('r', 't', 'i');" $DB) ))
done

echo $RELATIONS

I guess this isn't entirely accurate, as the above script returns 35883, but vacuum verbose returns:

INFO:  free space map contains 111435 pages in 10005 relations

If I take out the toast tables and indexes, I get a result much closer to what vacuum verbose returns: 10626  which might just be because the vacuum verbose ran a few hours ago.

So, the question is, do the FSM settings take into account toast tables and indexes as Alvaro suggested and vacuum verbose isn't properly reporting on it?


--  Jeff Frost, Owner 	<jeff@frostconsultingllc.com> Frost Consulting, LLC 	http://www.frostconsultingllc.com/ Phone: 916-647-6411	FAX: 916-405-4032 

Re: [GENERAL] integer values in conf file

Thomas Finneid wrote:
> Hi
>
> A quick question, In the doc on the net for miscellaneous config
> options, e.g. maintenance_work_mem, the doc states the argument is an
> integer, but it does not state whether the number should be in Bytes,
> KB, MB. From examples I have seen, I conclude its in KB, but is that
> correct?

From <http://www.postgresql.org/docs/8.3/static/config-setting.html>:
> Some settings specify a memory or time value.
> Each of these has an implicit unit, which is either kilobytes, blocks
> (typically eight kilobytes), milliseconds, seconds, or minutes.
> Default units can be queried by referencing pg_settings.unit.
> For convenience, a different unit can also be specified explicitly.
> Valid memory units are kB (kilobytes), MB (megabytes), and GB (gigabytes);
> valid time units are ms (milliseconds), s (seconds), min (minutes),
> h (hours), and d (days). Note that the multiplier for memory units is
> 1024, not 1000.

--
Lew

--
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] DUPS in tables columns ERROR: column ". . . " does not exist

Albretch Mueller wrote:
> Also I know there is a DISTINCT keyword, but I also need to know how
> many times the particular data in the column is repeated if it is,
> that is why I need to go:
> ~
> SELECT md5, COUNT(md5) AS md5cnt
> FROM jdk1_6_0_07_txtfls_md5
> WHERE (md5cnt > 1)
> GROUP BY md5
> ORDER BY md5cnt DESC;

Use HAVING instead of WHERE.

--
Lew

--
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] ERROR: relation . . . does not exist

Albretch Mueller wrote:
>> Varchar or text?
> ~
> Is the length of the data read in always less than 255 bytes ( or
> characters?)? ...

It may be more limited than that by application-domain-specific constraints -
e.g., a license plate might be statutorily limited to eight characters.

It might be coincidence that the input happens to fit within 255 characters
when future inputs might not. One cannot make certain statements about
whether "data read in always [being] less than 255 ... characters" based on a
limited sample set, only probabilistic ones, absent reasoning about the
application domain.

Additionally, one could use TEXT for shorter columns if one wanted:
> There are no performance differences between these three types,
[character varying(n), character(n) and text]
> apart from increased storage size when using the blank-padded
> type, and a few extra cycles to check the length when storing
> into a length-constrained column. While character(n) has
> performance advantages in some other database systems, it has
> no such advantages in PostgreSQL. In most situations text or
> character varying should be used instead.
<http://www.postgresql.org/docs/8.3/static/datatype-character.html>

DBMSes are about schemata and planning the data structures, not loosey-goosey
typing. (This reminds me of the debate between the loosely-typed language
(e.g., PHP) camp versus the strongly-typed language (C#, Java) camp.) Schemas
are based on analysis of and reasoning about the application domain, not lucky
guesses about a limited sample of inputs.

--
Lew

--
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] query with offset stops using index scan

> If there's a chance to upgrade to 8.3 please do so.

I am aware of the benefits with 8.3, but such an upgrade would require quite
some changes in our application, including introduction of explicit casting
mechanisms. We are going to do so sooner or later, but right now we need to
focus on other stuff.

> What's happening here is that the query
> planner is switching plans because it thinks the sequential scan and
> sort are cheaper. and at some point it will likely be right.

Thank you very much for pointing out the issue.
I am still a bit puzzled, because there are only about 2000 data sets in
this table. It's not like we're handling millions of rows.

Clustering on the id did the trick. Now the planner always chooses to use
the index.

Unfortunately, I cannot use multi-column indexes here, because the
expressions in the WHERE statement can vary quite strongly, depending on
user input.

Cursors are not an option, because it is a web application, meaning that I
have to use a new connection for basically every HTTP request.

The "where id between x and x+y" is indeed much, much faster, but it
presumes the knowledge of x and y, which is not the case, because serial ids
are not necessarily continuous (i.e. if some data sets were deleted).

-----Ursprüngliche Nachricht-----
Von: Scott Marlowe [mailto:scott.marlowe@gmail.com]
Gesendet: Sonntag, 31. August 2008 17:26
An: Stanislav Raskin
Cc: pgsql-general@postgresql.org
Betreff: Re: [GENERAL] query with offset stops using index scan

On Sun, Aug 31, 2008 at 7:14 AM, Stanislav Raskin <sr@brainswell.de> wrote:
> Hello everybody,
>
> Now, if I increase OFFSET slowly, it works all the same way, until OFFSET
> reaches the value of 750. Then, the planner refuses to use an index scan
and
> does a plain seq scan+sort, which makes the query about 10-20 times
slower:
>
> I use 8.1.4, and I did a vacuum full analyze before running the queries.

If there's a chance to upgrade to 8.3 please do so. While 8.1 was a
solid reliable workhorse of a database, there's been a lot of work
done in general for better performance and more features. It likely
won't fix this one problem, but it's often smarter about corner cases
in query plans than 8.1 so it's worth looking into.

Now back to your problem. What's happening here is that the query
planner is switching plans because it thinks the sequential scan and
sort are cheaper. and at some point it will likely be right. That's
because a random page cost is much higher than a sequential page cost.
So at some point, say when you're grabbing 2% to 25% of a table, it
will switch to sequential scans.

Now, if the data is all cached, then it's still quicker to do the
index scan further along than to use a seq scan and a sort. Unless
your table is clustered to the index you're sorting on, a Seq scan
will almost always win if you need the whole table.

However, you may be in a position where a multi-column index and
clustering on id will allow you to run this offset higher. It's still
a poor performer for large chunks of large tables.

first cluster on the primary key id, then create a three column index
for (active, valid_until, locked) Note that the order should be from
the most choosey to least choosey column, generally. So assuming only
a tiny percentage of records meet valid_until, make it the first
column, and so forth. A query like:

select active, count(active) from table group by active;

will give you an idea there.

In the long run if you want good performance on larger data sets (i.e.
higher offset numbers) you'll likely need to switch to either cursors,
or using "where id between x and x+y" or lookup tables, or something
like that.


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

Re: [NOVICE] Converting a table from SQL Server

On Sun, Aug 31, 2008 at 10:19 AM, Bob McConnell <rmcconne@lightlink.com> wrote:
> Sean Davis wrote:
>>
>> On Sun, Aug 31, 2008 at 9:03 AM, Bob McConnell <rmcconne@lightlink.com>
>> wrote:
>>>
>>> I am just beginning to learn a number of new tools simultaneously, so
>>> please
>>> bear with me. I have installed Apache 2.2, PHP 5 and PostgreSQL 8.2.1 on
>>> a
>>> couple of servers to play with. I also have pgAdmin III 1.8.4 running on
>>> one
>>> workstation which is able to connect with each server. I am not yet fully
>>> happy with the results, but they are close enough now for me to start
>>> trying
>>> a few experiments.
>>>
>>> I found the text below while searching for something on Google. Based on
>>> the
>>> site it was posted to, I believe it is for SQL Server. I would like to
>>> convert it into Postgres and make it a standard component of every
>>> database
>>> I build. (I added the PatchNumber field.)
>>>
>>> But I have only found articles on how to convert from MySQL to Postgres
>>> and
>>> a few on how to convert from SQL Server to MySQL. So how do I translate
>>> this
>>> without leaving the bad taste of MySQL in my mouth? Or is there a similar
>>> recommended practice for Postgres?
>>
>> Do you mean that you want an auto-translator for SQL Server to
>> Postgres? Or do you mean that you just need help with Postgresql
>> syntax? If it is the latter, the docs for postgresql are quite good:
>>
>> http://www.postgresql.org/docs/8.2/static/
>>
>> Sean
>>
>
> In this case, I just want to manually translate these lines from Microsoft
> SQL to Postgres SQL so I can append them to every database and script I
> build. Since I don't know either language yet, and have no desire to learn
> the Microsoft (nor MySQL) variation, I don't know the best way to proceed.
> What makes it even more confusing is that I know just enough Sybase ASA SQL
> to be dangerous. That's the one I have had to deal with at work for the past
> ten years.
>
> I know, the best thing about standards is that there are so many to choose
> from.

Thankfully, Postgresql SQL generally conforms to the SQL standard. I
would suggest working through some simple test examples found online.
You'll learn a great deal about SQL by just typing in examples and
getting familiar with the tools available. Then, you can peruse the
manual to learn more detail and some of the edge cases that you might
want to employ.

Sean

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

Re: [GENERAL] query with offset stops using index scan

On Sun, Aug 31, 2008 at 7:14 AM, Stanislav Raskin <sr@brainswell.de> wrote:
> Hello everybody,
>
> Now, if I increase OFFSET slowly, it works all the same way, until OFFSET
> reaches the value of 750. Then, the planner refuses to use an index scan and
> does a plain seq scan+sort, which makes the query about 10-20 times slower:
>
> I use 8.1.4, and I did a vacuum full analyze before running the queries.

If there's a chance to upgrade to 8.3 please do so. While 8.1 was a
solid reliable workhorse of a database, there's been a lot of work
done in general for better performance and more features. It likely
won't fix this one problem, but it's often smarter about corner cases
in query plans than 8.1 so it's worth looking into.

Now back to your problem. What's happening here is that the query
planner is switching plans because it thinks the sequential scan and
sort are cheaper. and at some point it will likely be right. That's
because a random page cost is much higher than a sequential page cost.
So at some point, say when you're grabbing 2% to 25% of a table, it
will switch to sequential scans.

Now, if the data is all cached, then it's still quicker to do the
index scan further along than to use a seq scan and a sort. Unless
your table is clustered to the index you're sorting on, a Seq scan
will almost always win if you need the whole table.

However, you may be in a position where a multi-column index and
clustering on id will allow you to run this offset higher. It's still
a poor performer for large chunks of large tables.

first cluster on the primary key id, then create a three column index
for (active, valid_until, locked) Note that the order should be from
the most choosey to least choosey column, generally. So assuming only
a tiny percentage of records meet valid_until, make it the first
column, and so forth. A query like:

select active, count(active) from table group by active;

will give you an idea there.

In the long run if you want good performance on larger data sets (i.e.
higher offset numbers) you'll likely need to switch to either cursors,
or using "where id between x and x+y" or lookup tables, or something
like that.

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

Re: [NOVICE] Converting a table from SQL Server

Sean Davis wrote:
> On Sun, Aug 31, 2008 at 9:03 AM, Bob McConnell <rmcconne@lightlink.com> wrote:
>> I am just beginning to learn a number of new tools simultaneously, so please
>> bear with me. I have installed Apache 2.2, PHP 5 and PostgreSQL 8.2.1 on a
>> couple of servers to play with. I also have pgAdmin III 1.8.4 running on one
>> workstation which is able to connect with each server. I am not yet fully
>> happy with the results, but they are close enough now for me to start trying
>> a few experiments.
>>
>> I found the text below while searching for something on Google. Based on the
>> site it was posted to, I believe it is for SQL Server. I would like to
>> convert it into Postgres and make it a standard component of every database
>> I build. (I added the PatchNumber field.)
>>
>> But I have only found articles on how to convert from MySQL to Postgres and
>> a few on how to convert from SQL Server to MySQL. So how do I translate this
>> without leaving the bad taste of MySQL in my mouth? Or is there a similar
>> recommended practice for Postgres?
>
> Do you mean that you want an auto-translator for SQL Server to
> Postgres? Or do you mean that you just need help with Postgresql
> syntax? If it is the latter, the docs for postgresql are quite good:
>
> http://www.postgresql.org/docs/8.2/static/
>
> Sean
>

In this case, I just want to manually translate these lines from
Microsoft SQL to Postgres SQL so I can append them to every database and
script I build. Since I don't know either language yet, and have no
desire to learn the Microsoft (nor MySQL) variation, I don't know the
best way to proceed. What makes it even more confusing is that I know
just enough Sybase ASA SQL to be dangerous. That's the one I have had to
deal with at work for the past ten years.

I know, the best thing about standards is that there are so many to
choose from.

Thanks,

Bob McConnell
N2SPP

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

Re: [NOVICE] Converting a table from SQL Server

On Sun, Aug 31, 2008 at 9:03 AM, Bob McConnell <rmcconne@lightlink.com> wrote:
> I am just beginning to learn a number of new tools simultaneously, so please
> bear with me. I have installed Apache 2.2, PHP 5 and PostgreSQL 8.2.1 on a
> couple of servers to play with. I also have pgAdmin III 1.8.4 running on one
> workstation which is able to connect with each server. I am not yet fully
> happy with the results, but they are close enough now for me to start trying
> a few experiments.
>
> I found the text below while searching for something on Google. Based on the
> site it was posted to, I believe it is for SQL Server. I would like to
> convert it into Postgres and make it a standard component of every database
> I build. (I added the PatchNumber field.)
>
> But I have only found articles on how to convert from MySQL to Postgres and
> a few on how to convert from SQL Server to MySQL. So how do I translate this
> without leaving the bad taste of MySQL in my mouth? Or is there a similar
> recommended practice for Postgres?

Do you mean that you want an auto-translator for SQL Server to
Postgres? Or do you mean that you just need help with Postgresql
syntax? If it is the latter, the docs for postgresql are quite good:

http://www.postgresql.org/docs/8.2/static/

Sean

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

[PERFORM] slow update of index during insert/copy

Hi

I am working on a table which stores up to 125K rows per second and I
find that the inserts are a little bit slow. The insert is in reality a
COPY of a chunk of rows, up to 125K. A COPY og 25K rows, without an
index, is fast enough, about 150ms. With the index, the insert takes
about 500ms. The read though, is lightning fast, because of the index.
It takes only 10ms to retrieve 1000 rows from a 15M row table. As the
table grows to several billion rows, that might change though.

I would like the insert, with an index, to be a lot faster than 500ms,
preferrably closer to 150ms. Any advice on what to do?
Additionally, I dont enough about pg configuring to be sure I have
included all the important directives and given them proportional
values, so any help on that as well would be appreciated.

Here are the details:

postgres 8.2.7 on latest kubuntu, running on dual Opteron quad cores,
with 8GB memory and 8 sata disks on a raid controller (no raid config)

table:

create table v1
(
id_s integer,
id_f integer,
id_st integer,
id_t integer,
value1 real,
value2 real,
value3 real,
value4 real,
value5 real,
...
value20 real
);

create index idx_v1 on v1 (id_s, id_st, id_t);

- insert is a COPY into the 5-8 first columns. the rest are unused so
far.

postgres config:

autovacuum = off
checkpoint_segments = 96
commit_delay = 5
effective_cache_size = 128000
fsync = on
max_fsm_pages = 208000
max_fsm_relations = 10000
max_connections = 20
shared_buffers = 128000
wal_sync_method = fdatasync
wal_buffers = 256
work_mem = 512000
maintenance_work_mem = 2000000

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