64
CREATECAST
function_name
(
argument_type
[,...])
Thefunctionusedtoperformthecast.Thefunctionnamecanbeschema-qualified.Ifitisnot,
thefunctionwillbelookedupintheschemasearchpath.Thefunction’sresultdatatypemust
matchthetargettypeofthecast.Itsargumentsarediscussedbelow.
WITHOUT FUNCTION
Indicatesthatthesourcetypeisbinary-coercibletothetargettype,sonofunctionisrequiredto
performthecast.
WITH INOUT
Indicatesthatthecastis anI/Oconversioncast,performedbyinvokingtheoutputfunctionof
thesourcedatatype,andpassingtheresultingstringtotheinputfunctionofthetargetdatatype.
AS ASSIGNMENT
Indicatesthatthecastcanbeinvokedimplicitlyinassignmentcontexts.
AS IMPLICIT
Indicatesthatthecastcanbeinvokedimplicitlyinanycontext.
Cast implementationfunctions can have one to three arguments.Thefirst argument type must be
identicaltoorbinary-coerciblefromthecast’ssourcetype.Thesecondargument,ifpresent,mustbe
type
integer
;itreceivesthetypemodifierassociatedwiththedestinationtype,or
-1
ifthereisnone.
Thethirdargument,ifpresent,mustbetype
boolean
;itreceives
true
ifthecastisanexplicitcast,
false
otherwise.(Bizarrely,theSQLstandarddemandsdifferentbehaviorsforexplicitandimplicit
castsinsomecases.Thisargumentissuppliedforfunctionsthatmustimplementsuchcasts.Itisnot
recommendedthatyoudesignyourowndatatypessothatthismatters.)
Thereturntypeofacastfunctionmustbeidenticaltoorbinary-coercibletothecast’stargettype.
Ordinarilyacastmusthavedifferentsourceandtargetdatatypes.However,itisallowedtodeclare
acastwithidenticalsourceandtargettypes ifithas acastimplementationfunctionwithmorethan
oneargument.Thisisusedtorepresenttype-specificlengthcoercionfunctionsinthesystemcatalogs.
Thenamedfunctionisusedtocoerceavalueofthetypetothetypemodifiervaluegivenbyitssecond
argument.
Whenacasthasdifferentsourceandtargettypesandafunctionthattakesmorethanoneargument,
itsupportsconvertingfromonetypetoanotherandapplyingalengthcoercioninasinglestep.When
nosuchentryisavailable,coerciontoatypethatusesatypemodifierinvolvestwocaststeps,oneto
convertbetweendatatypesandasecondtoapplythemodifier.
Acasttoorfromadomaintypecurrentlyhasnoeffect.Castingtoorfromadomainusesthecasts
associatedwithitsunderlyingtype.
Notes
UseDROPCASTtoremoveuser-definedcasts.
Rememberthatifyouwanttobeabletoconverttypesbothwaysyouneedtodeclarecastsbothways
explicitly.
Itisnormallynotnecessarytocreatecastsbetweenuser-definedtypesandthestandardstringtypes
(
text
,
varchar
,and
char(
n
)
,as wellas user-defined types that are definedto be in the string
category).PostgreSQLprovidesautomaticI/Oconversioncastsforthat.Theautomaticcaststostring
types aretreatedasassignmentcasts,while theautomaticcastsfromstringtypesareexplicit-only.
Youcanoverridethisbehaviorbydeclaringyourowncasttoreplaceanautomaticcast,butusually
1330
67
CREATECAST
theonlyreasontodosoisifyouwanttheconversiontobemoreeasilyinvokablethanthestandard
assignment-onlyorexplicit-onlysetting.Anotherpossiblereasonisthatyouwanttheconversionto
behavedifferentlyfromthetype’sI/Ofunction;butthatissufficientlysurprisingthatyoushouldthink
twiceaboutwhetherit’sagoodidea.(Asmallnumberofthebuilt-intypesdoindeedhavedifferent
behaviorsforconversions,mostlybecauseofrequirementsoftheSQLstandard.)
While notrequired,it is recommended thatyou continueto follow this oldconventionofnaming
cast implementationfunctionsafterthe targetdatatype.Manyusers areusedtobeingable tocast
datatypesusingafunction-stylenotation,thatis
typename
(
x
).Thisnotationisinfactnothingmore
norlessthanacallofthecastimplementationfunction;itisnotspeciallytreatedasacast.Ifyour
conversion functions are notnamedtosupport this conventionthenyou willhavesurprisedusers.
SincePostgreSQLallowsoverloadingofthesamefunctionnamewithdifferentargumenttypes,there
is nodifficultyinhavingmultiple conversionfunctionsfromdifferenttypes that all use the target
type’sname.
Note:Actuallytheprecedingparagraphisanoversimplification:therearetwocasesinwhicha
function-callconstructwillbe treatedas acastrequestwithouthavingmatchedittoanactual
function.Ifafunctioncall
name
(
x
)doesnotexactlymatchany existingfunction,but
name
isthe
name of adata typeand
pg_cast
provides a binary-coerciblecastto this type from thetype
of
x
,thenthecallwillbeconstruedasabinary-coerciblecast.This exceptionis madesothat
binary-coerciblecastscanbeinvokedusingfunctionalsyntax,eventhoughtheylackanyfunction.
Likewise,ifthereisno
pg_cast
entrybutthecastwouldbetoorfromastringtype,thecallwill
beconstruedasanI/Oconversioncast.ThisexceptionallowsI/Oconversioncaststobeinvoked
usingfunctionalsyntax.
Note:Thereisalso anexceptiontotheexception:I/Oconversion casts fromcomposite types
to stringtypes cannotbeinvoked usingfunctional syntax, butmust be written in explicitcast
syntax(either
CAST
or
::
notation).Thisexceptionwasaddedbecauseaftertheintroductionof
automatically-providedI/Oconversioncasts,itwasfoundtooeasytoaccidentallyinvokesucha
castwhenafunctionorcolumnreferencewasintended.
Examples
Tocreateanassignmentcastfromtype
bigint
totype
int4
usingthefunction
int4(bigint)
:
CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT;
(Thiscastisalreadypredefinedinthesystem.)
Compatibility
The
CREATE CAST
commandconformstotheSQLstandard,exceptthatSQLdoesnotmakeprovi-
sionsforbinary-coercibletypesorextraargumentstoimplementationfunctions.
AS IMPLICIT
isa
PostgreSQLextension,too.
1331
4
CREATECAST
See Also
CREATEFUNCTION,CREATETYPE,DROPCAST
1332
55
CREATE COLLATION
Name
CREATE COLLATION—defineanewcollation
Synopsis
CREATE COLLATION
name
(
[ LOCALE =
locale
, ]
[ LC_COLLATE =
lc_collate
, ]
[ LC_CTYPE =
lc_ctype
]
)
CREATE COLLATION
name
FROM
existing_collation
Description
CREATE COLLATION
definesanewcollationusingthespecifiedoperatingsystemlocalesettings,or
bycopyinganexistingcollation.
Tobeabletocreateacollation,youmusthave
CREATE
privilegeonthedestinationschema.
Parameters
name
Thenameofthecollation.Thecollationnamecanbeschema-qualified.Ifitisnot,thecollation
isdefinedinthecurrentschema.Thecollationnamemustbeuniquewithinthatschema.(The
systemcatalogscancontaincollationswiththesamenameforotherencodings,butthese are
ignoredifthedatabaseencodingdoesnotmatch.)
locale
Thisisashortcutforsetting
LC_COLLATE
and
LC_CTYPE
atonce.Ifyouspecifythis,youcannot
specifyeitherofthoseparameters.
lc_collate
Usethespecifiedoperatingsystemlocaleforthe
LC_COLLATE
localecategory.Thelocalemust
beapplicabletothecurrentdatabaseencoding.(SeeCREATEDATABASEforthepreciserules.)
lc_ctype
Usethespecifiedoperatingsystemlocaleforthe
LC_CTYPE
localecategory.Thelocalemustbe
applicabletothecurrentdatabaseencoding.(SeeCREATEDATABASEforthepreciserules.)
existing_collation
Thenameofanexistingcollationtocopy.Thenewcollationwillhavethesamepropertiesasthe
existingone,butitwillbeanindependentobject.
1333
26
CREATECOLLATION
Notes
Use
DROP COLLATION
toremoveuser-definedcollations.
SeeSection22.2formoreinformationaboutcollationsupportinPostgreSQL.
Examples
Tocreateacollationfromtheoperatingsystemlocale
fr_FR.utf8
(assumingthecurrentdatabase
encodingis
UTF8
):
CREATE COLLATION french (LOCALE = ’fr_FR.utf8’);
Tocreateacollationfromanexistingcollation:
CREATE COLLATION german FROM "de_DE";
Thiscanbeconvenienttobeabletouseoperating-system-independentcollationnames inapplica-
tions.
Compatibility
Thereisa
CREATE COLLATION
statementintheSQLstandard,butitislimitedtocopyinganexisting
collation.ThesyntaxtocreateanewcollationisaPostgreSQLextension.
See Also
ALTERCOLLATION,DROPCOLLATION
1334
54
CREATE CONVERSION
Name
CREATE CONVERSION—defineanewencodingconversion
Synopsis
CREATE [ DEFAULT ] CONVERSION
name
FOR
source_encoding
TO
dest_encoding
FROM
function_name
Description
CREATE CONVERSION
definesanewconversionbetweencharactersetencodings.Also,conversions
thataremarked
DEFAULT
canbeusedforautomaticencodingconversionbetweenclientandserver.
Forthispurpose,twoconversions,fromencodingAtoBandfromencodingBtoA,mustbedefined.
To be able tocreatea conversion,youmust have
EXECUTE
privilegeonthefunctionand
CREATE
privilegeonthedestinationschema.
Parameters
DEFAULT
The
DEFAULT
clause indicates that this conversionis the default forthis particularsource to
destinationencoding.Thereshouldbeonlyonedefaultencodinginaschemafortheencoding
pair.
name
Thenameoftheconversion.Theconversionnamecanbeschema-qualified.Ifitisnot,thecon-
versionisdefinedinthecurrentschema.Theconversionnamemustbeuniquewithinaschema.
source_encoding
Thesourceencodingname.
dest_encoding
Thedestinationencodingname.
function_name
Thefunctionusedtoperformtheconversion.Thefunctionnamecanbeschema-qualified.Ifit
isnot,thefunctionwillbelookedupinthepath.
Thefunctionmusthavethefollowingsignature:
conv_proc(
integer,
-- source encoding ID
integer,
-- destination encoding ID
cstring,
-- source string (null terminated C string)
internal, -- destination (fill with a null terminated C string)
integer
-- source string length
) RETURNS void;
1335
26
CREATECONVERSION
Notes
Use
DROP CONVERSION
toremoveuser-definedconversions.
Theprivilegesrequiredtocreateaconversionmightbechangedinafuturerelease.
Examples
Tocreateaconversionfromencoding
UTF8
to
LATIN1
using
myfunc
:
CREATE CONVERSION myconv FOR ’UTF8’ TO ’LATIN1’ FROM myfunc;
Compatibility
CREATE CONVERSION
is aPostgreSQL extension.Thereis no
CREATE CONVERSION
statementin
theSQLstandard,buta
CREATE TRANSLATION
statementthatisverysimilarinpurposeandsyntax.
See Also
ALTERCONVERSION,CREATEFUNCTION,DROPCONVERSION
1336
73
CREATE DATABASE
Name
CREATE DATABASE—createanewdatabase
Synopsis
CREATE DATABASE
name
[ [ WITH ] [ OWNER [=]
user_name
]
[ TEMPLATE [=]
template
]
[ ENCODING [=]
encoding
]
[ LC_COLLATE [=]
lc_collate
]
[ LC_CTYPE [=]
lc_ctype
]
[ TABLESPACE [=]
tablespace_name
]
[ CONNECTION LIMIT [=]
connlimit
] ]
Description
CREATE DATABASE
createsanewPostgreSQLdatabase.
Tocreateadatabase,youmustbeasuperuserorhavethespecial
CREATEDB
privilege.SeeCREATE
USER.
Bydefault,thenewdatabasewillbecreatedbycloningthestandardsystemdatabase
template1
.A
differenttemplatecanbespecifiedbywriting
TEMPLATE
name
.Inparticular,bywriting
TEMPLATE
template0
,youcancreateavirgindatabasecontainingonlythestandardobjectspredefinedbyyour
versionofPostgreSQL.Thisisusefulifyouwishtoavoidcopyinganyinstallation-localobjectsthat
mighthavebeenaddedto
template1
.
Parameters
name
Thenameofadatabasetocreate.
user_name
Therolenameoftheuserwhowillownthenewdatabase,or
DEFAULT
tousethedefault(namely,
the userexecutingthecommand).Tocreateadatabaseownedbyanotherrole,youmustbea
directorindirectmemberofthatrole,orbeasuperuser.
template
Thenameofthetemplatefromwhichtocreatethenewdatabase,or
DEFAULT
tousethedefault
template(
template1
).
encoding
Character set encoding to use in the new database. Specify a string constant (e.g.,
’SQL_ASCII’
), or an integer encoding number, or
DEFAULT
to use the default encoding
(namely, the encoding of the template database). The character sets supported by the
PostgreSQLserveraredescribedinSection22.3.1.Seebelowforadditionalrestrictions.
1337
Documents you may be interested
Documents you may be interested