《數(shù)據(jù)庫系統(tǒng)》教學課件
《數(shù)據(jù)庫系統(tǒng)》教學課件,數(shù)據(jù)庫系統(tǒng),數(shù)據(jù)庫,系統(tǒng),教學,課件
Storing Data:Disks and FilesJianlin FengSchool of SoftwareSUN YAT-SEN UNIVERSITYcourtesy of Joe Hellerstein for some slidesBlock diagram of a DBMSQuery Optimizationand ExecutionRelational OperatorsFiles and Access MethodsBuffer ManagementDisk Space ManagementDBConcurrency Control and RecoveryDisks,Memory,and FilesQuery Optimizationand ExecutionRelational OperatorsFiles and Access MethodsBuffer ManagementDisk Space ManagementDBDisks and Files nDBMS stores information on disks.qTapes are also used.nMajor implications for DBMS design!qREAD:transfer data from disk to main memory(RAM).qWRITE:transfer data from RAM to disk.qBoth high-cost relative to memory referencesnCan/should plan carefully!Why Not Store Everything in Main Memory?nCosts too much.For$1000,PCConnection will sell you either q80GB of RAM(unrealistic)q400GB of Flash USB keys(unrealistic)q180GB of Flash solid-state disk(serious)q7.7TB of disk(serious)nMain memory is volatile.qWant data to persist between runs.(Obviously!)The Storage HierarchySource:Operating Systems Concepts 5th Edition Main memory(RAM)for currently used data.Disk for main database(secondary storage).Tapes for archive(tertiary storage).The role of Flash(SSD)still unclearSmaller,FasterBigger,SlowerDisksnStill the secondary storage device of choice.nMain advantage over tape:qrandom access vs.sequential.nFixed unit of transferqRead/write disk blocks or pages(8K)nNot“random access”(vs.RAM)qTime to retrieve a block depends on locationqRelative placement of blocks on disk has major impact on DBMS performance!Components of a Disk Platters The platters spin(say,120 rps).Spindle The arm assembly is moved in or out to position a head on a desired track.Tracks under heads make a cylinder(imaginary!).Disk headArm movementArm assemblyOnly one head reads/writes at any one time.TracksSectorv Block size is a multiple of sector size(which is fixed).Accessing a Disk PagenTime to access(read/write)a disk block:qseek time(moving arms to position disk head on track)qrotational delay(waiting for block to rotate under head)qtransfer time(actually moving data to/from disk surface)nSeek time and rotational delay dominate.qSeek time varies from 0 to 10msecqRotational delay varies from 0 to 3msecqTransfer rate around.02msec per 8K blocknKey to lower I/O cost:reduce seek/rotation delays!Hardware vs.software solutions?Arranging Pages on DisknNext block concept:qblocks on same track,followed byqblocks on same cylinder,followed byqblocks on adjacent cylindernBlocks in a file should be arranged sequentially on disk(by next),to minimize seek and rotational delay.nFor a sequential scan,pre-fetching several pages at a time is a big win!Disk Space ManagementnLowest layer of DBMS,manages space on disknHigher levels call upon this layer to:qallocate/de-allocate a pageqread/write a pagenRequest for a sequence of pages best satisfied by pages stored sequentially on disk!qResponsibility of disk space manager.qHigher levels dont know how this is done,or how free space is managed.qThough they may make performance assumptions!nHence disk space manager should do a decent job.ContextQuery Optimizationand ExecutionRelational OperatorsFiles and Access MethodsBuffer ManagementDisk Space ManagementDBBuffer Management in a DBMSnData must be in RAM for DBMS to operate on it!nBufMgr hides the fact that not all data is in RAMAXCDBMAIN MEMORYDISKcopy ofdisk pagefree framePage Requests from Higher LevelsBUFFER POOLchoice of frame dictatedby replacement policyAdisk pageWhen a Page is Requested.nBuffer pool information table contains:1.If requested page is not in pool:a.Choose a frame for replacement.Only“un-pinned”pages are candidates!b.If frame“dirty”,write current page to diskc.Read requested page into frame2.Pin the page and return its address.*If requests can be predicted(e.g.,sequential scans)pages can be pre-fetched several pages at a time!More on Buffer ManagementnRequestor of page must eventually:1.unpin it2.indicate whether page was modified via dirty bit.nPage in pool may be requested many times,qa pin _count is used.qTo pin a page:pin_count+q A page is a candidate for replacement iff pin_count=0(“unpinned”)nConcurrency Control(CC)&recovery may do additional I/Os upon replacement.qWrite-Ahead Log protocol;more later!Buffer Replacement PolicynFrame is chosen for replacement by a replacement policy:qLeast-recently-used(LRU),MRU,Clock,nPolicy can have big impact on#I/Os;qDepends on the access pattern.LRU Replacement PolicynLeast Recently Used(LRU)qtrack time each frame last unpinned(end of use),qby using a queue of pointers to frames with pin_count 0.qreplace the frame which has the earliest unpinned timenVery common policy:intuitive and simpleqWorks well for repeated accesses to popular pagesProblem of LRUnProblem:Sequential flooding qLRU+repeated sequential scans.nAn illustrative situation:qsuppose a buffer pool has 10 frames,qand the file to be scanned has 11 frames;qthen using LRU,every scan of the file will result in reading every page of the file.“Clock”Replacement PolicynAn approximation of LRUqHas similar behavior but less overheadnArrange frames into a cycle,store one reference bit per frameqCan think of this as the 2nd chance bitnWhen pin_count reduces to 0,turn on reference bit(ref bit).nWhen replacement necessary:do for each frame in cycle if(pin_count=0&ref bit is on)turn off ref bit;/2nd chanceelse if(pin_count=0&ref bit is off)choose this page for replacement;until a page is chosen;A(1)B(p)C(1)D(1)DBMS vs.OS File System OS does disk space&buffer mgmt:why not let OS manage these tasks?nA DBMS can often predict page reference patterns more accurately than an OS.qMost page references are generated by higher-level operations such as sequential scan.qadjust replacement policy,and pre-fetch pages based on page reference patterns in typical DB operations.nA DBMS also requires the ability to explicitly force a page to disk.qFor realizing Write-Ahead Log protocolContextQuery Optimizationand ExecutionRelational OperatorsFiles and Access MethodsBuffer ManagementDisk Space ManagementDBFiles of RecordsnBlocks are the interface for I/O,butnHigher levels of DBMS operate on records,and files of records.nFILE:A collection of pages,each containing a collection of records.Must support:qinsert/delete/modify recordqfetch a particular record(specified using record id)qscan all records(possibly with some conditions on the records to be retrieved)nTypically implemented as multiple OS“files”qOr“raw”disk spaceUnordered(Heap)FilesnCollection of records in no particular order.nAs file shrinks/grows,disk pages(de)allocatednTo support record level operations,we must:qkeep track of the pages in a fileqkeep track of free space on pagesqkeep track of the records on a pagenThere are many alternatives for keeping track of this.qWell consider two.Heap File Implemented as a List nThe header page id and Heap file name must be stored someplace.qDatabase“catalog”nEach page contains 2 pointers plus data.HeaderPageDataPageDataPageDataPageDataPageDataPageDataPagePages withFree SpaceFull PagesHeap File Implemented as a List(Cont.)nOne disadvantageqVirtually all pages will be on the free list if records are of variable length,i.e.,every page may have some free bytes if we like to keep each record in a single page.HeaderPageDataPageDataPageDataPageDataPageDataPageDataPagePages withFree SpaceFull PagesHeap File Using a Page DirectorynThe directory is itself a collection of pages;each page can hold several entries.nThe entry for a page can include the number of free bytes on the page.nTo insert a record,we can search the directory to determine which page has enough space to hold the record.DataPage 1DataPage 2DataPage NHeaderPageDIRECTORYIndexes(a sneak preview)nA Heap file allows us to retrieve records:qby specifying the rid(record id),orqby scanning all records sequentiallynSometimes,we want to retrieve records by specifying the values in one or more fields,e.g.,qFind all students in the“CS”departmentqFind all students with a gpa 3nIndexes are file structures that enable us to answer such value-based queries efficiently.Record Formats:Fixed LengthnInformation about field types same for all records in a file;stored in system catalogs.nFinding ith field done via arithmetic.Base address(B)L1L2L3L4F1F2F3F4Address=B+L1+L2Record Formats:Variable LengthnTwo alternative formats(#fields is fixed):*Second offers direct access to ith field,efficient storage of nulls(special dont know value);small directory overhead.$Fields Delimited by Special SymbolsF1 F2 F3 F4F1 F2 F3 F4Array of Field OffsetsPage Formats:Fixed Length Records*Record id=.In first alternative,moving records for free space management changes rid;may not be acceptable.Slot 1Slot 2Slot N.NM10.M .3 2 1PACKEDUNPACKED,BITMAPSlot 1Slot 2Slot NFreeSpaceSlot M11number of recordsnumberof slotsPage Formats:Variable Length Records*Can move records on page without changing rid;so,attractive for fixed-length records too.Page iRid=(i,N)Rid=(i,2)Rid=(i,1)Pointerto startof freespaceSLOT DIRECTORYN .2 1201624N#slotsData AreaFree Spaceslots format:081624Slotted page:a detailed viewnWhats the biggest tuple you can add?qNeeds 2 bytes of slot spaceqx bytes of storage4804213Pointerto startof freespaceSlot directory#of slotsSystem CatalogsnFor each relation:qname,file location,file structure(e.g.,Heap file)qattribute name and type,for each attributeqindex name,for each indexqintegrity constraintsnFor each index:qstructure(e.g.,B+tree)and search key fieldsnFor each view:qview name and definitionnPlus statistics,authorization,buffer pool size,etc.*Catalogs are themselves stored as relations!Attr_Cat(attr_name,rel_name,type,position)attr_namerel_nametypepositionattr_nameAttribute_Catstring1rel_nameAttribute_Catstring2typeAttribute_Catstring3positionAttribute_Catinteger4sidStudentsstring1nameStudentsstring2loginStudentsstring3ageStudentsinteger4gpaStudentsreal5fidFacultystring1fnameFacultystring2salFacultyreal3SummarynDisks provide cheap,non-volatile storage.qBetter random access than tape,worse than RAMqArrange data to minimize seek and rotation delays.nDepends on workload!nBuffer manager brings pages into RAM.qPage pinned in RAM until released by requestor.qDirty pages written to disk when frame replaced(sometime after requestor unpins the page).qChoice of frame to replace based on replacement policy.qTries to pre-fetch several pages at a time.Summary(Contd.)nDBMS vs.OS File SupportqDBMS needs non-default featuresqCareful timing of writes,control over prefetchnVariable length record formatqDirect access to ith field and null values.nSlotted page format qVariable length records and intra-page reorgSummary(Contd.)nDBMS“File”tracks collection of pages,records within each.qPages with free space identified using linked list or directory structurenIndexes support efficient retrieval of records based on the values in some fields.nCatalog relations store information about relations,indexes and views.
收藏