Commit Graph

322 Commits

Author SHA1 Message Date
Tom Lane ec646dbc65 Create a 'type cache' that keeps track of the data needed for any particular
datatype by array_eq and array_cmp; use this to solve problems with memory
leaks in array indexing support.  The parser's equality_oper and ordering_oper
routines also use the cache.  Change the operator search algorithms to look
for appropriate btree or hash index opclasses, instead of assuming operators
named '<' or '=' have the right semantics.  (ORDER BY ASC/DESC now also look
at opclasses, instead of assuming '<' and '>' are the right things.)  Add
several more index opclasses so that there is no regression in functionality
for base datatypes.  initdb forced due to catalog additions.
2003-08-17 19:58:06 +00:00
Tom Lane ecbed6e1b9 create_unique_plan() should not discard existing output columns of the
subplan it starts with, as they may be needed at upper join levels.
See comments added to code for the non-obvious reason why.  Per bug report
from Robert Creager.
2003-08-07 19:20:24 +00:00
Bruce Momjian f3c3deb7d0 Update copyrights to 2003. 2003-08-04 02:40:20 +00:00
Bruce Momjian 089003fb46 pgindent run. 2003-08-04 00:43:34 +00:00
Tom Lane a56ff9a0bd Another round of error message editing, covering backend/parser/. 2003-07-19 20:20:53 +00:00
Tom Lane b89140a7ec Do honest transformation and preprocessing of LIMIT/OFFSET clauses,
instead of the former kluge whereby gram.y emitted already-transformed
expressions.  This is needed so that Params appearing in these clauses
actually work correctly.  I suppose some might claim that the side effect
of 'SELECT ... LIMIT 2+2' working is a new feature, but I say this is
a bug fix.
2003-07-03 19:07:54 +00:00
Tom Lane a499725469 Allow GROUP BY, ORDER BY, DISTINCT targets to be unknown literals,
silently resolving them to type TEXT.  This is comparable to what we
do when faced with UNKNOWN in CASE, UNION, and other contexts.  It gets
rid of this and related annoyances:
	select distinct f1, '' from int4_tbl;
	ERROR:  Unable to identify an ordering operator '<' for type unknown
This was discussed many moons ago, but no one got round to fixing it.
2003-06-16 02:03:38 +00:00
Tom Lane 996fdb9af1 Cause GROUP BY clause to adopt ordering operators from ORDER BY when
both clauses specify the same targets, rather than always using the
default ordering operator.  This allows 'GROUP BY foo ORDER BY foo DESC'
to be done with only one sort step.
2003-06-15 16:42:08 +00:00
Tom Lane e649796f12 Implement outer-level aggregates to conform to the SQL spec, with
extensions to support our historical behavior.  An aggregate belongs
to the closest query level of any of the variables in its argument,
or the current query level if there are no variables (e.g., COUNT(*)).
The implementation involves adding an agglevelsup field to Aggref,
and treating outer aggregates like outer variables at planning time.
2003-06-06 15:04:03 +00:00
Tom Lane aa282d4446 Infrastructure for deducing Param types from context, in the same way
that the types of untyped string-literal constants are deduced (ie,
when coerce_type is applied to 'em, that's what the type must be).
Remove the ancient hack of storing the input Param-types array as a
global variable, and put the info into ParseState instead.  This touches
a lot of files because of adjustment of routine parameter lists, but
it's really not a large patch.  Note: PREPARE statement still insists on
exact specification of parameter types, but that could easily be relaxed
now, if we wanted to do so.
2003-04-29 22:13:11 +00:00
Tom Lane 05f916e6ad Adjust subquery qual pushdown rules to be more forgiving: if a qual
refers to a non-DISTINCT output column of a DISTINCT ON subquery, or
if it refers to a function-returning-set, we cannot push it down.
But the old implementation refused to push down *any* quals if the
subquery had any such 'dangerous' outputs.  Now we just look at the
output columns actually referenced by each qual expression.  More code
than before, but probably no slower since we don't make unnecessary checks.
2003-03-22 01:49:38 +00:00
Tom Lane aa83bc04e0 Restructure parsetree representation of DECLARE CURSOR: now it's a
utility statement (DeclareCursorStmt) with a SELECT query dangling from
it, rather than a SELECT query with a few unusual fields in it.  Add
code to determine whether a planned query can safely be run backwards.
If DECLARE CURSOR specifies SCROLL, ensure that the plan can be run
backwards by adding a Materialize plan node if it can't.  Without SCROLL,
you get an error if you try to fetch backwards from a cursor that can't
handle it.  (There is still some discussion about what the exact
behavior should be, but this is necessary infrastructure in any case.)
Along the way, make EXPLAIN DECLARE CURSOR work.
2003-03-10 03:53:52 +00:00
Tom Lane 51972a9d5d COALESCE() and NULLIF() are now first-class expressions, not macros
that turn into CASE expressions.  They evaluate their arguments at most
once.  Patch by Kris Jurka, review and (very light) editorializing by me.
2003-02-16 02:30:39 +00:00
Tom Lane 18e8f06c9d Arrange to give error when a SetOp member statement refers to a variable
of the containing query (which really can only happen in a rule context).
Per example from Brandon Craig Rhodes.  Also, make the error message
more specific for the similar case with sub-select in FROM.  The revised
coding should be easier to adapt to SQL99's LATERAL(), when we get around
to supporting that.
2003-02-13 20:45:22 +00:00
Bruce Momjian e529e9fa44 [ Revert patch ]
> =================================================================
> User interface proposal for multi-row function targetlist entries
> =================================================================
> 1. Only one targetlist entry may return a set.
> 2. Each targetlist item (other than the set returning one) is
>    repeated for each item in the returned set.
>

Having gotten no objections (actually, no response at all), I can only
assume no one had heartburn with this change. The attached patch covers
the first of the two proposals, i.e. restricting the target list to only
one set returning function.

Joe Conway
2003-02-13 05:53:46 +00:00
Bruce Momjian d21de3b121 > =================================================================
> User interface proposal for multi-row function targetlist entries
> =================================================================
> 1. Only one targetlist entry may return a set.
> 2. Each targetlist item (other than the set returning one) is
>    repeated for each item in the returned set.
>

Having gotten no objections (actually, no response at all), I can only assume
no one had heartburn with this change. The attached patch covers the first of
the two proposals, i.e. restricting the target list to only one set returning
function.

It compiles cleanly, and passes all regression tests. If there are no
objections, please apply.

Any suggestions on where this should be documented (other than maybe sql-select)?

Thanks,

Joe

p.s. Here's what the previous example now looks like:
CREATE TABLE bar(f1 int, f2 text, f3 int);
INSERT INTO bar VALUES(1, 'Hello', 42);
INSERT INTO bar VALUES(2, 'Happy', 45);

CREATE TABLE foo(a int, b text);
INSERT INTO foo VALUES(42, 'World');
INSERT INTO foo VALUES(42, 'Everyone');
INSERT INTO foo VALUES(45, 'Birthday');
INSERT INTO foo VALUES(45, 'New Year');

CREATE TABLE foo2(a int, b text);
INSERT INTO foo2 VALUES(42, '!!!!');
INSERT INTO foo2 VALUES(42, '????');
INSERT INTO foo2 VALUES(42, '####');
INSERT INTO foo2 VALUES(45, '$$$$');

CREATE OR REPLACE FUNCTION getfoo(int) RETURNS SETOF text AS '
   SELECT b FROM foo WHERE a = $1
' language 'sql';

CREATE OR REPLACE FUNCTION getfoo2(int) RETURNS SETOF text AS '
   SELECT b FROM foo2 WHERE a = $1
' language 'sql';

regression=# SELECT f1, f2, getfoo(f3) AS f4 FROM bar;
  f1 |  f2   |    f4
----+-------+----------
   1 | Hello | World
   1 | Hello | Everyone
   2 | Happy | Birthday
   2 | Happy | New Year
(4 rows)

regression=# SELECT f1, f2, getfoo(f3) AS f4, getfoo2(f3) AS f5 FROM bar;
ERROR:  Only one target list entry may return a set result


Joe Conway
2003-02-13 05:06:35 +00:00
Tom Lane c5ba16a83c Get rid of last few vestiges of parsetree dependency on grammar token
codes, per discussion from last March.  parse.h should now be included
*only* by gram.y, scan.l, keywords.c, parser.c.  This prevents surprising
misbehavior after seemingly-trivial grammar adjustments.
2003-02-10 04:44:47 +00:00
Tom Lane 39b7ec3309 Create a distinction between Lists of integers and Lists of OIDs, to get
rid of the assumption that sizeof(Oid)==sizeof(int).  This is one small
step towards someday supporting 8-byte OIDs.  For the moment, it doesn't
do much except get rid of a lot of unsightly casts.
2003-02-09 06:56:28 +00:00
Tom Lane c15a4c2aef Replace planner's representation of relation sets, per pghackers discussion.
Instead of Lists of integers, we now store variable-length bitmap sets.
This should be faster as well as less error-prone.
2003-02-08 20:20:55 +00:00
Tom Lane 260faf0b63 Fix ALTER TABLE ADD COLUMN to disallow the same column types that are
disallowed by CREATE TABLE (eg, pseudo-types); also disallow these types
from being introduced by the range-function syntax.  While at it, allow
CREATE TABLE to create zero-column tables, per recent pghackers discussion.
I am back-patching this into 7.3 since failure to disallow pseudo-types
is arguably a security hole.
2002-12-16 18:39:22 +00:00
Tom Lane b0422b215c Preliminary code review for domain CHECK constraints patch: add documentation,
make VALUE a non-reserved word again, use less invasive method of passing
ConstraintTestValue into transformExpr, fix problems with nested constraint
testing, do correct thing with NULL result from a constraint expression,
remove memory leak.  Domain checks still need much more work if we are going
to allow ALTER DOMAIN, however.
2002-12-12 20:35:16 +00:00
Tom Lane a0bf885f9e Phase 2 of read-only-plans project: restructure expression-tree nodes
so that all executable expression nodes inherit from a common supertype
Expr.  This is somewhat of an exercise in code purity rather than any
real functional advance, but getting rid of the extra Oper or Func node
formerly used in each operator or function call should provide at least
a little space and speed improvement.
initdb forced by changes in stored-rules representation.
2002-12-12 15:49:42 +00:00
Tom Lane f68f11928d Tighten selection of equality and ordering operators for grouping
operations: make sure we use operators that are compatible, as determined
by a mergejoin link in pg_operator.  Also, add code to planner to ensure
we don't try to use hashed grouping when the grouping operators aren't
marked hashable.
2002-11-29 21:39:12 +00:00
Bruce Momjian 6b603e67dc Add DOMAIN check constraints.
Rod Taylor
2002-11-15 02:50:21 +00:00
Tom Lane b26dfb9522 Extend pg_cast castimplicit column to a three-way value; this allows us
to be flexible about assignment casts without introducing ambiguity in
operator/function resolution.  Introduce a well-defined promotion hierarchy
for numeric datatypes (int2->int4->int8->numeric->float4->float8).
Change make_const to initially label numeric literals as int4, int8, or
numeric (never float8 anymore).
Explicitly mark Func and RelabelType nodes to indicate whether they came
from a function call, explicit cast, or implicit cast; use this to do
reverse-listing more accurately and without so many heuristics.
Explicit casts to char, varchar, bit, varbit will truncate or pad without
raising an error (the pre-7.2 behavior), while assigning to a column without
any explicit cast will still raise an error for wrong-length data like 7.3.
This more nearly follows the SQL spec than 7.2 behavior (we should be
reporting a 'completion condition' in the explicit-cast cases, but we have
no mechanism for that, so just do silent truncation).
Fix some problems with enforcement of typmod for array elements;
it didn't work at all in 'UPDATE ... SET array[n] = foo', for example.
Provide a generalized array_length_coerce() function to replace the
specialized per-array-type functions that used to be needed (and were
missing for NUMERIC as well as all the datetime types).
Add missing conversions int8<->float4, text<->numeric, oid<->int8.
initdb forced.
2002-09-18 21:35:25 +00:00
Bruce Momjian e50f52a074 pgindent run. 2002-09-04 20:31:48 +00:00
Tom Lane 22bfa72068 Remove optimization whereby parser would make only one sort-list entry
when two equal() targetlist items were to be added to an ORDER BY or
DISTINCT list.  Although indeed this would make sorting fractionally
faster by sometimes saving a comparison, it confuses the heck out of
later stages of processing, because it makes it look like the user
wrote DISTINCT ON rather than DISTINCT.  Bug reported by joe@piscitella.com.
2002-08-18 18:46:15 +00:00
Bruce Momjian 9218689b69 Attached are two patches to implement and document anonymous composite
types for Table Functions, as previously proposed on HACKERS. Here is a
brief explanation:

1. Creates a new pg_type typtype: 'p' for pseudo type (currently either
     'b' for base or 'c' for catalog, i.e. a class).

2. Creates new builtin type of typtype='p' named RECORD. This is the
     first of potentially several pseudo types.

3. Modify FROM clause grammer to accept:
     SELECT * FROM my_func() AS m(colname1 type1, colname2 type1, ...)
     where m is the table alias, colname1, etc are the column names, and
     type1, etc are the column types.

4. When typtype == 'p' and the function return type is RECORD, a list
     of column defs is required, and when typtype != 'p', it is
disallowed.

5. A check was added to ensure that the tupdesc provide via the parser
     and the actual return tupdesc match in number and type of
attributes.

When creating a function you can do:
     CREATE FUNCTION foo(text) RETURNS setof RECORD ...

When using it you can do:
     SELECT * from foo(sqlstmt) AS (f1 int, f2 text, f3 timestamp)
       or
     SELECT * from foo(sqlstmt) AS f(f1 int, f2 text, f3 timestamp)
       or
     SELECT * from foo(sqlstmt) f(f1 int, f2 text, f3 timestamp)

Included in the patches are adjustments to the regression test sql and
expected files, and documentation.

p.s.
     This potentially solves (or at least improves) the issue of builtin
     Table Functions. They can be bootstrapped as returning RECORD, and
     we can wrap system views around them with properly specified column
     defs. For example:

     CREATE VIEW pg_settings AS
       SELECT s.name, s.setting
       FROM show_all_settings()AS s(name text, setting text);

     Then we can also add the UPDATE RULE that I previously posted to
     pg_settings, and have pg_settings act like a virtual table, allowing
     settings to be queried and set.


Joe Conway
2002-08-04 19:48:11 +00:00
Bruce Momjian d84fe82230 Update copyright to 2002. 2002-06-20 20:29:54 +00:00
Tom Lane a5b370943e Teach query_tree_walker, query_tree_mutator, and SS_finalize_plan to
process function RTE expressions, which they were previously missing.
This allows outer-Var references and subselects to work correctly in
the arguments of a function RTE.  Install check to prevent function RTEs
from cross-referencing Vars of sibling FROM-items, which doesn't make
any sense (if you want to join, write a JOIN or WHERE clause).
2002-05-18 18:49:41 +00:00
Tom Lane 3389a110d4 Get rid of long-since-vestigial Iter node type, in favor of adding a
returns-set boolean field in Func and Oper nodes.  This allows cleaner,
more reliable tests for expressions returning sets in the planner and
parser.  For example, a WHERE clause returning a set is now detected
and complained of in the parser, not only at runtime.
2002-05-12 23:43:04 +00:00
Tom Lane f9e4f611a1 First pass at set-returning-functions in FROM, by Joe Conway with
some kibitzing from Tom Lane.  Not everything works yet, and there's
no documentation or regression test, but let's commit this so Joe
doesn't need to cope with tracking changes in so many files ...
2002-05-12 20:10:05 +00:00
Tom Lane 6c59886942 Second try at fixing join alias variables. Instead of attaching miscellaneous
lists to join RTEs, attach a list of Vars and COALESCE expressions that will
replace the join's alias variables during planning.  This simplifies
flatten_join_alias_vars while still making it easy to fix up varno references
when transforming the query tree.  Add regression test cases for interactions
of subqueries with outer joins.
2002-04-28 19:54:29 +00:00
Tom Lane 6cef5d2549 Operators live in namespaces. CREATE/DROP/COMMENT ON OPERATOR take
qualified operator names directly, for example CREATE OPERATOR myschema.+
( ... ).  To qualify an operator name in an expression you need to write
OPERATOR(myschema.+) (thanks to Peter for suggesting an escape hatch).
I also took advantage of having to reformat pg_operator to fix something
that'd been bugging me for a while: mergejoinable operators should have
explicit links to the associated cross-data-type comparison operators,
rather than hardwiring an assumption that they are named < and >.
2002-04-16 23:08:12 +00:00
Tom Lane 3767970cbf Fix oversight in recent change of representation for JOIN alias
variables: JOIN/ON should allow references to contained JOINs.
Per bug report from Barry Lind.
2002-04-15 06:05:49 +00:00
Tom Lane 1dbf8aa7a8 pg_class has a relnamespace column. You can create and access tables
in schemas other than the system namespace; however, there's no search
path yet, and not all operations work yet on tables outside the system
namespace.
2002-03-26 19:17:02 +00:00
Tom Lane 108a0ec87d A little further progress on schemas: push down RangeVars into
addRangeTableEntry calls.  Remove relname field from RTEs, since
it will no longer be a useful unique identifier of relations;
we want to encourage people to rely on the relation OID instead.
Further work on dumping qual expressions in EXPLAIN, too.
2002-03-22 02:56:37 +00:00
Tom Lane 95ef6a3448 First phase of SCHEMA changes, concentrating on fixing the grammar and
the parsetree representation.  As yet we don't *do* anything with schema
names, just drop 'em on the floor; but you can enter schema-compatible
command syntax, and there's even a primitive CREATE SCHEMA command.
No doc updates yet, except to note that you can now extract a field
from a function-returning-row's result with (foo(...)).fieldname.
2002-03-21 16:02:16 +00:00
Tom Lane 6eeb95f0f5 Restructure representation of join alias variables. An explicit JOIN
now has an RTE of its own, and references to its outputs now are Vars
referencing the JOIN RTE, rather than CASE-expressions.  This allows
reverse-listing in ruleutils.c to use the correct alias easily, rather
than painfully reverse-engineering the alias namespace as it used to do.
Also, nested FULL JOINs work correctly, because the result of the inner
joins are simple Vars that the planner can cope with.  This fixes a bug
reported a couple times now, notably by Tatsuo on 18-Nov-01.  The alias
Vars are expanded into COALESCE expressions where needed at the very end
of planning, rather than during parsing.
Also, beginnings of support for showing plan qualifier expressions in
EXPLAIN.  There are probably still cases that need work.
initdb forced due to change of stored-rule representation.
2002-03-12 00:52:10 +00:00
Bruce Momjian b81844b173 pgindent run on all C files. Java run to follow. initdb/regression
tests pass.
2001-10-25 05:50:21 +00:00
Peter Eisentraut 2e57875b97 Use format_type sibling in backend error messages, so the user sees
consistent type naming.
2001-08-09 18:28:18 +00:00
Tom Lane 116d2bba7e Add IS UNKNOWN, IS NOT UNKNOWN boolean tests, fix the existing boolean
tests to return the correct results per SQL9x when given NULL inputs.
Reimplement these tests as well as IS [NOT] NULL to have their own
expression node types, instead of depending on special functions.
From Joe Conway, with a little help from Tom Lane.
2001-06-19 22:39:12 +00:00
Bruce Momjian dc0ff5c67a Small code cleanups,formatting. 2001-05-18 21:24:20 +00:00
Bruce Momjian 0686d49da0 Remove dashes in comments that don't need them, rewrap with pgindent. 2001-03-22 06:16:21 +00:00
Bruce Momjian 9e1552607a pgindent run. Make it all clean. 2001-03-22 04:01:46 +00:00
Tom Lane 13cc7eb3e2 Clean up two rather nasty bugs in operator selection code.
1. If there is exactly one pg_operator entry of the right name and oprkind,
oper() and related routines would return that entry whether its input type
had anything to do with the request or not.  This is just premature
optimization: we shouldn't return the single candidate until after we verify
that it really is a valid candidate, ie, is at least coercion-compatible
with the given types.

2. oper() and related routines only promise a coercion-compatible result.
Unfortunately, there were quite a few callers that assumed the returned
operator is binary-compatible with the given datatype; they would proceed
to call it without making any datatype coercions.  These callers include
sorting, grouping, aggregation, and VACUUM ANALYZE.  In general I think
it is appropriate for these callers to require an exact or binary-compatible
match, so I've added a new routine compatible_oper() that only succeeds if
it can find an operator that doesn't require any run-time conversions.
Callers now call oper() or compatible_oper() depending on whether they are
prepared to deal with type conversion or not.

The upshot of these bugs is revealed by the following silliness in PL/Tcl's
selftest: it creates an operator @< on int4, and then tries to use it to
sort a char(N) column.  The system would let it do that :-( (and evidently
has done so since 6.3 :-( :-().  The result in this case was just a silly
sort order, but the reverse combination would've provoked coredump from
trying to dereference integers.  With this fix you get more reasonable
behavior:
pltcl_test=# select * from T_pkey1 order by key1, key2 using @<;
ERROR:  Unable to identify an operator '@<' for types 'bpchar' and 'bpchar'
        You will have to retype this query using an explicit cast
2001-02-16 03:16:58 +00:00
Tom Lane 4a66f9dd54 Change scoping of table and join refnames to conform to SQL92: a JOIN
clause with an alias is a <subquery> and therefore hides table references
appearing within it, according to the spec.  This is the same as the
preliminary patch I posted to pgsql-patches yesterday, plus some really
grotty code in ruleutils.c to reverse-list a query tree with the correct
alias name depending on context.  I'd rather not have done that, but unless
we want to force another initdb for 7.1, there's no other way for now.
2001-02-14 21:35:07 +00:00
Bruce Momjian 623bf843d2 Change Copyright from PostgreSQL, Inc to PostgreSQL Global Development Group. 2001-01-24 19:43:33 +00:00
Tom Lane 2fb6cc9045 Remove not-really-standard implementation of CREATE TABLE's UNDER clause,
and revert documentation to describe the existing INHERITS clause
instead, per recent discussion in pghackers.  Also fix implementation
of SQL_inheritance SET variable: it is not cool to look at this var
during the initial parsing phase, only during parse_analyze().  See
recent bug report concerning misinterpretation of date constants just
after a SET TIMEZONE command.  gram.y really has to be an invariant
transformation of the query string to a raw parsetree; anything that
can vary with time must be done during parse analysis.
2001-01-05 06:34:23 +00:00
Tom Lane a933ee38bb Change SearchSysCache coding conventions so that a reference count is
maintained for each cache entry.  A cache entry will not be freed until
the matching ReleaseSysCache call has been executed.  This eliminates
worries about cache entries getting dropped while still in use.  See
my posting to pg-hackers of even date for more info.
2000-11-16 22:30:52 +00:00
Tom Lane 6543d81d65 Restructure handling of inheritance queries so that they work with outer
joins, and clean things up a good deal at the same time.  Append plan node
no longer hacks on rangetable at runtime --- instead, all child tables are
given their own RT entries during planning.  Concept of multiple target
tables pushed up into execMain, replacing bug-prone implementation within
nodeAppend.  Planner now supports generating Append plans for inheritance
sets either at the top of the plan (the old way) or at the bottom.  Expanding
at the bottom is appropriate for tables used as sources, since they may
appear inside an outer join; but we must still expand at the top when the
target of an UPDATE or DELETE is an inheritance set, because we actually need
a different targetlist and junkfilter for each target table in that case.
Fortunately a target table can't be inside an outer join...  Bizarre mutual
recursion between union_planner and prepunion.c is gone --- in fact,
union_planner doesn't really have much to do with union queries anymore,
so I renamed it grouping_planner.
2000-11-12 00:37:02 +00:00
Tom Lane 3908473c80 Make DROP TABLE rollback-able: postpone physical file delete until commit.
(WAL logging for this is not done yet, however.)  Clean up a number of really
crufty things that are no longer needed now that DROP behaves nicely.  Make
temp table mapper do the right things when drop or rename affecting a temp
table is rolled back.  Also, remove "relation modified while in use" error
check, in favor of locking tables at first reference and holding that lock
throughout the statement.
2000-11-08 22:10:03 +00:00
Tom Lane fbd26d6984 Arrange that no database accesses are attempted during parser() --- this
took some rejiggering of typename and ACL parsing, as well as moving
parse_analyze call out of parser().  Restructure postgres.c processing
so that parse analysis and rewrite are skipped when in abort-transaction
state.  Only COMMIT and ABORT statements will be processed beyond the raw
parser() phase.  This addresses problem of parser failing with database access
errors while in aborted state (see pghackers discussions around 7/28/00).
Also fix some bugs with COMMIT/ABORT statements appearing in the middle of
a single query input string.
Function, operator, and aggregate arguments/results can now use full
TypeName production, in particular foo[] for array types.
DROP OPERATOR and COMMENT ON OPERATOR were broken for unary operators.
Allow CREATE AGGREGATE to accept unquoted numeric constants for initcond.
2000-10-07 00:58:23 +00:00
Tom Lane 05e3d0ee86 Reimplementation of UNION/INTERSECT/EXCEPT. INTERSECT/EXCEPT now meet the
SQL92 semantics, including support for ALL option.  All three can be used
in subqueries and views.  DISTINCT and ORDER BY work now in views, too.
This rewrite fixes many problems with cross-datatype UNIONs and INSERT/SELECT
where the SELECT yields different datatypes than the INSERT needs.  I did
that by making UNION subqueries and SELECT in INSERT be treated like
subselects-in-FROM, thereby allowing an extra level of targetlist where the
datatype conversions can be inserted safely.
INITDB NEEDED!
2000-10-05 19:11:39 +00:00
Tom Lane 3a94e789f5 Subselects in FROM clause, per ISO syntax: FROM (SELECT ...) [AS] alias.
(Don't forget that an alias is required.)  Views reimplemented as expanding
to subselect-in-FROM.  Grouping, aggregates, DISTINCT in views actually
work now (he says optimistically).  No UNION support in subselects/views
yet, but I have some ideas about that.  Rule-related permissions checking
moved out of rewriter and into executor.
INITDB REQUIRED!
2000-09-29 18:21:41 +00:00
Tom Lane aef7a0c8ea Parse JOIN/ON conditions with the proper visibility of input columns,
ie, consider only the columns coming from the JOIN clause's sub-clauses.
Also detect attempts to reference columns belonging to other tables
(which would still be possible using an explicitly-qualified name).
I'm not sure this implements the spec's semantics 100% accurately, but
at least it gives plausible behavior.
2000-09-17 22:21:27 +00:00
Tom Lane ed5003c584 First cut at full support for OUTER JOINs. There are still a few loose
ends to clean up (see my message of same date to pghackers), but mostly
it works.  INITDB REQUIRED!
2000-09-12 21:07:18 +00:00
Bruce Momjian df43800fc8 Clean up #include's. 2000-06-15 03:33:12 +00:00
Bruce Momjian 8c1d09d591 Inheritance overhaul by Chris Bitmead <chris@bitmead.com> 2000-06-09 01:44:34 +00:00
Bruce Momjian 20ad43b576 Mark functions as static and ifdef NOT_USED as appropriate. 2000-06-08 22:38:00 +00:00
Bruce Momjian a12a23f0d0 Remove unused include files. Do not touch /port or includes used by defines. 2000-05-30 00:49:57 +00:00
Tom Lane 091126fa28 Generated header files parse.h and fmgroids.h are now copied into
the src/include tree, so that -I backend is no longer necessary anywhere.
Also, clean up some bit rot in contrib tree.
2000-05-29 05:45:56 +00:00
Tom Lane 01911c98db Repair list-vs-node confusion that resulted in failure for INNER JOIN ON.
Make it behave correctly when there are more than two tables being
joined, also.  Update regression test expected outputs.
2000-05-12 01:33:56 +00:00
Bruce Momjian 52f77df613 Ye-old pgindent run. Same 4-space tabs. 2000-04-12 17:17:23 +00:00
Tom Lane 37ab088770 Remove no-longer-necessary restriction against uplevel correlation vars
outside WHERE clause.  Fix a couple of places that didn't handle uplevel
refs cleanly.
2000-03-23 07:38:30 +00:00
Tom Lane 1763a7c1ea Tweak GROUP BY so that it will still accept result-column names, but only
after trying to resolve the item as an input-column name.  This allows us
to be compliant with the SQL92 spec for queries that fall within the spec,
while still accepting the same out-of-spec queries as 6.5 did.  You'll only
lose if there is an output column name that is the same as an input
column name, but doesn't refer to the same value.  7.0 will interpret
such a GROUP BY spec differently than 6.5 did.  No way around that, because
6.5 was clearly not spec compliant.
2000-03-15 23:31:19 +00:00
Thomas G. Lockhart 6456810078 Implement column aliases on views "CREATE VIEW name (collist)".
Implement TIME WITH TIME ZONE type (timetz internal type).
Remap length() for character strings to CHAR_LENGTH() for SQL92
 and to remove the ambiguity with geometric length() functions.
Keep length() for character strings for backward compatibility.
Shrink stored views by removing internal column name list from visible rte.
Implement min(), max() for time and timetz data types.
Implement conversion of TIME to INTERVAL.
Implement abs(), mod(), fac() for the int8 data type.
Rename some math functions to generic names:
 round(), sqrt(), cbrt(), pow(), etc.
Rename NUMERIC power() function to pow().
Fix int2 factorial to calculate result in int4.
Enhance the Oracle compatibility function translate() to work with string
 arguments (from Edwin Ramirez).
Modify pg_proc system table to remove OID holes.
2000-03-14 23:06:59 +00:00
Tom Lane 751a14e60c Repair longstanding violation of SQL92 semantics: GROUP BY would
interpret a column name as an output column alias (targetlist AS name),
ather than a real column name as it ought to.  According to the spec,
only ORDER BY should look at output column names.  I left in GROUP BY's
willingness to use an output column number ('GROUP BY 2'), even though
this is also contrary to the spec --- again, only ORDER BY is supposed
to accept that.  But there is no possible reason to want to GROUP BY
an integer constant, so keeping this old behavior won't break any
SQL-compliant queries.  DISTINCT ON will behave the same as GROUP BY.

Change numerology regress test, which depended on the incorrect
behavior.
2000-02-19 23:45:07 +00:00
Tom Lane 90e160beff Fix missing lfirst() in ListTableAsAttrs(). This code
doesn't seem to be used at the moment, but as long as I'm looking at it...
2000-02-15 23:09:08 +00:00
Tom Lane 1204c3e964 Remove some // comments, which are not ANSI C last I heard. 2000-02-15 07:47:37 +00:00
Thomas G. Lockhart a344a6e7b5 Carry column aliases from the parser frontend. Enables queries like
SELECT a FROM t1 tx (a);
Allow join syntax, including queries like
  SELECT * FROM t1 NATURAL JOIN t2;
Update RTE structure to hold column aliases in an Attr structure.
2000-02-15 03:38:29 +00:00
Tom Lane dd979f66be Redesign DISTINCT ON as discussed in pgsql-sql 1/25/00: syntax is now
SELECT DISTINCT ON (expr [, expr ...]) targetlist ...
and there is a check to make sure that the user didn't specify an ORDER BY
that's incompatible with the DISTINCT operation.
Reimplement nodeUnique and nodeGroup to use the proper datatype-specific
equality function for each column being compared --- they used to do
bitwise comparisons or convert the data to text strings and strcmp().
(To add insult to injury, they'd look up the conversion functions once
for each tuple...)  Parse/plan representation of DISTINCT is now a list
of SortClause nodes.
initdb forced by querytree change...
2000-01-27 18:11:50 +00:00
Bruce Momjian 5c25d60244 Add:
* Portions Copyright (c) 1996-2000, PostgreSQL, Inc

to all files copyright Regents of Berkeley.  Man, that's a lot of files.
2000-01-26 05:58:53 +00:00
Tom Lane ac4878a060 Pass atttypmod to CoerceTargetExpr, so that it can pass it on to
coerce_type, so that the right things happen when coercing a previously-
unknown constant to a destination data type.
2000-01-17 02:04:16 +00:00
Thomas G. Lockhart aac9f5bee8 Re-enable makeAttr() if ENABLE_OUTER_JOINS is defined.
Somehow got bracketed with #ifdef NOT_USED instead.
1999-12-17 14:47:35 +00:00
Bruce Momjian 0e1bfe92c7 I have a patch for postgresql-snapshot(1999-10-22).
This patch fix a TODO list item.
* require SELECT DISTINCT target list to have all ORDER BY columns

example
ogawa=> select distinct x from t1 order by y;
ERROR:  ORDER BY columns must appear in SELECT DISTINCT target list

---
Atsushi Ogawa
1999-10-22 11:51:35 +00:00
Tom Lane 3eb1c82277 Fix planner and rewriter to follow SQL semantics for tables that are
mentioned in FROM but not elsewhere in the query: such tables should be
joined over anyway.  Aside from being more standards-compliant, this allows
removal of some very ugly hacks for COUNT(*) processing.  Also, allow
HAVING clause without aggregate functions, since SQL does.  Clean up
CREATE RULE statement-list syntax the same way Bruce just fixed the
main stmtmulti production.
CAUTION: addition of a field to RangeTblEntry nodes breaks stored rules;
you will have to initdb if you have any rules.
1999-10-07 04:23:24 +00:00
Tom Lane bd272cace6 Mega-commit to make heap_open/heap_openr/heap_close take an
additional argument specifying the kind of lock to acquire/release (or
'NoLock' to do no lock processing).  Ensure that all relations are locked
with some appropriate lock level before being examined --- this ensures
that relevant shared-inval messages have been processed and should prevent
problems caused by concurrent VACUUM.  Fix several bugs having to do with
mismatched increment/decrement of relation ref count and mismatched
heap_open/close (which amounts to the same thing).  A bogus ref count on
a relation doesn't matter much *unless* a SI Inval message happens to
arrive at the wrong time, which is probably why we got away with this
sloppiness for so long.  Repair missing grab of AccessExclusiveLock in
DROP TABLE, ALTER/RENAME TABLE, etc, as noted by Hiroshi.
Recommend 'make clean all' after pulling this update; I modified the
Relation struct layout slightly.
Will post further discussion to pghackers list shortly.
1999-09-18 19:08:25 +00:00
Tom Lane db436adf76 Major revision of sort-node handling: push knowledge of query
sort order down into planner, instead of handling it only at the very top
level of the planner.  This fixes many things.  An explicit sort is now
avoided if there is a cheaper alternative (typically an indexscan) not
only for ORDER BY, but also for the internal sort of GROUP BY.  It works
even when there is no other reason (such as a WHERE condition) to consider
the indexscan.  It works for indexes on functions.  It works for indexes
on functions, backwards.  It's just so cool...

CAUTION: I have changed the representation of SortClause nodes, therefore
THIS UPDATE BREAKS STORED RULES.  You will need to initdb.
1999-08-21 03:49:17 +00:00
Tom Lane 08320bfb22 Small updates to #include lists for pending optimizer checkin. 1999-08-16 02:10:13 +00:00
Tom Lane 7f76eab140 Rewrite parser's handling of INSERT ... SELECT so that processing
of the SELECT part of the statement is just like a plain SELECT.  All
INSERT-specific processing happens after the SELECT parsing is done.
This eliminates many problems, e.g. INSERT ... SELECT ... GROUP BY using
the wrong column labels.  Ensure that DEFAULT clauses are coerced to
the target column type, whether or not stored clause produces the right
type.  Substantial cleanup of parser's array support.
1999-07-19 00:26:20 +00:00
Bruce Momjian 3406901a29 Move some system includes into c.h, and remove duplicates. 1999-07-17 20:18:55 +00:00
Bruce Momjian a71802e12e Final cleanup. 1999-07-16 05:00:38 +00:00
Bruce Momjian 2e6b1e63a3 Remove unused #includes in *.c files. 1999-07-15 22:40:16 +00:00
Bruce Momjian 4b2c2850bf Clean up #include in /include directory. Add scripts for checking includes. 1999-07-15 15:21:54 +00:00
Bruce Momjian 278bbf4572 Make functions static or NOT_USED as appropriate. 1999-05-26 12:57:23 +00:00
Bruce Momjian 07842084fe pgindent run over code. 1999-05-25 16:15:34 +00:00
Bruce Momjian 9710995fc9 Make postgres prompt backend>, and remove PARSEDEBUG. 1999-05-22 02:55:58 +00:00
Bruce Momjian 19c4e862d4 Skip junk nodes when comparing UNION target list lengths. 1999-05-17 18:22:19 +00:00
Bruce Momjian 585c967720 Change resjunk to a boolean. 1999-05-17 17:03:51 +00:00
Thomas G. Lockhart 81c83db3bb Surround a variable declaration with ENABLE_OUTER_JOINS to suppress
compiler warnings about an unused variable.
1999-05-13 14:59:05 +00:00
Tom Lane 507a0a2ab0 Rip out QueryTreeList structure, root and branch. Querytree
lists are now plain old garden-variety Lists, allocated with palloc,
rather than specialized expansible-array data allocated with malloc.
This substantially simplifies their handling and eliminates several
sources of memory leakage.
Several basic types of erroneous queries (syntax error, attempt to
insert a duplicate key into a unique index) now demonstrably leak
zero bytes per query.
1999-05-13 07:29:22 +00:00
Jan Wieck 79c2576f77 Replaced targetlist entry in GroupClause by reference number
in Resdom and GroupClause so changing of resno's doesn't confuse
the grouping any more.

Jan
1999-05-12 15:02:39 +00:00
Thomas G. Lockhart b4def32439 Include some new code for outer joins. Disabled by default, but enable by
including the following in your Makefile.custom:
 CFLAGS+= -DENABLE_OUTER_JOINS -DEXEC_MERGEJOINDEBUG
1999-02-23 07:46:42 +00:00
Bruce Momjian 6724a50787 Change my-function-name-- to my_function_name, and optimizer renames. 1999-02-13 23:22:53 +00:00
Jan Wieck 7ab88a16a1 Fixed failed assertion happening in multiple action rules
when parsestate in makeRangeTable() already contains an
opened p_target_relation.

Jan
1999-02-02 12:57:51 +00:00
Thomas G. Lockhart ee88006cf2 Clean up code in analyze.c for SERIAL data type.
Remove _all_ PARSEDEBUG print statements.
1998-09-25 13:36:08 +00:00
Bruce Momjian fa1a8d6a97 OK, folks, here is the pgindent output. 1998-09-01 04:40:42 +00:00
Bruce Momjian 0fc13f582a Make sure resdomno for update/insert match attribute number for
rewrite system.  Restructure parse_target to make it easier to
understand.
1998-08-25 03:17:29 +00:00
Marc G. Fournier a1627a1d64 From: David Hartwig <daybee@bellatlantic.net>
I have attached a patch to allow GROUP BY and/or ORDER BY function or
expressions.  Note worthy items:

1. The expression or function need not be in the target list.
Example:
            SELECT  name FROM foo GROUP BY lower(name);

2.   Simplified the grammar to use expressions only.

3.  Cleaned up earlier patch in this area to make use of existing
utility functions.

3.  Reduced some of the members in the SortGroupBy parse node.   The
original data members were redundant with the new expression node.
(MUST do a "make clean" now)

4.  Added a new parse node "JoinUsing".   The JOIN USING clause was
overloading this SortGroupBy structure.   With the afore mentioned
reduction of members, the two clauses lost all their commonality.

5.  A bug still exist where, if a function or expression is GROUPed BY,
and an aggregate function does not include a attribute from the
expression or function, the backend crashes.   (or something like
that)   The bug pre-dates this patch.    Example:

    SELECT lower(a) AS lowcase, count(b) FROM foo GROUP BY lowcase;
                 *** BOOM  ***

    --Also when not in target list
    SELECT  count(b) FROM foo GROUP BY lower(a);
                *** BOOM  AGAIN ***
1998-08-05 04:49:19 +00:00
Thomas G. Lockhart 7665e7b0a8 Allows the following query to succeed: "SELECT NULL ORDER BY 1;"
There are three or four cases in transformSortClause() and I had fixed
only one case for UNION. A second case is now fixed, in the same way; I
assigned INT4OID to the column type for the "won't actually happen"
sort. Didn't want to skip the code entirely, since the backend needs to
_try_ a sort to get the NULLs right. I'm not certain under what
circumstances the other cases are invoked and these are not yet
fixed up, though perhaps they don't need to be...
1998-08-02 13:34:26 +00:00
Thomas G. Lockhart 9fdbbdc877 Fix for UNION selects with constant NULL expressions; e.g.
SELECT 1 UNION SELECT NULL;
1998-07-14 03:51:42 +00:00
Thomas G. Lockhart fa2a1d7d52 Handle case of GROUP BY target list column number out of range. 1998-07-09 14:34:05 +00:00
Thomas G. Lockhart 92ed9294de Allow floating point constants for "def_arg" numeric arguments.
Used in the generic "CREATE xxx" parsing.
Do some automatic type conversion for inserts from other columns.
Previous trouble with "resjunk" regression test remains for now.
1998-07-08 14:04:11 +00:00
Bruce Momjian 2e6159311a I made several adjustments to my earlier patch to handle the
condition where the target label is ambiguous.
1998-06-05 03:49:20 +00:00
Thomas G. Lockhart 8536c96261 Do type conversion to match columns in UNION clauses.
Currently force the type to match the _first_ select in the union.
Move oper_select_candidate() from parse_func.c to parse_oper.c.
Throw error inside of oper_inexact() if no match for binary operators.
Check more carefully that types can be coerced
 even if there is only one candidate operator in oper_inexact().
Fix up error messages for more uniform look.
Remove unused code.
Fix up comments.
1998-05-29 14:00:24 +00:00
Marc G. Fournier 9f3d63936b From: David Hartwig <daveh@insightdist.com>
Here is a patch to remove the requirement that ORDER/GROUP BY clause
identifiers be included in the target list.
1998-05-21 03:53:51 +00:00
Bruce Momjian d7050cb68c Merge rename name page into alter table. Fix UNION with DISTINCT
or ORDER BY bug.
1998-03-31 04:44:35 +00:00
Bruce Momjian c530fbfb2f Add checks for UNION target fields, and add optional TABLE to LOCK
and SELECT manual pages and psql help.
1998-03-18 15:49:08 +00:00
Bruce Momjian a32450a585 pgindent run before 6.3 release, with Thomas' requested changes. 1998-02-26 04:46:47 +00:00
Bruce Momjian 7e46348e62 FIx for regression-test found bug. 1998-01-20 22:55:25 +00:00
Bruce Momjian 7f31669bea Add Var.varlevelup to code. More parser cleanup. 1998-01-20 22:12:17 +00:00
Bruce Momjian 412a5e6539 Parser cleanup.
Add lock to i386 asm.
1998-01-20 05:05:08 +00:00
Bruce Momjian 588867bd7b Create SubLink nodes in parser for Vadim. 1998-01-19 05:06:41 +00:00
Bruce Momjian e22b09c227 Fix sorting of multiple fields broken with UNION. 1998-01-06 23:58:05 +00:00
Bruce Momjian 0d9fc5afd6 Change elog(WARN) to elog(ERROR) and elog(ABORT). 1998-01-05 03:35:55 +00:00
Bruce Momjian a1dd409053 Fix for ORDER BY in UNION. 1997-12-29 04:31:50 +00:00
Bruce Momjian 499b13c994 UNION cleanup again. 1997-12-29 02:09:54 +00:00
Bruce Momjian a01b085c78 Cleanup of UNION ALL fix. Manual page updates. 1997-12-29 01:13:37 +00:00
Bruce Momjian b704426618 Make parser functions static where possible. 1997-11-26 03:43:18 +00:00
Bruce Momjian 598e86f3b3 Cleanup up include files. 1997-11-26 01:14:33 +00:00
Bruce Momjian 4a5b781d71 Break parser functions into smaller files, group together. 1997-11-25 22:07:18 +00:00