pdf viewer for asp.net web application : How to add image to pdf form SDK software API .net winforms wpf sharepoint postgresql-9.4-A4200-part2836

Chapter 54. Genetic Query Optimizer
Author:WrittenbyMartinUtesch(<
utesch@aut.tu-freiberg.de
>)fortheInstituteofAutomatic
ControlattheUniversityofMiningandTechnologyinFreiberg,Germany.
54.1. Query Handling as a Complex Optimization
Problem
Amongallrelationaloperatorsthemostdifficultonetoprocessandoptimizeisthejoin.Thenumber
ofpossiblequeryplansgrowsexponentiallywiththenumberofjoinsinthequery.Furtheroptimiza-
tioneffortiscausedbythesupportofavarietyofjoinmethods(e.g.,nestedloop,hashjoin,merge
joininPostgreSQL)toprocessindividualjoinsandadiversityofindexes(e.g.,B-tree,hash,GiST
andGINinPostgreSQL)asaccesspathsforrelations.
ThenormalPostgreSQLqueryoptimizerperformsanear-exhaustivesearchoverthespaceofalterna-
tivestrategies.Thisalgorithm,firstintroducedinIBM’sSystemRdatabase,producesanear-optimal
joinorder,butcantakeanenormousamountoftimeandmemoryspacewhenthenumberofjoinsin
thequerygrowslarge.ThismakestheordinaryPostgreSQLqueryoptimizerinappropriateforqueries
thatjoinalargenumberoftables.
TheInstituteofAutomaticControlattheUniversityofMiningandTechnology,inFreiberg,Germany,
encounteredsomeproblemswhenitwantedtousePostgreSQLasthebackendforadecisionsupport
knowledgebasedsystemforthemaintenanceofanelectricalpowergrid.TheDBMSneededtohandle
largejoinqueriesfortheinferencemachineoftheknowledgebasedsystem.Thenumberofjoinsin
thesequeriesmadeusingthenormalqueryoptimizerinfeasible.
Inthefollowingwedescribetheimplementationofageneticalgorithmtosolvethejoinordering
probleminamannerthatisefficientforqueriesinvolvinglargenumbersofjoins.
54.2. Genetic Algorithms
Thegeneticalgorithm(GA)isaheuristicoptimizationmethodwhichoperatesthroughrandomized
search.Thesetofpossiblesolutionsfortheoptimizationproblemisconsideredasapopulationof
individuals.Thedegreeofadaptationofanindividualtoitsenvironmentisspecifiedbyitsfitness.
Thecoordinatesofanindividualinthesearchspacearerepresentedbychromosomes,inessencea
setofcharacterstrings.Ageneisasubsectionofachromosomewhichencodesthevalueofasingle
parameterbeingoptimized.Typicalencodingsforagenecouldbebinaryorinteger.
Throughsimulationoftheevolutionaryoperationsrecombination,mutation,andselectionnewgen-
erationsofsearchpointsarefoundthatshowahigheraveragefitnessthantheirancestors.
1928
How to add image to pdf form - insert images into PDF in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Sample C# code to add image, picture, logo or digital photo into PDF document page using PDF page editor control
add jpg to pdf online; how to add a picture to a pdf file
How to add image to pdf form - VB.NET PDF insert image library: insert images into PDF in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide VB.NET Programmers How to Add Images in PDF Document
adding images to pdf forms; add image to pdf java
Chapter54.GeneticQueryOptimizer
Accordingtothecomp.ai.geneticFAQitcannotbestressedtoostronglythataGAis notapure
randomsearchforasolutiontoaproblem.AGAusesstochasticprocesses,buttheresultisdistinctly
non-random(betterthanrandom).
Figure54-1.StructuredDiagramofaGeneticAlgorithm
P(t)
generationofancestorsatatimet
P”(t)
generationofdescendantsatatimet
+=========================================+
|>>>>>>>>>>>
Algorithm GA
<<<<<<<<<<<<<<|
+=========================================+
| INITIALIZE t := 0
|
+=========================================+
| INITIALIZE P(t)
|
+=========================================+
| evaluate FITNESS of P(t)
|
+=========================================+
| while not STOPPING CRITERION do
|
|
+-------------------------------------+
|
| P’(t)
:= RECOMBINATION{P(t)}
|
|
+-------------------------------------+
|
| P”(t) := MUTATION{P’(t)}
|
|
+-------------------------------------+
|
| P(t+1) := SELECTION{P”(t) + P(t)}
|
|
+-------------------------------------+
|
| evaluate FITNESS of P”(t)
|
|
+-------------------------------------+
|
| t := t + 1
|
+===+=====================================+
54.3. Genetic Query Optimization (GEQO) in
PostgreSQL
TheGEQOmoduleapproachesthequeryoptimizationproblemasthoughitwerethewell-known
travelingsalesmanproblem(TSP).Possiblequeryplansareencodedasintegerstrings.Eachstring
representsthejoinorderfromonerelationofthequerytothenext.Forexample,thejointree
/\
/\ 2
/\ 3
4
1
isencodedbytheintegerstring’4-1-3-2’,whichmeans,firstjoinrelation’4’and’1’,then’3’,and
then’2’,where1,2,3,4arerelationIDswithinthePostgreSQLoptimizer.
SpecificcharacteristicsoftheGEQOimplementationinPostgreSQLare:
UsageofasteadystateGA(replacementoftheleastfitindividualsinapopulation,notwhole-
generationalreplacement)allowsfastconvergencetowardsimprovedqueryplans.Thisisessential
forqueryhandlingwithreasonabletime;
1929
VB.NET PDF Form Data Read library: extract form data from PDF in
featured PDF software, it should have functions for processing text, image as well can help you have a quick evaluation of our PDF SDK. Add necessary references
adding an image to a pdf in preview; adding a jpeg to a pdf
C# PDF Form Data Read Library: extract form data from PDF in C#.
featured PDF software, it should have functions for processing text, image as well can help you have a quick evaluation of our PDF SDK. Add necessary references
add photo pdf; add picture to pdf online
Chapter54.GeneticQueryOptimizer
Usageofedgerecombinationcrossoverwhichisespeciallysuitedtokeepedgelosseslowforthe
solutionoftheTSPbymeansofaGA;
Mutationasgeneticoperatorisdeprecatedsothatnorepairmechanismsareneededtogenerate
legalTSPtours.
PartsoftheGEQOmoduleareadaptedfromD.Whitley’sGenitoralgorithm.
TheGEQOmoduleallowsthePostgreSQLqueryoptimizertosupportlargejoinquerieseffectively
throughnon-exhaustivesearch.
54.3.1.GeneratingPossiblePlanswithGEQO
TheGEQOplanningprocessusesthestandardplannercodetogenerateplansforscansofindividual
relations.Thenjoinplansaredevelopedusingthegeneticapproach.Asshownabove,eachcandidate
joinplanisrepresentedbyasequenceinwhichtojointhebaserelations.Intheinitialstage,theGEQO
codesimplygeneratessomepossiblejoinsequencesatrandom.Foreachjoinsequenceconsidered,
thestandardplannercodeisinvokedtoestimatethecostofperformingthequeryusingthatjoin
sequence.(Foreachstepofthejoinsequence,allthreepossiblejoinstrategiesareconsidered;and
alltheinitially-determinedrelationscanplansareavailable.Theestimatedcostisthecheapestof
thesepossibilities.)Joinsequenceswithlowerestimatedcostareconsidered“morefit”thanthose
withhighercost.Thegeneticalgorithmdiscardstheleastfitcandidates.Thennewcandidatesare
generatedbycombininggenesofmore-fitcandidates—thatis,byusingrandomly-chosenportions
ofknownlow-costjoinsequencestocreatenewsequencesforconsideration.Thisprocessisrepeated
untilapresetnumberofjoinsequenceshavebeenconsidered;thenthebestonefoundatanytime
duringthesearchisusedtogeneratethefinishedplan.
Thisprocessisinherentlynondeterministic,becauseoftherandomizedchoicesmadeduringboth
theinitialpopulationselectionandsubsequent“mutation”ofthebestcandidates.Toavoidsurprising
changesoftheselectedplan,eachrunoftheGEQOalgorithmrestartsitsrandomnumbergenerator
withthecurrentgeqo_seedparametersetting.Aslongas
geqo_seed
andtheotherGEQOparameters
arekeptfixed,thesameplanwillbegeneratedforagivenquery(andotherplannerinputssuchas
statistics).Toexperimentwithdifferentsearchpaths,trychanging
geqo_seed
.
54.3.2.FutureImplementationTasksforPostgreSQLGEQO
Work is still needed to improve the genetic algorithm parameter settings. In file
src/backend/optimizer/geqo/geqo_main.c
,
routines
gimme_pool_size
and
gimme_number_generations
,wehavetofindacompromisefortheparametersettingstosatisfy
twocompetingdemands:
Optimalityofthequeryplan
Computingtime
Inthecurrentimplementation,thefitnessofeachcandidatejoinsequenceisestimatedbyrunningthe
standardplanner’sjoinselectionandcostestimationcodefromscratch.Totheextentthatdifferent
candidatesusesimilarsub-sequencesofjoins,agreatdealofworkwillberepeated.Thiscouldbe
madesignificantlyfasterbyretainingcostestimatesforsub-joins.Theproblemistoavoidexpending
unreasonableamountsofmemoryonretainingthatstate.
1930
C# PDF Image Extract Library: Select, copy, paste PDF images in C#
Scan image to PDF, tiff and various image formats. Get image information, such as its location, zonal information Able to edit, add, delete, move, and output PDF
add jpg to pdf document; add a picture to a pdf document
VB.NET PDF Password Library: add, remove, edit PDF file password
passwordSetting.IsAnnot = True ' Allow to fill form. passwordSetting document. passwordSetting.IsAssemble = True ' Add password to PDF file. PDFDocument
add jpg to pdf online; adding a png to a pdf
Chapter54.GeneticQueryOptimizer
Atamorebasiclevel,itisnotclearthatsolvingqueryoptimizationwithaGAalgorithmdesignedfor
TSPisappropriate.IntheTSPcase,thecostassociatedwithanysubstring(partialtour)isindependent
oftherestofthetour,butthisiscertainlynottrueforqueryoptimization.Thusitisquestionable
whetheredgerecombinationcrossoveristhemosteffectivemutationprocedure.
54.4. Further Reading
Thefollowingresourcescontainadditionalinformationaboutgeneticalgorithms:
TheHitch-Hiker’sGuidetoEvolutionaryComputation
1
,(FAQfornews://comp.ai.genetic)
EvolutionaryComputationanditsapplicationtoartanddesign
2
,byCraigReynolds
FundamentalsofDatabaseSystems
ThedesignandimplementationofthePOSTGRESqueryoptimizer
1. http://www.aip.de/~ast/EvolCompFAQ/
2. http://www.red3d.com/cwr/evolve.html
1931
VB.NET PDF Image Extract Library: Select, copy, paste PDF images
multiple types of image from PDF file in VB.NET, like XObject Image, XObject Form, Inline Image DLLs for PDF Image Extraction in VB.NET. Add necessary references
add picture pdf; add jpg signature to pdf
C# PDF Password Library: add, remove, edit PDF file password in C#
passwordSetting.IsAnnot = true; // Allow to fill form. passwordSetting document. passwordSetting.IsAssemble = true; // Add password to PDF file. PDFDocument
add an image to a pdf with acrobat; add a picture to a pdf file
Chapter 55. Index Access Method Interface
Definition
ThischapterdefinestheinterfacebetweenthecorePostgreSQLsystemandindexaccessmethods,
whichmanageindividualindextypes.Thecoresystemknowsnothingaboutindexesbeyondwhatis
specifiedhere,soitispossibletodevelopentirelynewindextypesbywritingadd-oncode.
AllindexesinPostgreSQLarewhatareknowntechnicallyassecondaryindexes;thatis,theindex
isphysicallyseparatefromthetablefilethatitdescribes.Eachindexisstoredasitsownphysical
relationandsoisdescribedbyanentryinthe
pg_class
catalog.Thecontentsofanindexareentirely
underthecontrolofitsindexaccessmethod.Inpractice,allindexaccessmethodsdivideindexesinto
standard-sizepagessothattheycanusetheregularstoragemanagerandbuffermanagertoaccess
theindexcontents.(Alltheexistingindexaccessmethodsfurthermoreusethestandardpagelayout
describedinSection59.6,andtheyallusethesameformatforindextupleheaders;butthesedecisions
arenotforcedonanaccessmethod.)
Anindexiseffectivelyamappingfromsomedatakeyvaluestotupleidentifiers,orTIDs,ofrow
versions(tuples)intheindex’sparenttable.ATIDconsistsofablocknumberandanitemnumber
withinthatblock(seeSection59.6).Thisissufficientinformationtofetchaparticularrowversion
fromthetable.Indexes arenotdirectlyawarethatunderMVCC,theremightbemultipleextant
versionsofthesamelogicalrow;toanindex,eachtupleisanindependentobjectthatneedsitsown
indexentry.Thus,anupdateofarowalwayscreatesall-newindexentriesfortherow,evenifthe
keyvaluesdidnotchange.(HOTtuplesareanexceptiontothisstatement;butindexesdonotdeal
withthose,either.)Indexentriesfordeadtuplesarereclaimed(byvacuuming)whenthedeadtuples
themselvesarereclaimed.
55.1. Catalog Entries for Indexes
Eachindexaccessmethodisdescribedbyarowinthe
pg_am
systemcatalog(seeSection48.3).The
principalcontentsofa
pg_am
rowarereferencesto
pg_proc
entriesthatidentifytheindexaccess
functionssuppliedbytheaccessmethod.TheAPIsforthesefunctionsaredefinedlaterinthischapter.
Inaddition,the
pg_am
rowspecifiesafewfixedpropertiesoftheaccessmethod,suchaswhetherit
cansupportmulticolumnindexes.Thereisnotcurrentlyanyspecialsupportforcreatingordeleting
pg_am
entries;anyoneabletowriteanewaccessmethodisexpectedtobecompetenttoinsertan
appropriaterowforthemselves.
Tobeuseful,anindexaccessmethodmustalsohaveoneormoreoperatorfamiliesandoperator
classesdefinedin
pg_opfamily
,
pg_opclass
,
pg_amop
, and
pg_amproc
. Theseentries allow
theplannertodeterminewhatkindsofqueryqualificationscanbeusedwithindexesofthisaccess
method.OperatorfamiliesandclassesaredescribedinSection35.14,whichisprerequisitematerial
forreadingthischapter.
Anindividualindexisdefinedbya
pg_class
entrythatdescribesitasaphysicalrelation,plusa
pg_index
entrythatshowsthelogicalcontentoftheindex—thatis,thesetofindexcolumnsit
hasandthesemanticsofthosecolumns,ascapturedbytheassociatedoperatorclasses.Theindex
columns(keyvalues)canbeeithersimplecolumnsoftheunderlyingtableorexpressionsoverthe
tablerows.Theindexaccessmethodnormallyhasnointerestinwheretheindexkeyvaluescome
from(itisalwayshandedprecomputedkeyvalues)butitwillbeveryinterestedintheoperatorclass
1932
C# Create PDF from images Library to convert Jpeg, png images to
List<Bitmap> images = new List<Bitmap>(); images.Add(new Bitmap(Program.RootPath + "\\" 1.gif")); / Build a PDF document with GIF image.
how to add image to pdf file; add jpeg to pdf
C# PDF Sticky Note Library: add, delete, update PDF note in C#.net
C#.NET PDF SDK - Add Sticky Note to PDF Page in C#.NET. Able to add notes to PDF using C# source code in Visual Studio .NET framework.
add photo to pdf for; add image to pdf in preview
Chapter55.IndexAccessMethodInterfaceDefinition
informationin
pg_index
.Bothofthesecatalogentriescanbeaccessedaspartofthe
Relation
data
structurethatispassedtoalloperationsontheindex.
Some of the flag columns of
pg_am
have nonobvious implications. The requirements of
amcanunique
are discussed inSection55.5. The
amcanmulticol
flag asserts that the access
methodsupportsmulticolumnindexes,while
amoptionalkey
assertsthatitallowsscanswhereno
indexablerestrictionclause is given forthefirst index column. When
amcanmulticol
is false,
amoptionalkey
essentiallysayswhethertheaccessmethodsupportsfull-indexscanswithoutany
restrictionclause.Accessmethodsthatsupportmultipleindexcolumnsmustsupportscansthatomit
restrictionsonanyorallofthecolumnsafterthefirst;howevertheyarepermittedtorequiresome
restrictiontoappearforthefirstindexcolumn,andthisissignaledbysetting
amoptionalkey
false.
OnereasonthatanindexAMmightset
amoptionalkey
falseisifitdoesn’tindexnullvalues.
Sincemostindexableoperatorsarestrictandhencecannotreturntruefornullinputs,itisatfirst
sightattractivetonotstoreindexentriesfornullvalues:theycouldneverbereturnedbyanindex
scananyway.However,thisargumentfailswhenanindexscanhasnorestrictionclauseforagiven
indexcolumn.Inpracticethismeansthatindexesthathave
amoptionalkey
truemustindexnulls,
sincetheplannermightdecidetousesuchanindexwithnoscankeysatall.Arelatedrestrictionis
thatanindexaccessmethodthatsupportsmultipleindexcolumnsmustsupportindexingnullvalues
incolumnsafterthefirst,becausetheplannerwillassumetheindexcanbeusedforqueriesthatdo
notrestrictthesecolumns.Forexample,consideranindexon(a,b)andaquerywith
WHERE a = 4
.
Thesystemwillassumetheindexcanbeusedtoscanforrowswith
a = 4
,whichiswrongifthe
indexomitsrowswhere
b
isnull.Itis,however,OKtoomitrowswherethefirstindexedcolumnis
null.Anindexaccessmethodthatdoesindexnullsmayalsoset
amsearchnulls
,indicatingthatit
supports
IS NULL
and
IS NOT NULL
clausesassearchconditions.
55.2. Index Access Method Functions
Theindexconstructionandmaintenancefunctionsthatanindexaccessmethodmustprovideare:
IndexBuildResult
*
ambuild (Relation heapRelation,
Relation indexRelation,
IndexInfo
*
indexInfo);
Buildanewindex.Theindexrelationhasbeenphysicallycreated,butisempty.Itmustbefilledin
withwhateverfixeddatatheaccessmethodrequires,plusentriesforalltuplesalreadyexistingin
thetable.Ordinarilythe
ambuild
functionwillcall
IndexBuildHeapScan()
toscanthetablefor
existingtuplesandcomputethekeysthatneedtobeinsertedintotheindex.Thefunctionmustreturn
apalloc’dstructcontainingstatisticsaboutthenewindex.
void
ambuildempty (Relation indexRelation);
Buildanemptyindex,andwriteittotheinitializationfork(
INIT_FORKNUM
)ofthegivenrelation.
Thismethodiscalledonlyforunloggedtables;theemptyindexwrittentotheinitializationforkwill
becopiedoverthemainrelationforkoneachserverrestart.
bool
aminsert (Relation indexRelation,
Datum
*
values,
bool
*
isnull,
ItemPointer heap_tid,
1933
Chapter55.IndexAccessMethodInterfaceDefinition
Relation heapRelation,
IndexUniqueCheck checkUnique);
Insertanewtupleintoanexistingindex.The
values
and
isnull
arraysgivethekeyvaluesto
beindexed,and
heap_tid
istheTIDtobeindexed.Iftheaccessmethodsupportsuniqueindexes
(its
pg_am
.
amcanunique
flagistrue)then
checkUnique
indicatesthetypeofuniquenesscheck
toperform.Thisvariesdependingonwhethertheuniqueconstraintisdeferrable;seeSection55.5
fordetails.Normallytheaccessmethodonlyneedsthe
heapRelation
parameterwhenperforming
uniquenesschecking(sincethenitwillhavetolookintotheheaptoverifytupleliveness).
The function’s Boolean result value is significant only when
checkUnique
is
UNIQUE_CHECK_PARTIAL
. In this case a TRUE result means the new entry is known unique,
whereasFALSEmeansitmightbenon-unique(andadeferreduniquenesscheckmustbescheduled).
ForothercasesaconstantFALSEresultisrecommended.
Someindexesmightnotindexalltuples.Ifthetupleisnottobeindexed,
aminsert
shouldjustreturn
withoutdoinganything.
IndexBulkDeleteResult
*
ambulkdelete (IndexVacuumInfo
*
info,
IndexBulkDeleteResult
*
stats,
IndexBulkDeleteCallback callback,
void
*
callback_state);
Deletetuple(s)fromtheindex.Thisisa“bulkdelete”operationthatisintendedtobeimplemented
byscanningthewholeindexandcheckingeachentrytoseeifitshouldbedeleted.Thepassed-in
callback
functionmustbe called, in the style
callback(
TID
, callback_state) returns
bool
,todeterminewhetheranyparticularindexentry,asidentifiedbyitsreferencedTID,istobe
deleted. Must return either NULL or a palloc’d struct containing statistics about the effects
ofthe deletion operation. Itis OKtoreturnNULLifnoinformation needstobe passed on to
amvacuumcleanup
.
Becauseoflimited
maintenance_work_mem
,
ambulkdelete
mightneedtobecalledmorethan
oncewhenmanytuplesaretobedeleted.The
stats
argumentistheresultofthepreviouscallfor
thisindex(itisNULLforthefirstcallwithina
VACUUM
operation).ThisallowstheAMtoaccumulate
statisticsacrossthewholeoperation.Typically,
ambulkdelete
willmodifyandreturnthesamestruct
ifthepassed
stats
isnotnull.
IndexBulkDeleteResult
*
amvacuumcleanup (IndexVacuumInfo
*
info,
IndexBulkDeleteResult
*
stats);
Cleanupaftera
VACUUM
operation(zeroormore
ambulkdelete
calls).Thisdoesnothavetodo
anythingbeyondreturningindexstatistics,butitmightperformbulkcleanupsuchasreclaimingempty
indexpages.
stats
iswhateverthelast
ambulkdelete
callreturned,orNULLif
ambulkdelete
wasnotcalledbecausenotuplesneededtobedeleted.IftheresultisnotNULLitmustbeapalloc’d
struct.Thestatisticsitcontainswillbeusedtoupdate
pg_class
,andwillbereportedby
VACUUM
if
VERBOSE
isgiven.ItisOKtoreturnNULLiftheindexwasnotchangedatallduringthe
VACUUM
operation,butotherwisecorrectstatsshouldbereturned.
AsofPostgreSQL8.4,
amvacuumcleanup
willalsobecalledatcompletionofan
ANALYZE
oper-
ation.Inthiscase
stats
isalwaysNULLandanyreturnvaluewillbeignored.Thiscasecanbe
distinguishedbychecking
info->analyze_only
.Itisrecommendedthattheaccessmethoddo
nothingexceptpost-insertcleanupinsuchacall,andthatonlyinanautovacuumworkerprocess.
1934
Chapter55.IndexAccessMethodInterfaceDefinition
bool
amcanreturn (Relation indexRelation);
Checkwhethertheindexcansupportindex-onlyscansbyreturningtheindexedcolumnvaluesforan
indexentryintheformofan
IndexTuple
.ReturnTRUEifso,elseFALSE.IftheindexAMcan
neversupportindex-onlyscans(anexampleishash,whichstoresonlythehashvaluesnottheoriginal
data),itissufficienttosetits
amcanreturn
fieldtozeroin
pg_am
.
void
amcostestimate (PlannerInfo
*
root,
IndexPath
*
path,
double loop_count,
Cost
*
indexStartupCost,
Cost
*
indexTotalCost,
Selectivity
*
indexSelectivity,
double
*
indexCorrelation);
Estimatethecostsofanindexscan.ThisfunctionisdescribedfullyinSection55.6,below.
bytea
*
amoptions (ArrayType
*
reloptions,
bool validate);
Parseandvalidatethereloptionsarrayforanindex.Thisiscalledonlywhenanon-nullreloptions
arrayexistsfortheindex.
reloptions
isa
text
arraycontainingentriesoftheform
name=value
.
Thefunctionshouldconstructa
bytea
value,whichwillbecopiedintothe
rd_options
fieldofthe
index’srelcacheentry.Thedatacontentsofthe
bytea
valueareopenfortheaccessmethodtodefine;
mostofthestandardaccessmethodsusestruct
StdRdOptions
.When
validate
istrue,thefunction
shouldreportasuitableerrormessageifanyoftheoptionsareunrecognizedorhaveinvalidvalues;
when
validate
isfalse,invalidentriesshouldbesilentlyignored.(
validate
isfalsewhenloading
optionsalreadystoredin
pg_catalog
;aninvalidentrycouldonlybefoundiftheaccessmethodhas
changeditsrulesforoptions,andinthatcaseignoringobsoleteentriesisappropriate.)ItisOKto
returnNULLifdefaultbehavioriswanted.
Thepurpose ofanindex,ofcourse, istosupportscans fortuplesmatchinganindexable
WHERE
condition,oftencalledaqualifierorscankey.Thesemanticsofindexscanningaredescribedmore
fullyinSection55.3,below.Anindexaccessmethodcansupport“plain”indexscans,“bitmap”index
scans,orboth.Thescan-relatedfunctionsthatanindexaccessmethodmustormayprovideare:
IndexScanDesc
ambeginscan (Relation indexRelation,
int nkeys,
int norderbys);
Prepareforanindexscan. The
nkeys
and
norderbys
parameters indicatethenumberofquals
andorderingoperatorsthatwillbeusedinthescan;thesemaybeusefulforspaceallocationpur-
poses.Notethattheactualvaluesofthescankeysaren’tprovidedyet.Theresultmustbeapal-
loc’dstruct.Forimplementationreasonstheindexaccessmethodmustcreatethisstructbycalling
RelationGetIndexScan()
.Inmostcases
ambeginscan
doeslittlebeyondmakingthatcalland
perhapsacquiringlocks;theinterestingpartsofindex-scanstartuparein
amrescan
.
void
amrescan (IndexScanDesc scan,
ScanKey keys,
1935
Chapter55.IndexAccessMethodInterfaceDefinition
int nkeys,
ScanKey orderbys,
int norderbys);
Startorrestartanindexscan,possiblywithnewscankeys.(Torestartusingpreviously-passedkeys,
NULLispassedfor
keys
and/or
orderbys
.)Notethatitisnotallowedforthenumberofkeysor
order-byoperatorstobelargerthanwhatwaspassedto
ambeginscan
.Inpracticetherestartfeature
isusedwhenanewoutertupleisselectedbyanested-loopjoinandsoanewkeycomparisonvalue
isneeded,butthescankeystructureremainsthesame.
boolean
amgettuple (IndexScanDesc scan,
ScanDirection direction);
Fetchthenexttupleinthegivenscan,movinginthegivendirection(forwardorbackwardinthe
index).ReturnsTRUEifatuplewasobtained,FALSEifnomatchingtuplesremain.IntheTRUEcase
thetupleTIDisstoredintothe
scan
structure.Notethat“success”meansonlythattheindexcontains
anentrythatmatchesthescankeys,notthatthetuplenecessarilystillexistsintheheaporwillpass
thecaller’ssnapshottest.Onsuccess,
amgettuple
mustalsoset
scan->xs_recheck
toTRUEor
FALSE.FALSEmeansitiscertainthattheindexentrymatchesthescankeys.TRUEmeansthisisnot
certain,andtheconditionsrepresentedbythescankeysmustberecheckedagainsttheheaptupleafter
fetchingit.Thisprovisionsupports“lossy”indexoperators.Notethatrecheckingwillextendonlyto
thescanconditions;apartialindexpredicate(ifany)isneverrecheckedby
amgettuple
callers.
Iftheindexsupportsindex-onlyscans(i.e.,
amcanreturn
returnsTRUEforit),thenonsuccessthe
AMmustalsocheck
scan->xs_want_itup
,andifthatistrueitmustreturntheoriginalindexed
datafortheindexentry,intheformofan
IndexTuple
pointerstoredat
scan->xs_itup
,withtuple
descriptor
scan->xs_itupdesc
.(Managementofthedatareferencedbythepointeristheaccess
method’sresponsibility.Thedatamustremaingoodatleastuntilthenext
amgettuple
,
amrescan
,
or
amendscan
callforthescan.)
The
amgettuple
functionneedonlybeprovidediftheaccessmethodsupports“plain”indexscans.
Ifitdoesn’t,the
amgettuple
fieldinits
pg_am
rowmustbesettozero.
int64
amgetbitmap (IndexScanDesc scan,
TIDBitmap
*
tbm);
Fetchalltuplesinthegivenscanandaddthemtothecaller-supplied
TIDBitmap
(thatis,ORthe
setoftupleIDsintowhateversetisalreadyinthebitmap).Thenumberoftuplesfetchedisreturned
(thismightbejustanapproximatecount,forinstancesomeAMsdonotdetectduplicates).While
insertingtupleIDsintothebitmap,
amgetbitmap
canindicatethatrecheckingofthescancondi-
tionsisrequiredforspecifictupleIDs.Thisisanalogoustothe
xs_recheck
outputparameterof
amgettuple
.Note:inthecurrentimplementation, supportforthisfeatureisconflatedwithsup-
portforlossystorageofthebitmapitself,andthereforecallersrecheckboththescanconditionsand
thepartialindexpredicate(ifany)forrecheckabletuples.Thatmightnotalwaysbetrue,however.
amgetbitmap
and
amgettuple
cannotbeusedinthesameindexscan;thereareotherrestrictions
toowhenusing
amgetbitmap
,asexplainedinSection55.3.
The
amgetbitmap
functionneedonlybeprovidediftheaccessmethodsupports“bitmap”index
scans.Ifitdoesn’t,the
amgetbitmap
fieldinits
pg_am
rowmustbesettozero.
void
amendscan (IndexScanDesc scan);
1936
Chapter55.IndexAccessMethodInterfaceDefinition
Endascanandreleaseresources.The
scan
structitselfshouldnotbefreed,butanylocksorpins
takeninternallybytheaccessmethodmustbereleased.
void
ammarkpos (IndexScanDesc scan);
Markcurrentscanposition.Theaccessmethodneedonlysupportonerememberedscanpositionper
scan.
void
amrestrpos (IndexScanDesc scan);
Restorethescantothemostrecentlymarkedposition.
Byconvention, the
pg_proc
entryforanindexaccess methodfunctionshouldshowthecorrect
numberofarguments,butdeclarethemallastype
internal
(sincemostoftheargumentshavetypes
thatarenotknowntoSQL,andwedon’twantuserscallingthefunctionsdirectlyanyway).Thereturn
typeisdeclaredas
void
,
internal
,or
boolean
asappropriate.Theonlyexceptionis
amoptions
,
whichshouldbecorrectlydeclaredastaking
text[]
and
bool
andreturning
bytea
.Thisprovision
allowsclientcodetoexecute
amoptions
totestvalidityofoptionssettings.
55.3. Index Scanning
Inanindexscan,theindexaccessmethodisresponsibleforregurgitatingtheTIDsofallthetuples
ithasbeentoldaboutthatmatchthescankeys.Theaccessmethodisnotinvolvedinactuallyfetch-
ingthosetuplesfromtheindex’sparenttable,norindeterminingwhethertheypassthescan’stime
qualificationtestorotherconditions.
Ascankeyis theinternalrepresentationofa
WHERE
clause ofthe form
index_key operator
constant
,wheretheindexkeyisoneofthecolumnsoftheindexandtheoperatorisoneofthe
membersoftheoperatorfamilyassociatedwiththatindexcolumn.Anindexscanhaszeroormore
scankeys,whichareimplicitlyANDed—thereturnedtuplesareexpectedtosatisfyalltheindicated
conditions.
Theaccessmethodcanreportthattheindexislossy,orrequiresrechecks,foraparticularquery.This
impliesthattheindexscanwillreturnalltheentriesthatpassthescankey,pluspossiblyadditional
entriesthatdonot.Thecoresystem’s index-scanmachinerywillthenapplytheindexconditions
againtotheheaptupletoverifywhetherornotitreallyshouldbeselected.Iftherecheckoptionis
notspecified,theindexscanmustreturnexactlythesetofmatchingentries.
Notethatitisentirelyuptotheaccessmethodtoensurethatitcorrectlyfindsallandonlytheentries
passingallthegivenscankeys.Also,thecoresystemwillsimplyhandoffallthe
WHERE
clauses
thatmatchtheindexkeysandoperatorfamilies,withoutanysemanticanalysistodeterminewhether
theyareredundantorcontradictory.Asanexample,given
WHERE x > 4 AND x > 14
where
x
is
ab-treeindexedcolumn,itislefttotheb-tree
amrescan
functiontorealizethatthefirstscankeyis
redundantandcanbediscarded.Theextentofpreprocessingneededduring
amrescan
willdepend
ontheextenttowhichtheindexaccessmethodneedstoreducethescankeystoa“normalized”form.
Someaccessmethodsreturnindexentriesinawell-definedorder,othersdonot.Thereareactually
twodifferentwaysthatanaccessmethodcansupportsortedoutput:
Accessmethodsthatalwaysreturnentriesinthenaturalorderingoftheirdata(suchasbtree)should
set
pg_am
.
amcanorder
totrue.Currently,suchaccessmethodsmustusebtree-compatiblestrategy
numbersfortheirequalityandorderingoperators.
1937
Documents you may be interested
Documents you may be interested