In PostgreSQL, which types can be cast with the type name first? - postgresql

Reading the PostgreSQL docs, I see that you can cast a longish bit of text to xml like this:
SELECT xml '<long>long text, may span many lines</long>'
SELECT xml '...'
Curious, I found that I could do the same with JSON:
SELECT json '{"arg1":"val1", <more args spanning many lines>}'
(I couldn't find an official reference for this one. It just works!)
By contrast, this does not work:
SELECT float8 3.14159
I like this alternate syntax from a readability perspective. Now I'm looking for a reference listing which types may be specified up front like this. but I haven't found it yet.
Any pointers?

The documentation says:
A constant of an arbitrary type can be entered using any one of the following notations:
type 'string'
'string'::type
CAST ( 'string' AS type )
The string constant's text is passed to the input conversion routine for the type called type. The result is a constant of the indicated type. The explicit type cast can be omitted if there is no ambiguity as to the type the constant must be (for example, when it is assigned directly to a table column), in which case it is automatically coerced.
The form you are asking about is the first one.
So this can be used for all PostgreSQL types.
Note that the data must be specified as a string literal (in single or dollar quotes) when you use that syntax.

Related

Is empty string value generally allowed by the FIX protocol?

When I look at the definition of a String type in the FIX protocol (e.g. here or here), I don't see a minimum length specified. Is it allowed to use empty strings? One online decoder seems to accept an empty string value (see tag 320), an other complains that it's invalid.
The FIX 4.4 specification states the following (emphasis in the original text):
Each message is constructed of a stream of <tag>=<value> fields with a
field delimiter between fields in the stream. Tags are of data type
TagNum. All tags must have a value specified. Optional fields without
values should simply not be specified in the FIX message. A Reject
message is the appropriate response to a tag with no value.
That strongly suggests (but does not unambiguously state) to me that the use of an empty value for a string is invalid. It is unsurprising to me that different FIX implementations might treat this edge case in different ways. So, I think the best approach is to avoid using empty values for strings.
+1 for Ciaran's and Grant's answer/comments. Just want to add something.
I generally suggest to look up things like this in the most current specification since they usually have been refined/reworded/clarified to eliminate unclear or ambiguous statements from older specs.
The answer is on the very page you link to in your question (emphasis mine, search for "Well-formed field"): https://www.fixtrading.org/standards/tagvalue-online/#field-syntax
A well-formed field has the form:
tag=value<SOH>
A field shall be considered malformed if any of the following occurs as a result of encoding:
the tag is empty
the tag delimiter is missing
the value is empty
the value contains an <SOH> character and the datatype of the field is not data or XMLdata
the datatype of the field is data and the field is not immediately preceded by its associated Length field.

Built-in list of numeric types in Matlab

Does Matlab provide a list of numeric datatypes?
Some functions, like zeros, take an optional typename argument, a string naming a numeric type (e.g., 'double' or 'uint8'), that determines the type of the returned array. I would like to add something similar to my own code, and a complete list of numeric types would help with argument validation, as in:
ip = inputParer()
...
ip.addParameter('DataType', 'double', #(x) ismember(x, numeric_types()));
It seems as though something similar must exist, but I haven't been able to find it.
isnumeric checks an instance, rather than the typename itself.
superclasses doesn't return anything for numeric types on 2018b.
Obviously, this is not hard to implement, but it'd be nice to use a built-in if it existed.

Which part of PostgreSQL code is handling type definition?

In PostgreSQL when I call NUMERIC(10,2) to define a variable type. Which part of the PostgreSQL C code is handling it?
I am interested in knowing where the precision and scale are handled.
Lots of parts.
The lexer and parser transforms it into a type name and type modifier.
The system catalogs and syscache look up numeric to find the matching type oid.
The numeric.c code handles the actual type input/output and operators, and interprets the type modifier.
The index access methods and index operator classes handle selection of operators for comparisons etc.

PostgreSQL syntax error in parameterized query on "date $1"

Trying to parameterize my SQL queries (using libpq function PQexecParams), I was stuck on a syntax error:
SELECT date $1
The error is:
ERROR: syntax error at or near "$1"
Prepared statements
The explanation for this can be found in the chapter Constants of Other Types of the manual:
The ::, CAST(), and function-call syntaxes can also be used to specify
run-time type conversions of arbitrary expressions, as discussed in
Section 4.2.9. To avoid syntactic ambiguity, the type 'string' syntax
can only be used to specify the type of a simple literal constant.
Another restriction on the type 'string' syntax is that it does not
work for array types; use :: or CAST() to specify the type of an array
constant.
Bold emphasis mine.
Parameters for prepared statements are not actually sting literals but typed values, so you cannot use the form type 'string'. Use one of the other two forms to cast the value to a different type, like you found yourself already.
Example:
PREPARE foo AS SELECT $1::date;
EXECUTE foo('2005-1-1');
Similar for PQexecParams in the libpq C library
The documentation:
... In the SQL command text, attach an explicit cast to the parameter
symbol to show what data type you will send. For example:
SELECT * FROM mytable WHERE x = $1::bigint;
This forces parameter $1 to be treated as bigint, whereas by default
it would be assigned the same type as x. Forcing the parameter type
decision, either this way or by specifying a numeric type OID, is
strongly recommended. ...
The alternative, as mentioned in the quote above, is to pass the OIDs of respective data types with paramTypes[] - if you actually need the cast. In most cases it should work just fine to let Postgres derive data types from the query context.
paramTypes[]
Specifies, by OID, the data types to be assigned to the parameter
symbols. If paramTypes is NULL, or any particular element in the array
is zero, the server infers a data type for the parameter symbol in the
same way it would do for an untyped literal string.
You can get the OID of data types from the system catalog pg_type:
SELECT oid FROM pg_type WHERE typname = 'date';
You must use the correct internal type name. For instance: int4 for integer.
Or with a convenience cast to regtype:
SELECT 'date'::regtype::oid;
This is more flexible as known aliases for the type name are accepted as well. For instance: int4, int or integer for integer.
The solution is to use a type cast instead of date:
SELECT $1::date

functions and operator for user define type

I have built User Define Type with function_in and function_out.
CREATE OR REPLACE FUNCTION MyOwnType_in(cstring)
RETURNS MyOwnType
AS '/home/postgres/ENCRIPTION/MyOwnType/MyOwnType.so','MyOwnType_in'
LANGUAGE C IMMUTABLE STRICT;
CREATE OR REPLACE FUNCTION MyOwnType_out(MyOwnType)
RETURNS cstring
AS '/home/postgres/ENCRIPTION/MyOwnType/MyOwnType.so','MyOwnType_out'
LANGUAGE C IMMUTABLE STRICT;
As you can see each function_in receives cstring and function_out returns cstring.
The thing is function overloading and operator overriding on which I don't want to waste my time.
Is there any way to declare DEFAULT TYPE for my MyOwnType type which tells postgres that functions and operators with MyOwnTypearguments can parse and rewrite it into text?
The most you can do with your type is to mark it as a string type, with:
CREATE TYPE MyOwnType(
INPUT = MyOwnType_in,
OUTPUT = MyOwnType_out,
CATEGORY = 'S'
-- ...
);
The category parameter is especially useful when adding a user-defined type to an existing built-in category, such as the numeric or string types. However, it is also possible to create new entirely-user-defined type categories. Select any ASCII character other than an upper-case letter to name such a category ...
It may require additional CASTs, as #IgorRomanchenko suggested.
You need to CREATE CAST ... AS IMPLICIT from your datatype to text. This way your type will be automatically cast to text when a function/operator requires text.
Details here: http://www.postgresql.org/docs/current/static/sql-createcast.html