Tải bản đầy đủ

OReilly practical PostgreSQL jan 2002 ISBN 1565928466

PracticalPostgreSQL
Prev

Next


CREATEINDEX


Name
CREATEINDEX--Placesanindexonatable.


Synopsis
CREATE[UNIQUE]INDEXindex_nameONtable
[USINGmethod](column[op_class][,...])
CREATE[UNIQUE]INDEXindex_nameONtable
[USINGmethod](func_name(column[,...])[op_class])

Parameters
UNIQUE


TheoptionalUNIQUEkeyword.Whenused,thiscausesthedatabaseto
checkfor,andprevent,duplicatevalueswithinthecolumn(orcombined
columns)itisplacedupon.Thischeckwilloccurbothwhentheindexis
createdandeachtimedataisaddedtothetable.PostgreSQLwillthen
generateanerrorwheneveranINSERTorUPDATErequestismadethatwould
placeduplicatedatawithintheindex,andthecommandwillfail.
index_name

Thenameforthenewindex.
table

Thenameofthetableyouareplacingtheindexon.
method

Thetypeofindexingmethodyouwishtousefortheindex.Therearethree
methodsavailabletochoosefrom,thedefaultbeingbtree:
btree

ThePostgreSQLimplementationofLehman-Yaohigh-concurrencyBtrees.
rtree

ThePostgreSQLimplementationofstandardR-treesusingGuttman's
quadraticsplitalgorithm.


hash

ThePostgreSQLimplementationofLitwin'slinearhashing.
column

Thenameofthecolumn(orcomma-delimitedlistofcolumns)onwhichto
placetheindex.
op_class

Theoptionallyspecifiedassociatedoperatorclass.Formostusers,this
shouldnotbespecified.
func_name

ThenameofafunctionyouwishCREATEINDEXtouseonthespecified
columns(ratherthanonthedatavaluesliterallyinthosecolumns).The
specifiedfunctionmustreturnavalidvaluethatcanbeindexed(e.g.,nota
setofvalues).

Results
CREATE

Themessagereturnedwhenanindexiscreatedsuccessfully.
ERROR:Cannotcreateindex:'index_name'alreadyexists

Theerrorreturnedifanindexwiththenameyouspecifiedalreadyexists.
ERROR:DefineIndex:attribute"column"notfound

Theerrorreturnedifthespecifiedcolumndoesnotexistinthespecified
tabletoindex.
ERROR:DefineIndex:relation"table"notfound

Theerrorreturnedifthespecifiedtabledoesnotexistintheconnected
database.


Description
UseCREATEINDEXtobuildanoptimizationindexonaspecifiedtable,basedon
oneormoreofitscolumns.Rememberthatwhileindicesaredesignedto
improvetheperformanceandeffectivenessofyourdatabase,usingthemon
tableswhosecostofindexmaintenanceoutweighsthepracticalbenefitactually
decreasesoverallperformance.

Columnindex
Youmaycreateanindexspecifyingalistofoneormoretablecolumns.Thisis
the"traditional"indextype.Itmaybeusedbyqueriesthatdirectlyreferencethe
indexedcolumnsinaWHEREclause.NotethatR-treeandHashindicesmayonly
indexonecolumn,thoughB-treeindicescanindexuptosixteencolumns.

Functionalindex
Analternatetypeofindexisonecalledafunctionalindex.Afunctionalindexis
anindexbasedonthereturnedvalueofafunctionappliedtooneormore
columns.Suchanindexisusefulforqueriesthatusethesamefunctionina
WHEREclausefrequently.
Forexample,ifyouhaveaquerythatalwaysreferencesupper(last_name)in
itsWHEREclause,youcouldoptimizedthatquerybycreatingafunctionalindex
onupper(last_name).

Operatorsandoperatorclasses
ThePostgreSQLqueryoptimizerwillusedifferentindicesfordifferentoperators
usedinacomparison.Itwillchoosewhichtypeofindextousedbasedonthe
pre-definedlistshowninTable14-1.
Table14-1.Operator/indexcorrespondence
Index Operator
B-

<,<=,


tree

>=,>

Rtree

<<,&<,
&>,>>,
@,~=,
&&

Hash

=

Youcanoptionallyspecifyanoperatorclassforeachcolumnonwhichanindex
isplaced.Thisisdonebysettingtheoptionalop_classparametertotheclassof
operatoryouintendtouse.Thisoptiononlyexistsbecause,insome
circumstances,therecanbemorethanonemeaningfulwaytoorderdata.The
defaultindexingmethodisgenerallysufficientformostusers,however,andthis
optionisbestleftunusedunlessyouarecreatingyourowncustomtypesand
operators.


Examples
Thefollowingexamplecreatesauniqueindexontheidcolumnofthe
employeestable:
booktown=#CREATEUNIQUEINDEXemployee_id_idx
booktown-#ONemployees(id);
CREATE

Thenextexamplecreatesafunctionalindexonthelast_namecolumnofthe
employeestable,usingtheupper()function:
booktown=#CREATEINDEXemployee_upper_name_idx
booktown-#ONemployees(upper(last_name));
CREATE

Prev
CREATEGROUP

Home
Up

Next
CREATELANGUAGE


PracticalPostgreSQL
Prev

Next


CREATEGROUP


Name
CREATEGROUP--CreatesanewPostgreSQLgroupwithinthedatabase.


Synopsis
CREATEGROUPname
[WITH[SYSIDgid]
[USERusername[,...]]]

Parameters
name

Thenameofthenewgrouptocreate.
gid

ThegroupIDtouseforthenewgroup.Ifyoudonotexplicitlyspecifythe
groupID,itwillautomaticallybecalculatedasonehigherthanthehighest
groupIDcurrentlyinuse.
username

Theuser(orcomma-delimitedlistofusers)thatyouwishtoautomatically
includeinthegroupyouarecreating.Theuserslistedinthisparameter
mustalreadyexistwithinthedatabase.

Results
CREATEGROUP

ThemessagereturnedwhenaPostgreSQLgroupiscreatedsuccessfully.
ERROR:CREATEGROUP:groupname"name"alreadyexists

TheerrorreturnedifaPostgreSQLgroupnamednamecurrentlyexistsin
thesystem.
ERROR:CREATEGROUP:permissiondenied

Theerrorreturnedifanon-superuserattemptstocreateagroup.
ERROR:CREATEGROUP:user"username"doesnotexist


TheerrorreturnediftheusernameintheWITHUSERclausedoesnot
currentlyexist.


Description
AdatabasesuperusercanuseCREATEGROUPtocreateanewgroupin
PostgreSQL.Agroupisasystem-widedatabaseobjectthatcanbeassigned
privileges(withtheGRANTcommand),andhaveusersaddedtoitasmembers.
Membersofagroupareassigneditsprivilegesbyproxy.
Tomodifyagroup(andthelistofusersthatitiscomposedofit),usetheALTER
GROUPcommand.Ifyouwishtoremoveagroupentirely,usetheDROPGROUP
command.


Examples
Thefollowingexamplecreatesanemptygroupnamedmanagement:
booktown=#CREATEGROUPmanagement;
CREATEGROUP

Thenextexamplecreatesagroupcalledaccounting,andautomaticallyadds
userstoittwousersbyspecifyingtheirusernamesfollowingtheWITHUSER
clause:
booktown=#CREATEGROUPaccountingWITHUSERvincent,allen;
CREATEGROUP

Prev
CREATEFUNCTION

Home
Up

Next
CREATEINDEX


PracticalPostgreSQL
Prev

Next


CREATELANGUAGE


Name
CREATELANGUAGE--Definesanewlanguagetobeusedbyfunctions.


Synopsis
CREATE[TRUSTED][PROCEDURAL]LANGUAGE'langname'
HANDLERcall_handler
LANCOMPILER'comment'

Parameters
TRUSTED

TheTRUSTEDkeywordindicatesthatthePostgreSQLletsunprivilegedusers
bypassuserandpermission-relatedaccessrestrictionsonthelanguage.If
thisparameterisnotspecifiedduringcreationofthelanguage,only
databasesuperuserswillbeabletousethelanguagetocreatenew
functions.
PROCEDURAL

TheoptionalPROCEDURALnoiseterm.Thismaybeusedtoincrease
readabilityofyourCREATELANGUAGEstatements,buthasnoeffect.
langname

Thenameofthenewprocedurallanguagetodefine.Thisnameiscase
insensitive.Aprocedurallanguagewillnot(andcannot)overridean
existing,built-inPostgreSQLlanguage.
HANDLERcall_handler

Thenameofthealready-definedfunctionthatwillbecalledtoexecutethe
PLprocedures.
comment

Astringthatisinsertedintothelancompilercolumnofthepg_language
systemtable.TheLANCOMPILERclauseisalegacyclausewithnopractical
effect,andmayberemovedinafuturePostgreSQLrelease.However,asof
version7.1.x,thisisstillarequiredclause.

Results


CREATE

Themessagereturnedwhenanewlanguageissuccessfullycreated.
ERROR:PLhandlerfunctioncall_handler()doesn'texist

Theerrorreturnedifthefunctionyouspecifiedasthecallhandlerwith
call_handlerparametercannotbefound.


Description
UsetheCREATELANGUAGEcommandtoloadanewprocedurallanguageintothe
connecteddatabase.Thiscommandcanbeusedwithlanguagesthatyou
specifiedusing--with-langnamewhenyoufirstinstalledPostgreSQL,orone
youhavecreatedyourself.Forinstance,tocorrectlyaddthepltcllanguageinto
PostgreSQL,youshouldhaveusedthetag--with-tclwhenyouconfigured
PostgreSQLtomakeitscallhandleravailable.
Afterthiscommandhasbeenissued,youshouldbeabletodefinefunctions
usingthenewlyaddedlanguage.NotethattheuserwhoexecutestheCREATE
LANGUAGEcommandmustbeasuperuser.
AsofPostgreSQL7.1.x(themostcurrentversionattheprintingofthisbook),
onceaprocedurallanguagesisdefined,thedefinitioncannotbemodified.To
changethedefinitionofyourprocedurallanguage,youwillneedtodropitfrom
thedatabasewiththeDROPLANGUAGEcommandandrecreateit.
Note:IfyouuseCREATELANGUAGEtocreatealanguageinthetemplate1
database,allsubsequentdatabasesthatarecreatedfromthetemplate1(the
defaulttemplate)willsupportthatlanguage.
InorderforaprocedurallanguagetobeusedbyPostgreSQL,acallhandlermust
bewrittenforit.Thatcallhandlermustbecompiledintoabinaryform;itis
thereforerequiredthatthelanguageusedtowriteahandlerbeonethatcompiles
intoabinaryformat,suchasCorC++.
ThecallhandlermustbecreatedwithinPostgreSQLasafunctionthatdoesnot
acceptargumentsandhasareturntypeofopaque.Bydefiningthehandler
functioninthismanner,youenablePostgreSQLtopreventthefunction(and
thus,thelanguage)fromeverbeingusedinanarbitrarySQLstatement.


Examples
Ahandlermustalreadyexistforthelanguageinquestionwhenyouusethe
CREATELANGUAGEcommand.Thefirststepinregisteringaprocedurallanguage
tocreateafunctionthatspecifiesthelocationofobjectcodeforthecallhandler.
Thefollowingexamplecreatesanexamplecallhandler,whoseobjectcodeis
locatedat/usr/local/pgsql/lib/libexample.so:
booktown=#CREATEFUNCTIONexample_call_handler()RETURNSopaque
booktown-#AS'/usr/local/pgsql/lib/libexample.so'
booktown-#LANGUAGE'C';
CREATE

Note:Youdonotneedtodefinethecallhandlerfunctionifithasalready
beencreatedbytheprogrammer.Forillustrativepurposes,weareassuming
thattheprogrammerhasnotdefinedafunctionthatreferstothecall
handler.
ThesecondstepistouseCREATELANGUAGEtoloadtheexistinglanguageintothe
connecteddatabase.Thefollowingexamplecreatesalanguagecalled
plexample,whichusesthecallhandlercreatedintheprecedingexample:
booktown=#CREATEPROCEDURALLANGUAGE'plexample'
booktown-#HANDLERexample_call_handler
booktown-#LANCOMPILER'MyExample';
CREATE

Prev
CREATEINDEX

Home
Up

Next
CREATEOPERATOR


PracticalPostgreSQL
Prev

Next


CREATEINDEX


Name
CREATEINDEX--Placesanindexonatable.


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×

×