Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
SQL statements can, intentionally or not, require the mixing of different data types in the same expression. PostgreSQL has extensive facilities for evaluating mixed-type expressions.
In many cases a user does not need to understand the details of the type conversion mechanism. However, implicit conversions done by PostgreSQL can affect the results of a query. When necessary, these results can be tailored by using explicit type conversion.
This chapter introduces the PostgreSQL type conversion mechanisms and conventions. Refer to the relevant sections in Chapter 8 and Chapter 9 for more information on specific data types and allowed functions and operators.
版本:11
Values to be inserted into a table are converted to the destination column's data type according to the following steps.
Value Storage Type Conversion
Check for an exact match with the target.
Otherwise, try to convert the expression to the target type. This is possible if an assignment cast between the two types is registered in the pg_cast
catalog (see CREATE CAST). Alternatively, if the expression is an unknown-type literal, the contents of the literal string will be fed to the input conversion routine for the target type.
Check to see if there is a sizing cast for the target type. A sizing cast is a cast from that type to itself. If one is found in the pg_cast
catalog, apply it to the expression before storing into the destination column. The implementation function for such a cast always takes an extra parameter of type integer
, which receives the destination column's atttypmod
value (typically its declared length, although the interpretation of atttypmod
varies for different data types), and it may take a third boolean
parameter that says whether the cast is explicit or implicit. The cast function is responsible for applying any length-dependent semantics such as size checking or truncation.
character
Storage Type ConversionFor a target column declared as character(20)
the following statement shows that the stored value is sized correctly:
What has really happened here is that the two unknown literals are resolved to text
by default, allowing the ||
operator to be resolved as text
concatenation. Then the text
result of the operator is converted to bpchar
(“blank-padded char”, the internal name of the character
data type) to match the target column type. (Since the conversion from text
to bpchar
is binary-coercible, this conversion does not insert any real function call.) Finally, the sizing function bpchar(bpchar, integer, boolean)
is found in the system catalog and applied to the operator's result and the stored column length. This type-specific function performs the required length check and addition of padding spaces.
SQL UNION 結構必須匹配可能不相似的型別才能成為單個結果集合。解析演算法分別套用於合併集合查詢的每個輸出欄位。INTERSECT 和 EXCEPT 結構以與 UNION 相同的方式解析不同型別。CASE,ARRAY,VALUES,GREATEST 和 LEAST 結構使用相同的演算法來匹配其組合表示式並選擇結果資料型別。
UNION,CASE 和相關結構的型別解析
如果所有輸入屬於同一型別且不是未知,就以該型別解析。
如果任何輸入屬於 domain 型別,則將其視為 domain 的基本型別進行所有後續步驟。
註:有點像處理運算子和函數的 domain 輸入,這種行為允許透過 UNION 或類似結構保留 doamin 型別,只要使用者小心確保所有輸入都能確定該型別。否則, domain 的基本型別將是首選。
如果所有輸入都是未知類型,則解析為 text 型別(字串類別的偏好型別)。否則,為了剩餘規則的處理,將忽略未知輸入。
如果非未知輸入不是所有相同的型別類別,則失敗。
選擇第一個非未知輸入型別,如果有,則選擇該類別中的偏好型別。
否則,選擇允許所有前面的非未知輸入直接轉換為它的最後一個非未知輸入型別。 (總是有這樣的型別,因為列表中至少第一個型別必須滿足這個條件。)
將所有輸入轉換為所選型別。如果沒有從給予輸入到所選型別的轉換,則失敗。
一些例子如下。
Example 10.10. 在 UNION 中使用未指定型別輸入解析方案
在這裡,未知型別文字「b」將被解析為 text 型別。\
Example 10.11. 在簡單 UNION 中的型別解析
文字 1.2 是數字型別,整數值 1 可以直接轉換為數字,因此使用該型別。\
Example 10.12. 在轉置 UNION 中的型別轉換
這裡,由於型別 real 不能直接轉換為整數,但整數可以直接轉換為實數,因此 union 結果型別被解析為 real。\
Example 10.13. 在巢狀 UNION 中的型別解析
此失敗是因為 PostgreSQL 將多個 UNION 視為巢狀的成對操作;也就是說,與以下的輸入是相同的
根據上面給予的規則,內部 UNION 被解析為 text。然後外部 UNION 具有 text 和 integer 型別的輸入,導致觀察的錯誤。可以透過確保最左邊的 UNION 至少具有所需結果型別的一種輸入來解決此問題。
INTERSECT 和 EXCEPT 操作同樣成對處理。然而,本節中描述的其他結構同樣在一套解析步驟中考慮它們的所有輸入。 \
The rules given in the preceding sections will result in assignment of non-unknown
data types to all expressions in a SQL query, except for unspecified-type literals that appear as simple output columns of aSELECT
command. For example, in
there is nothing to identify what type the string literal should be taken as. In this situationPostgreSQLwill fall back to resolving the literal's type astext
.
When theSELECT
is one arm of aUNION
(orINTERSECT
orEXCEPT
) construct, or when it appears withinINSERT ... SELECT
, this rule is not applied since rules given in preceding sections take precedence. The type of an unspecified-type literal can be taken from the otherUNION
arm in the first case, or from the destination column in the second case.
RETURNING
lists are treated the same asSELECT
output lists for this purpose.
Prior toPostgreSQL10, this rule did not exist, and unspecified-type literals in aSELECT
output list were left as typeunknown
. That had assorted bad consequences, so it's been changed.
The specific operator that is referenced by an operator expression is determined using the following procedure. Note that this procedure is indirectly affected by the precedence of the operators involved, since that will determine which sub-expressions are taken to be the inputs of which operators. SeeSection 4.1.6for more information.
Operator Type Resolution
Select the operators to be considered from thepg_operator
system catalog. If a non-schema-qualified operator name was used (the usual case), the operators considered are those with the matching name and argument count that are visible in the current search path (seeSection 5.8.3). If a qualified operator name was given, only operators in the specified schema are considered.
If the search path finds multiple operators with identical argument types, only the one appearing earliest in the path is considered. Operators with different argument types are considered on an equal footing regardless of search path position.
Check for an operator accepting exactly the input argument types. If one exists (there can be only one exact match in the set of operators considered), use it.
If one argument of a binary operator invocation is of theunknown
type, then assume it is the same type as the other argument for this check. Invocations involving twounknown
inputs, or a unary operator with anunknown
input, will never find a match at this step.
If one argument of a binary operator invocation is of theunknown
type and the other is of a domain type, next check to see if there is an operator accepting exactly the domain's base type on both sides; if so, use it.
Look for the best match.
Discard candidate operators for which the input types do not match and cannot be converted (using an implicit conversion) to match.unknown
literals are assumed to be convertible to anything for this purpose. If only one candidate remains, use it; else continue to the next step.
If any input argument is of a domain type, treat it as being of the domain's base type for all subsequent steps. This ensures that domains act like their base types for purposes of ambiguous-operator resolution.
Run through all candidates and keep those with the most exact matches on input types. Keep all candidates if none have exact matches. If only one candidate remains, use it; else continue to the next step.
Run through all candidates and keep those that accept preferred types (of the input data type's type category) at the most positions where type conversion will be required. Keep all candidates if none accept preferred types. If only one candidate remains, use it; else continue to the next step.
If any input arguments areunknown
, check the type categories accepted at those argument positions by the remaining candidates. At each position, select thestring
category if any candidate accepts that category. (This bias towards string is appropriate since an unknown-type literal looks like a string.) Otherwise, if all the remaining candidates accept the same type category, select that category; otherwise fail because the correct choice cannot be deduced without more clues. Now discard candidates that do not accept the selected type category. Furthermore, if any candidate accepts a preferred type in that category, discard candidates that accept non-preferred types for that argument. Keep all candidates if none survive these tests. If only one candidate remains, use it; else continue to the next step.
If there are bothunknown
and known-type arguments, and all the known-type arguments have the same type, assume that theunknown
arguments are also of that type, and check which candidates can accept that type at theunknown
-argument positions. If exactly one candidate passes this test, use it. Otherwise, fail.
Some examples follow.
Example 10.1. Factorial Operator Type Resolution
There is only one factorial operator (postfix!
) defined in the standard catalog, and it takes an argument of typebigint
. The scanner assigns an initial type ofinteger
to the argument in this query expression:
So the parser does a type conversion on the operand and the query is equivalent to:
Example 10.2. String Concatenation Operator Type Resolution
A string-like syntax is used for working with string types and for working with complex extension types. Strings with unspecified type are matched with likely operator candidates.
An example with one unspecified argument:
In this case the parser looks to see if there is an operator takingtext
for both arguments. Since there is, it assumes that the second argument should be interpreted as typetext
.
Here is a concatenation of two values of unspecified types:
In this case there is no initial hint for which type to use, since no types are specified in the query. So, the parser looks for all candidate operators and finds that there are candidates accepting both string-category and bit-string-category inputs. Since string category is preferred when available, that category is selected, and then the preferred type for strings,text
, is used as the specific type to resolve the unknown-type literals as.
Example 10.3. Absolute-Value and Negation Operator Type Resolution
ThePostgreSQLoperator catalog has several entries for the prefix operator@
, all of which implement absolute-value operations for various numeric data types. One of these entries is for typefloat8
, which is the preferred type in the numeric category. Therefore,PostgreSQLwill use that entry when faced with anunknown
input:
Here the system has implicitly resolved the unknown-type literal as typefloat8
before applying the chosen operator. We can verify thatfloat8
and not some other type was used:
On the other hand, the prefix operator~
(bitwise negation) is defined only for integer data types, not forfloat8
. So, if we try a similar case with~
, we get:
This happens because the system cannot decide which of the several possible~
operators should be preferred. We can help it out with an explicit cast:
Example 10.4. Array Inclusion Operator Type Resolution
Here is another example of resolving an operator with one known and one unknown input:
ThePostgreSQLoperator catalog has several entries for the infix operator<@
, but the only two that could possibly accept an integer array on the left-hand side are array inclusion (anyarray<@anyarray
) and range inclusion (anyelement<@anyrange
). Since none of these polymorphic pseudo-types (seeSection 8.20) are considered preferred, the parser cannot resolve the ambiguity on that basis. However,Step 3.ftells it to assume that the unknown-type literal is of the same type as the other input, that is, integer array. Now only one of the two operators can match, so array inclusion is selected. (Had range inclusion been selected, we would have gotten an error, because the string does not have the right format to be a range literal.)
Example 10.5. Custom Operator on a Domain Type
Users sometimes try to declare operators applying just to a domain type. This is possible but is not nearly as useful as it might seem, because the operator resolution rules are designed to select operators applying to the domain's base type. As an example consider
This query will not use the custom operator. The parser will first see if there is amytext=mytext
operator (Step 2.a), which there is not; then it will consider the domain's base typetext
, and see if there is atext=text
operator (Step 2.b), which there is; so it resolves theunknown
-type literal astext
and uses thetext=text
operator. The only way to get the custom operator to be used is to explicitly cast the literal:
so that themytext=text
operator is found immediately according to the exact-match rule. If the best-match rules are reached, they actively discriminate against operators on domain types. If they did not, such an operator would create too many ambiguous-operator failures, because the casting rules always consider a domain as castable to or from its base type, and so the domain operator would be considered usable in all the same cases as a similarly-named operator on the base type.
SQLis a strongly typed language. That is, every data item has an associated data type which determines its behavior and allowed usage.PostgreSQLhas an extensible type system that is more general and flexible than otherSQLimplementations. Hence, most type conversion behavior inPostgreSQLis governed by general rules rather than by_ad hoc_heuristics. This allows the use of mixed-type expressions even with user-defined types.
ThePostgreSQLscanner/parser divides lexical elements into five fundamental categories: integers, non-integer numbers, strings, identifiers, and key words. Constants of most non-numeric types are first classified as strings. TheSQLlanguage definition allows specifying type names with strings, and this mechanism can be used inPostgreSQLto start the parser down the correct path. For example, the query:
has two literal constants, of typetext
andpoint
. If a type is not specified for a string literal, then the placeholder typeunknown
is assigned initially, to be resolved in later stages as described below.
There are four fundamentalSQLconstructs requiring distinct type conversion rules in thePostgreSQLparser:
Function calls
Much of thePostgreSQLtype system is built around a rich set of functions. Functions can have one or more arguments. SincePostgreSQLpermits function overloading, the function name alone does not uniquely identify the function to be called; the parser must select the right function based on the data types of the supplied arguments.
Operators
PostgreSQLallows expressions with prefix and postfix unary (one-argument) operators, as well as binary (two-argument) operators. Like functions, operators can be overloaded, so the same problem of selecting the right operator exists.
Value Storage
SQLINSERT
andUPDATE
statements place the results of expressions into a table. The expressions in the statement must be matched up with, and perhaps converted to, the types of the target columns.
UNION
,
CASE
, and related constructs
Since all query results from a unionizedSELECT
statement must appear in a single set of columns, the types of the results of eachSELECT
clause must be matched up and converted to a uniform set. Similarly, the result expressions of aCASE
construct must be converted to a common type so that theCASE
expression as a whole has a known output type. The same holds forARRAY
constructs, and for theGREATEST
andLEAST
functions.
The system catalogs store information about which conversions, or_casts_, exist between which data types, and how to perform those conversions. Additional casts can be added by the user with theCREATE CASTcommand. (This is usually done in conjunction with defining new data types. The set of casts between built-in types has been carefully crafted and is best not altered.)
An additional heuristic provided by the parser allows improved determination of the proper casting behavior among groups of types that have implicit casts. Data types are divided into several basic_type categories_, includingboolean
,numeric
,string
,bitstring
,datetime
,timespan
,geometric
,network
, and user-defined. (For a list seeTable 51.63; but note it is also possible to create custom type categories.) Within each category there can be one or more_preferred types_, which are preferred when there is a choice of possible types. With careful selection of preferred types and available implicit casts, it is possible to ensure that ambiguous expressions (those with multiple candidate parsing solutions) can be resolved in a useful way.
All type conversion rules are designed with several principles in mind:
Implicit conversions should never have surprising or unpredictable outcomes.
There should be no extra overhead in the parser or executor if a query does not need implicit type conversion. That is, if a query is well-formed and the types already match, then the query should execute without spending extra time in the parser and without introducing unnecessary implicit conversion calls in the query.
Additionally, if a query usually requires an implicit conversion for a function, and if then the user defines a new function with the correct argument types, the parser should use this new function and no longer do implicit conversion to use the old function.
The specific function that is referenced by a function call is determined using the following procedure.
Function Type Resolution
Select the functions to be considered from thepg_proc
system catalog. If a non-schema-qualified function name was used, the functions considered are those with the matching name and argument count that are visible in the current search path (seeSection 5.8.3). If a qualified function name was given, only functions in the specified schema are considered.
If the search path finds multiple functions of identical argument types, only the one appearing earliest in the path is considered. Functions of different argument types are considered on an equal footing regardless of search path position.
If a function is declared with aVARIADIC
array parameter, and the call does not use theVARIADIC
keyword, then the function is treated as if the array parameter were replaced by one or more occurrences of its element type, as needed to match the call. After such expansion the function might have effective argument types identical to some non-variadic function. In that case the function appearing earlier in the search path is used, or if the two functions are in the same schema, the non-variadic one is preferred.
Functions that have default values for parameters are considered to match any call that omits zero or more of the defaultable parameter positions. If more than one such function matches a call, the one appearing earliest in the search path is used. If there are two or more such functions in the same schema with identical parameter types in the non-defaulted positions (which is possible if they have different sets of defaultable parameters), the system will not be able to determine which to prefer, and so an“ambiguous function call”error will result if no better match to the call can be found.
Check for a function accepting exactly the input argument types. If one exists (there can be only one exact match in the set of functions considered), use it. (Cases involvingunknown
will never find a match at this step.)
If no exact match is found, see if the function call appears to be a special type conversion request. This happens if the function call has just one argument and the function name is the same as the (internal) name of some data type. Furthermore, the function argument must be either an unknown-type literal, or a type that is binary-coercible to the named data type, or a type that could be converted to the named data type by applying that type's I/O functions (that is, the conversion is either to or from one of the standard string types). When these conditions are met, the function call is treated as a form ofCAST
specification.[8]
Look for the best match.
Discard candidate functions for which the input types do not match and cannot be converted (using an implicit conversion) to match.unknown
literals are assumed to be convertible to anything for this purpose. If only one candidate remains, use it; else continue to the next step.
If any input argument is of a domain type, treat it as being of the domain's base type for all subsequent steps. This ensures that domains act like their base types for purposes of ambiguous-function resolution.
Run through all candidates and keep those with the most exact matches on input types. Keep all candidates if none have exact matches. If only one candidate remains, use it; else continue to the next step.
Run through all candidates and keep those that accept preferred types (of the input data type's type category) at the most positions where type conversion will be required. Keep all candidates if none accept preferred types. If only one candidate remains, use it; else continue to the next step.
If any input arguments areunknown
, check the type categories accepted at those argument positions by the remaining candidates. At each position, select thestring
category if any candidate accepts that category. (This bias towards string is appropriate since an unknown-type literal looks like a string.) Otherwise, if all the remaining candidates accept the same type category, select that category; otherwise fail because the correct choice cannot be deduced without more clues. Now discard candidates that do not accept the selected type category. Furthermore, if any candidate accepts a preferred type in that category, discard candidates that accept non-preferred types for that argument. Keep all candidates if none survive these tests. If only one candidate remains, use it; else continue to the next step.
If there are bothunknown
and known-type arguments, and all the known-type arguments have the same type, assume that theunknown
arguments are also of that type, and check which candidates can accept that type at theunknown
-argument positions. If exactly one candidate passes this test, use it. Otherwise, fail.
Note that the“best match”rules are identical for operator and function type resolution. Some examples follow.
Example 10.6. Rounding Function Argument Type Resolution
There is only oneround
function that takes two arguments; it takes a first argument of typenumeric
and a second argument of typeinteger
. So the following query automatically converts the first argument of typeinteger
tonumeric
:
That query is actually transformed by the parser to:
Since numeric constants with decimal points are initially assigned the typenumeric
, the following query will require no type conversion and therefore might be slightly more efficient:
Example 10.7. Substring Function Type Resolution
There are severalsubstr
functions, one of which takes typestext
andinteger
. If called with a string constant of unspecified type, the system chooses the candidate function that accepts an argument of the preferred categorystring
(namely of typetext
).
If the string is declared to be of typevarchar
, as might be the case if it comes from a table, then the parser will try to convert it to becometext
:
This is transformed by the parser to effectively become:
The parser learns from thepg_cast
catalog thattext
andvarchar
are binary-compatible, meaning that one can be passed to a function that accepts the other without doing any physical conversion. Therefore, no type conversion call is really inserted in this case.
And, if the function is called with an argument of typeinteger
, the parser will try to convert that totext
:
This does not work becauseinteger
does not have an implicit cast totext
. An explicit cast will work, however:
[8]The reason for this step is to support function-style cast specifications in cases where there is not an actual cast function. If there is a cast function, it is conventionally named after its output type, and so there is no need to have a special case. SeeCREATE CASTfor additional commentary.