Robert Creager <Robert_Creager@LogicalChaos.org> writes:
> I've implemented a couple of functions ala date_trunc (listed at the bottom)
> [ and they're too slow ]
Well, it's hardly surprising that a function that invokes date_trunc and
half a dozen other comparably-expensive operations should be half a
dozen times as expensive as date_trunc. Not to mention that plpgsql is
inherently far slower than C.
Assuming that you don't want to descend to writing C, I'd suggest doing
arithmetic on the Unix-epoch version of the timestamp. Perhaps
something along the lines of
select 'epoch'::timestamptz +
trunc(extract(epoch from now())/(3600*24*7))*(3600*24*7) * '1sec'::interval;
This doesn't have the same roundoff behavior as what you posted, but I
think it could be adjusted to do so with a couple more additions and
subtractions, unless there's some magic I'm not seeing about the year
boundary behavior. Certainly the five-minute-trunc problem could be
done this way.
If you do feel like descending to C, I don't see any fundamental reason
why we accept date_part('week',...) but not date_trunc('week',...).
Feel free to submit a patch.
regards, tom lane