Discussion:
Custom type literal conversion
Chris Bandy
2014-09-24 12:45:27 UTC
Permalink
I would like to create a new type for version strings that sorts
numerically. The composite type below was quick to write and does not
require superuser privileges. However, it doesn't respond to type casts the
way I'd like.

Is there a way to implement this type's literal conversion without
resorting to a base type?

Thanks
-- Chris

===

=> CREATE TYPE myversion AS (version integer[], build varchar);
CREATE TYPE
=> CREATE OR REPLACE FUNCTION myversion(text)
-> RETURNS myversion AS $$
$> SELECT
$> string_to_array(split_part($1, '+', 1), '.')::integer[],
$> split_part($1, '+', 2);
$> $$ LANGUAGE SQL IMMUTABLE STRICT;
CREATE FUNCTION
=> SELECT myversion('1.0.9+jenkins');
myversion
---------------------
("{1,0,9}",jenkins)
(1 row)

=> SELECT '1.0.9+jenkins'::myversion;
ERROR: malformed record literal: "1.0.9+jenkins"
LINE 1: SELECT '1.0.9+jenkins'::myversion;
^
DETAIL: Missing left parenthesis.
hubert depesz lubaczewski
2014-09-24 13:40:35 UTC
Permalink
Post by Chris Bandy
I would like to create a new type for version strings that sorts
numerically. The composite type below was quick to write and does not
require superuser privileges. However, it doesn't respond to type casts the
way I'd like.
Is there a way to implement this type's literal conversion without
resorting to a base type?
I think you need to define casts too, but in any way - check if "semver"
extension (available on pgxn) doesn't solve your problem.

depesz
Chris Bandy
2014-09-24 19:02:00 UTC
Permalink
Post by hubert depesz lubaczewski
Post by Chris Bandy
I would like to create a new type for version strings that sorts
numerically. The composite type below was quick to write and does not
require superuser privileges. However, it doesn't respond to type casts the
way I'd like.
Is there a way to implement this type's literal conversion without
resorting to a base type?
I think you need to define casts too, but in any way - check if "semver"
extension (available on pgxn) doesn't solve your problem.
Casts from what? The following is not sufficient:

=> CREATE CAST (unknown AS myversion) WITH FUNCTION myversion(unknown);
CREATE CAST
=> SELECT '1.0.9+jenkins'::myversion;
ERROR: malformed record literal: "1.0.9+jenkins"

And cast on "record" isn't valid:

=> CREATE CAST (record AS myversion) WITH FUNCTION myversion(unknown);
ERROR: source data type record is a pseudo-type

I know about the semver extension, but I'm interested in a solution that
does not require extension/superuser access.

Thanks
-- Chris

Continue reading on narkive:
Loading...