dbf_idxfile.pas 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103
  1. unit dbf_idxfile;
  2. interface
  3. {$I dbf_common.inc}
  4. uses
  5. {$ifdef WIN32}
  6. Windows,
  7. {$else}
  8. {$ifdef KYLIX}
  9. Libc,
  10. {$endif}
  11. Types, dbf_wtil,
  12. {$endif}
  13. SysUtils,
  14. Classes,
  15. db,
  16. dbf_pgfile,
  17. {$ifdef USE_CACHE}
  18. dbf_pgcfile,
  19. {$endif}
  20. dbf_parser,
  21. dbf_prsdef,
  22. dbf_cursor,
  23. dbf_common;
  24. {$ifdef _DEBUG}
  25. {$define TDBF_INDEX_CHECK}
  26. {$endif}
  27. {$ifdef _ASSERTS}
  28. {$define TDBF_INDEX_CHECK}
  29. {$endif}
  30. const
  31. MaxIndexes = 47;
  32. type
  33. TIndexPage = class;
  34. TIndexTag = class;
  35. TIndexUpdateMode = (umAll, umCurrent);
  36. TLocaleError = (leNone, leUnknown, leTableIndexMismatch, leNotAvailable);
  37. TLocaleSolution = (lsNotOpen, lsNoEdit, lsBinary);
  38. TIndexUniqueType = (iuNormal, iuUnique, iuDistinct);
  39. TIndexModifyMode = (mmNormal, mmDeleteRecall);
  40. TDbfLocaleErrorEvent = procedure(var Error: TLocaleError; var Solution: TLocaleSolution) of object;
  41. TDbfCompareKeyEvent = function(Key: PChar): Integer of object;
  42. TDbfCompareKeysEvent = function(Key1, Key2: PChar): Integer of object;
  43. PDouble = ^Double;
  44. PInteger = ^Integer;
  45. //===========================================================================
  46. TDbfIndexDef = class;
  47. TDbfIndexDef = class(TCollectionItem)
  48. protected
  49. FIndexName: string;
  50. FExpression: string;
  51. FOptions: TIndexOptions;
  52. FTemporary: Boolean; // added at runtime
  53. procedure SetIndexName(NewName: string);
  54. procedure SetExpression(NewField: string);
  55. public
  56. constructor Create(ACollection: TCollection); override;
  57. destructor Destroy; override;
  58. procedure Assign(Source: TPersistent); override;
  59. property Temporary: Boolean read FTemporary write FTemporary;
  60. property Name: string read FIndexName write SetIndexName;
  61. property Expression: string read FExpression write SetExpression;
  62. published
  63. property IndexFile: string read FIndexName write SetIndexName;
  64. property SortField: string read FExpression write SetExpression;
  65. property Options: TIndexOptions read FOptions write FOptions;
  66. end;
  67. //===========================================================================
  68. TIndexFile = class;
  69. TIndexPageClass = class of TIndexPage;
  70. TIndexPage = class(TObject)
  71. protected
  72. FIndexFile: TIndexFile;
  73. FLowerPage: TIndexPage;
  74. FUpperPage: TIndexPage;
  75. FPageBuffer: Pointer;
  76. FEntry: Pointer;
  77. FEntryNo: Integer;
  78. FLockCount: Integer;
  79. FModified: Boolean;
  80. FPageNo: Integer;
  81. FWeight: Integer;
  82. // bracket props
  83. FLowBracket: Integer; // = FLowIndex if FPageNo = FLowPage
  84. FLowIndex: Integer;
  85. FLowPage: Integer;
  86. FHighBracket: Integer; // = FHighIndex if FPageNo = FHighPage
  87. FHighIndex: Integer;
  88. FHighPage: Integer;
  89. procedure LocalInsert(RecNo: Integer; Buffer: PChar; LowerPageNo: Integer);
  90. procedure LocalDelete;
  91. procedure Delete;
  92. procedure SyncLowerPage;
  93. procedure WritePage;
  94. procedure Split;
  95. procedure LockPage;
  96. procedure UnlockPage;
  97. function RecurPrev: Boolean;
  98. function RecurNext: Boolean;
  99. procedure RecurFirst;
  100. procedure RecurLast;
  101. procedure SetEntry(RecNo: Integer; AKey: PChar; LowerPageNo: Integer);
  102. procedure SetEntryNo(value: Integer);
  103. procedure SetPageNo(NewPageNo: Integer);
  104. procedure SetLowPage(NewPage: Integer);
  105. procedure SetHighPage(NewPage: Integer);
  106. procedure SetUpperPage(NewPage: TIndexPage);
  107. procedure UpdateBounds(IsInnerNode: Boolean);
  108. protected
  109. function GetEntry(AEntryNo: Integer): Pointer; virtual; abstract;
  110. function GetLowerPageNo: Integer; virtual; abstract;
  111. function GetKeyData: PChar; virtual; abstract;
  112. function GetNumEntries: Integer; virtual; abstract;
  113. function GetKeyDataFromEntry(AEntry: Integer): PChar; virtual; abstract;
  114. function GetRecNo: Integer; virtual; abstract;
  115. function GetIsInnerNode: Boolean; virtual; abstract;
  116. procedure IncNumEntries; virtual; abstract;
  117. procedure SetNumEntries(NewNum: Integer); virtual; abstract;
  118. procedure SetRecLowerPageNo(NewRecNo, NewPageNo: Integer); virtual; abstract;
  119. procedure SetRecLowerPageNoOfEntry(AEntry, NewRecNo, NewPageNo: Integer); virtual; abstract;
  120. {$ifdef TDBF_UPDATE_FIRST_LAST_NODE}
  121. procedure SetPrevBlock(NewBlock: Integer); virtual;
  122. {$endif}
  123. public
  124. constructor Create(Parent: TIndexFile);
  125. destructor Destroy; override;
  126. function FindNearest(ARecNo: Integer): Integer;
  127. function PhysicalRecNo: Integer;
  128. function MatchKey: Integer;
  129. procedure GotoInsertEntry;
  130. procedure Clear;
  131. procedure GetNewPage;
  132. procedure Modified;
  133. procedure RecalcWeight;
  134. procedure UpdateWeight;
  135. procedure Flush;
  136. property Key: PChar read GetKeyData;
  137. property Entry: Pointer read FEntry;
  138. property EntryNo: Integer read FEntryNo write SetEntryNo;
  139. property IndexFile: TIndexFile read FIndexFile;
  140. property UpperPage: TIndexPage read FUpperPage write SetUpperPage;
  141. property LowerPage: TIndexPage read FLowerPage;
  142. // property LowerPageNo: Integer read GetLowerPageNo; // never used
  143. property PageBuffer: Pointer read FPageBuffer;
  144. property PageNo: Integer read FPageNo write SetPageNo;
  145. property Weight: Integer read FWeight;
  146. property NumEntries: Integer read GetNumEntries;
  147. property HighBracket: Integer read FHighBracket write FHighBracket;
  148. property HighIndex: Integer read FHighIndex;
  149. property HighPage: Integer read FHighPage write SetHighPage;
  150. property LowBracket: Integer read FLowBracket write FLowBracket;
  151. property LowIndex: Integer read FLowIndex;
  152. property LowPage: Integer read FLowPage write SetLowPage;
  153. end;
  154. //===========================================================================
  155. TIndexTag = class(TObject)
  156. private
  157. FTag: Pointer;
  158. protected
  159. function GetHeaderPageNo: Integer; virtual; abstract;
  160. function GetTagName: string; virtual; abstract;
  161. function GetKeyFormat: Byte; virtual; abstract;
  162. function GetForwardTag1: Byte; virtual; abstract;
  163. function GetForwardTag2: Byte; virtual; abstract;
  164. function GetBackwardTag: Byte; virtual; abstract;
  165. function GetReserved: Byte; virtual; abstract;
  166. function GetKeyType: Char; virtual; abstract;
  167. procedure SetHeaderPageNo(NewPageNo: Integer); virtual; abstract;
  168. procedure SetTagName(NewName: string); virtual; abstract;
  169. procedure SetKeyFormat(NewFormat: Byte); virtual; abstract;
  170. procedure SetForwardTag1(NewTag: Byte); virtual; abstract;
  171. procedure SetForwardTag2(NewTag: Byte); virtual; abstract;
  172. procedure SetBackwardTag(NewTag: Byte); virtual; abstract;
  173. procedure SetReserved(NewReserved: Byte); virtual; abstract;
  174. procedure SetKeyType(NewType: Char); virtual; abstract;
  175. public
  176. property HeaderPageNo: Integer read GetHeaderPageNo write SetHeaderPageNo;
  177. property TagName: string read GetTagName write SetTagName;
  178. property KeyFormat: Byte read GetKeyFormat write SetKeyFormat;
  179. property ForwardTag1: Byte read GetForwardTag1 write SetForwardTag1;
  180. property ForwardTag2: Byte read GetForwardTag2 write SetForwardTag2;
  181. property BackwardTag: Byte read GetBackwardTag write SetBackwardTag;
  182. property Reserved: Byte read GetReserved write SetReserved;
  183. property KeyType: Char read GetKeyType write SetKeyType;
  184. property Tag: Pointer read FTag write FTag;
  185. end;
  186. //===========================================================================
  187. {$ifdef USE_CACHE}
  188. TIndexFile = class(TCachedFile)
  189. {$else}
  190. TIndexFile = class(TPagedFile)
  191. {$endif}
  192. protected
  193. FIndexName: string;
  194. FParsers: array[0..MaxIndexes-1] of TDbfParser;
  195. FIndexHeaders: array[0..MaxIndexes-1] of Pointer;
  196. FIndexHeaderModified: array[0..MaxIndexes-1] of Boolean;
  197. FIndexHeader: Pointer;
  198. FIndexVersion: TXBaseVersion;
  199. FRoots: array[0..MaxIndexes-1] of TIndexPage;
  200. FLeaves: array[0..MaxIndexes-1] of TIndexPage;
  201. FCurrentParser: TDbfParser;
  202. FRoot: TIndexPage;
  203. FLeaf: TIndexPage;
  204. FMdxTag: TIndexTag;
  205. FTempMdxTag: TIndexTag;
  206. FEntryHeaderSize: Integer;
  207. FPageHeaderSize: Integer;
  208. FTagSize: Integer;
  209. FTagOffset: Integer;
  210. FHeaderPageNo: Integer;
  211. FSelectedIndex: Integer;
  212. FIsDescending: Boolean;
  213. FUniqueMode: TIndexUniqueType;
  214. FModifyMode: TIndexModifyMode;
  215. FHeaderLocked: Integer; // used to remember which header page we have locked
  216. FKeyBuffer: array[0..100] of Char;
  217. FLowBuffer: array[0..100] of Char;
  218. FHighBuffer: array[0..100] of Char;
  219. FEntryBof: Pointer;
  220. FEntryEof: Pointer;
  221. FDbfFile: Pointer;
  222. FCanEdit: Boolean;
  223. FOpened: Boolean;
  224. FRangeActive: Boolean;
  225. FUpdateMode: TIndexUpdateMode;
  226. FUserKey: PChar; // find / insert key
  227. FUserRecNo: Integer; // find / insert recno
  228. FUserBCD: array[0..10] of Byte;
  229. FUserNumeric: Double;
  230. FForceClose: Boolean;
  231. FForceReadOnly: Boolean;
  232. FLocaleID: LCID;
  233. FLocaleCP: Integer;
  234. FCodePage: Integer;
  235. FCompareKey: TDbfCompareKeyEvent;
  236. FCompareKeys: TDbfCompareKeysEvent;
  237. FOnLocaleError: TDbfLocaleErrorEvent;
  238. function GetNewPageNo: Integer;
  239. procedure TouchHeader(AHeader: Pointer);
  240. function CreateTempFile(BaseName: string): TPagedFile;
  241. procedure WriteIndexHeader(AIndex: Integer);
  242. procedure SelectIndexVars(AIndex: Integer);
  243. procedure CalcKeyProperties;
  244. procedure UpdateIndexProperties;
  245. procedure ClearRoots;
  246. function CalcTagOffset(AIndex: Integer): Pointer;
  247. function FindKey(AInsert: boolean): Integer;
  248. procedure InsertKey(Buffer: PChar);
  249. procedure DeleteKey(Buffer: PChar);
  250. procedure InsertCurrent;
  251. procedure DeleteCurrent;
  252. procedure UpdateCurrent(PrevBuffer, NewBuffer: PChar);
  253. procedure ReadIndexes;
  254. procedure Resync(Relative: boolean);
  255. procedure ResyncRoot;
  256. procedure ResyncTree;
  257. procedure ResyncRange(KeepPosition: boolean);
  258. procedure ResetRange;
  259. procedure SetBracketLow;
  260. procedure SetBracketHigh;
  261. procedure WalkFirst;
  262. procedure WalkLast;
  263. function WalkPrev: boolean;
  264. function WalkNext: boolean;
  265. procedure TranslateToANSI(Src, Dest: PChar);
  266. function CompareKeyNumericNDX(Key: PChar): Integer;
  267. function CompareKeyNumericMDX(Key: PChar): Integer;
  268. function CompareKeyString(Key: PChar): Integer;
  269. function CompareKeysNumericNDX(Key1, Key2: PChar): Integer;
  270. function CompareKeysNumericMDX(Key1, Key2: PChar): Integer;
  271. function CompareKeysString(Key1, Key2: PChar): Integer;
  272. // property functions
  273. function GetName: string;
  274. function GetDbfLanguageId: Byte;
  275. function GetKeyLen: Integer;
  276. function GetKeyType: Char;
  277. // function GetIndexCount Integer;
  278. function GetExpression: string;
  279. function GetPhysicalRecNo: Integer;
  280. function GetSequentialRecNo: Integer;
  281. function GetSequentialRecordCount: Integer;
  282. procedure SetSequentialRecNo(RecNo: Integer);
  283. procedure SetPhysicalRecNo(RecNo: Integer);
  284. procedure SetUpdateMode(NewMode: TIndexUpdateMode);
  285. procedure SetIndexName(const AIndexName: string);
  286. procedure SetLocaleID(const NewID: LCID);
  287. property InternalLocaleID: LCID read FLocaleID write SetLocaleID;
  288. public
  289. constructor Create(ADbfFile: Pointer);
  290. destructor Destroy; override;
  291. procedure Open;
  292. procedure Close;
  293. procedure Clear;
  294. procedure Flush; override;
  295. procedure ClearIndex;
  296. procedure AddNewLevel;
  297. procedure UnlockHeader;
  298. procedure InsertError;
  299. procedure Insert(RecNo: Integer; Buffer: PChar);
  300. procedure Update(RecNo: Integer; PrevBuffer, NewBuffer: PChar);
  301. procedure Delete(RecNo: Integer; Buffer: PChar);
  302. function CheckKeyViolation(Buffer: PChar): Boolean;
  303. procedure RecordDeleted(RecNo: Integer; Buffer: PChar);
  304. procedure RecordRecalled(RecNo: Integer; Buffer: PChar);
  305. procedure DeleteIndex(const AIndexName: string);
  306. procedure RepageFile;
  307. procedure CompactFile;
  308. procedure PrepareRename(NewFileName: string);
  309. procedure CreateIndex(FieldDesc, TagName: string; Options: TIndexOptions);
  310. function ExtractKeyFromBuffer(Buffer: PChar): PChar;
  311. function SearchKey(Key: PChar; SearchType: TSearchKeyType): Boolean;
  312. function Find(RecNo: Integer; Buffer: PChar): Integer;
  313. function IndexOf(const AIndexName: string): Integer;
  314. procedure GetIndexNames(const AList: TStrings);
  315. procedure GetIndexInfo(const AIndexName: string; IndexDef: TDbfIndexDef);
  316. procedure WriteHeader; override;
  317. procedure WriteFileHeader;
  318. procedure First;
  319. procedure Last;
  320. function Next: Boolean;
  321. function Prev: Boolean;
  322. procedure SetRange(LowRange, HighRange: PChar);
  323. procedure CancelRange;
  324. function MatchKey(UserKey: PChar): Integer;
  325. function CompareKey(Key: PChar): Integer;
  326. function CompareKeys(Key1, Key2: PChar): Integer;
  327. function PrepareKey(Buffer: PChar; ResultType: TExpressionType): PChar;
  328. property KeyLen: Integer read GetKeyLen;
  329. property IndexVersion: TXBaseVersion read FIndexVersion;
  330. property EntryHeaderSize: Integer read FEntryHeaderSize;
  331. property KeyType: Char read GetKeyType;
  332. property SequentialRecordCount: Integer read GetSequentialRecordCount;
  333. property SequentialRecNo: Integer read GetSequentialRecNo write SetSequentialRecNo;
  334. property PhysicalRecNo: Integer read GetPhysicalRecNo write SetPhysicalRecNo;
  335. property HeaderPageNo: Integer read FHeaderPageNo;
  336. property IndexHeader: Pointer read FIndexHeader;
  337. property EntryBof: Pointer read FEntryBof;
  338. property EntryEof: Pointer read FEntryEof;
  339. property UniqueMode: TIndexUniqueType read FUniqueMode;
  340. property IsDescending: Boolean read FIsDescending;
  341. property UpdateMode: TIndexUpdateMode read FUpdateMode write SetUpdateMode;
  342. property IndexName: string read FIndexName write SetIndexName;
  343. property Expression: string read GetExpression;
  344. // property Count: Integer read GetIndexCount;
  345. property ForceClose: Boolean read FForceClose;
  346. property ForceReadOnly: Boolean read FForceReadOnly;
  347. property LocaleID: LCID read FLocaleID;
  348. property CodePage: Integer read FCodePage write FCodePage;
  349. property OnLocaleError: TDbfLocaleErrorEvent read FOnLocaleError write FOnLocaleError;
  350. end;
  351. //------------------------------------------------------------------------------
  352. implementation
  353. uses
  354. dbf_dbffile,
  355. dbf_fields,
  356. dbf_str,
  357. dbf_lang;
  358. const
  359. RecBOF = 0;
  360. RecEOF = MaxInt;
  361. lcidBinary = $0A03;
  362. KeyFormat_Expression = $00;
  363. KeyFormat_Data = $10;
  364. KeyFormat_Descending = $08;
  365. KeyFormat_String = $10;
  366. KeyFormat_Distinct = $20;
  367. KeyFormat_Unique = $40;
  368. Unique_None = $00;
  369. Unique_Unique = $01;
  370. Unique_Distinct = $21;
  371. type
  372. TLCIDList = class(TList)
  373. public
  374. constructor Create;
  375. procedure Enumerate;
  376. end;
  377. PMdxHdr = ^rMdxHdr;
  378. rMdxHdr = record
  379. MdxVersion : Byte; // 0
  380. Year : Byte; // 1
  381. Month : Byte; // 2
  382. Day : Byte; // 3
  383. FileName : array[0..15] of Char; // 4..19
  384. BlockSize : Word; // 20..21
  385. BlockAdder : Word; // 22..23
  386. ProdFlag : Byte; // 24
  387. NumTags : Byte; // 25
  388. TagSize : Byte; // 26
  389. Dummy1 : Byte; // 27
  390. TagsUsed : Word; // 28..29
  391. Dummy2 : Byte; // 30
  392. Language : Byte; // 31
  393. NumPages : Integer; // 32..35
  394. FreePage : Integer; // 36..39
  395. BlockFree : Integer; // 40..43
  396. UpdYear : Byte; // 44
  397. UpdMonth : Byte; // 45
  398. UpdDay : Byte; // 46
  399. Reserved : array[0..481] of Byte; // 47..528
  400. TagFlag : Byte; // 529 // dunno what this means but it ought to be 1 :-)
  401. end;
  402. // Tags -> I don't know what to with them
  403. // KeyType -> Variable position, db7 different from db4
  404. PMdx4Tag = ^rMdx4Tag;
  405. rMdx4Tag = record
  406. HeaderPageNo : Integer; // 0..3
  407. TagName : array [0..10] of Char; // 4..14 of Byte
  408. KeyFormat : Byte; // 15 00h: Calculated
  409. // 10h: Data Field
  410. ForwardTag1 : Byte; // 16
  411. ForwardTag2 : Byte; // 17
  412. BackwardTag : Byte; // 18
  413. Reserved : Byte; // 19
  414. KeyType : Char; // 20 C : Character
  415. // N : Numerical
  416. // D : Date
  417. end;
  418. PMdx7Tag = ^rMdx7Tag;
  419. rMdx7Tag = record
  420. HeaderPageNo : Integer; // 0..3
  421. TagName : array [0..32] of Char; // 4..36 of Byte
  422. KeyFormat : Byte; // 37 00h: Calculated
  423. // 10h: Data Field
  424. ForwardTag1 : Byte; // 38
  425. ForwardTag2 : Byte; // 39
  426. BackwardTag : Byte; // 40
  427. Reserved : Byte; // 41
  428. KeyType : Char; // 42 C : Character
  429. // N : Numerical
  430. // D : Date
  431. end;
  432. PIndexHdr = ^rIndexHdr;
  433. rIndexHdr = record
  434. RootPage : Integer; // 0..3
  435. NumPages : Integer; // 4..7
  436. KeyFormat : Byte; // 8 00h: Right, Left, DTOC
  437. // 08h: Descending order
  438. // 10h: String
  439. // 20h: Distinct
  440. // 40h: Unique
  441. KeyType : Char; // 9 C : Character
  442. // N : Numerical
  443. // D : Date
  444. Dummy : Word; // 10..11
  445. KeyLen : Word; // 12..13
  446. NumKeys : Word; // 14..15
  447. sKeyType : Word; // 16..17 00h: DB4: C/N; DB3: C
  448. // 01h: DB4: D ; DB3: N/D
  449. KeyRecLen : Word; // 18..19 Length of key entry in page
  450. Version : Word; // 20..21
  451. Dummy2 : Byte; // 22
  452. Unique : Byte; // 23
  453. KeyDesc : array [0..219] of Char; // 24..243
  454. Dummy3 : Byte; // 244
  455. ForExist : Byte; // 245
  456. KeyExist : Byte; // 246
  457. FirstNode : Longint; // 248..251 first node that contains data
  458. LastNode : Longint; // 252..255 last node that contains data
  459. // MDX Header has here a 506 byte block reserved
  460. // and then the FILTER expression, which obviously doesn't
  461. // fit in a NDX page, so we'll skip it
  462. end;
  463. PMdxEntry = ^rMdxEntry;
  464. rMdxEntry = record
  465. RecBlockNo: Longint; // 0..3 either recno or blockno
  466. KeyData : Char; // 4.. first byte of data, context => length
  467. end;
  468. PMdxPage = ^rMdxPage;
  469. rMdxPage = record
  470. NumEntries : Integer;
  471. PrevBlock : Integer;
  472. FirstEntry : rMdxEntry;
  473. end;
  474. PNdxEntry = ^rNdxEntry;
  475. rNdxEntry = record
  476. LowerPageNo: Integer; // 0..3 lower page
  477. RecNo : Integer; // 4..7 recno
  478. KeyData : Char;
  479. end;
  480. PNdxPage = ^rNdxPage;
  481. rNdxPage = record
  482. NumEntries: Integer; // 0..3
  483. FirstEntry: rNdxEntry;
  484. end;
  485. //---------------------------------------------------------------------------
  486. TMdxPage = class(TIndexPage)
  487. protected
  488. function GetEntry(AEntryNo: Integer): Pointer; override;
  489. function GetLowerPageNo: Integer; override;
  490. function GetKeyData: PChar; override;
  491. function GetNumEntries: Integer; override;
  492. function GetKeyDataFromEntry(AEntry: Integer): PChar; override;
  493. function GetRecNo: Integer; override;
  494. function GetIsInnerNode: Boolean; override;
  495. procedure IncNumEntries; override;
  496. procedure SetNumEntries(NewNum: Integer); override;
  497. procedure SetRecLowerPageNo(NewRecNo, NewPageNo: Integer); override;
  498. procedure SetRecLowerPageNoOfEntry(AEntry, NewRecNo, NewPageNo: Integer); override;
  499. {$ifdef TDBF_UPDATE_FIRST_LAST_NODE}
  500. procedure SetPrevBlock(NewBlock: Integer); override;
  501. {$endif}
  502. end;
  503. //---------------------------------------------------------------------------
  504. TNdxPage = class(TIndexPage)
  505. protected
  506. function GetEntry(AEntryNo: Integer): Pointer; override;
  507. function GetLowerPageNo: Integer; override;
  508. function GetKeyData: PChar; override;
  509. function GetNumEntries: Integer; override;
  510. function GetKeyDataFromEntry(AEntry: Integer): PChar; override;
  511. function GetRecNo: Integer; override;
  512. function GetIsInnerNode: Boolean; override;
  513. procedure IncNumEntries; override;
  514. procedure SetNumEntries(NewNum: Integer); override;
  515. procedure SetRecLowerPageNo(NewRecNo, NewPageNo: Integer); override;
  516. procedure SetRecLowerPageNoOfEntry(AEntry, NewRecNo, NewPageNo: Integer); override;
  517. end;
  518. //---------------------------------------------------------------------------
  519. TMdx4Tag = class(TIndexTag)
  520. protected
  521. function GetHeaderPageNo: Integer; override;
  522. function GetTagName: string; override;
  523. function GetKeyFormat: Byte; override;
  524. function GetForwardTag1: Byte; override;
  525. function GetForwardTag2: Byte; override;
  526. function GetBackwardTag: Byte; override;
  527. function GetReserved: Byte; override;
  528. function GetKeyType: Char; override;
  529. procedure SetHeaderPageNo(NewPageNo: Integer); override;
  530. procedure SetTagName(NewName: string); override;
  531. procedure SetKeyFormat(NewFormat: Byte); override;
  532. procedure SetForwardTag1(NewTag: Byte); override;
  533. procedure SetForwardTag2(NewTag: Byte); override;
  534. procedure SetBackwardTag(NewTag: Byte); override;
  535. procedure SetReserved(NewReserved: Byte); override;
  536. procedure SetKeyType(NewType: Char); override;
  537. end;
  538. //---------------------------------------------------------------------------
  539. TMdx7Tag = class(TIndexTag)
  540. function GetHeaderPageNo: Integer; override;
  541. function GetTagName: string; override;
  542. function GetKeyFormat: Byte; override;
  543. function GetForwardTag1: Byte; override;
  544. function GetForwardTag2: Byte; override;
  545. function GetBackwardTag: Byte; override;
  546. function GetReserved: Byte; override;
  547. function GetKeyType: Char; override;
  548. procedure SetHeaderPageNo(NewPageNo: Integer); override;
  549. procedure SetTagName(NewName: string); override;
  550. procedure SetKeyFormat(NewFormat: Byte); override;
  551. procedure SetForwardTag1(NewTag: Byte); override;
  552. procedure SetForwardTag2(NewTag: Byte); override;
  553. procedure SetBackwardTag(NewTag: Byte); override;
  554. procedure SetReserved(NewReserved: Byte); override;
  555. procedure SetKeyType(NewType: Char); override;
  556. end;
  557. var
  558. Entry_Mdx_BOF: rMdxEntry; //(RecBOF, #0);
  559. Entry_Mdx_EOF: rMdxEntry; //(RecBOF, #0);
  560. Entry_Ndx_BOF: rNdxEntry; //(0, RecBOF, #0);
  561. Entry_Ndx_EOF: rNdxEntry; //(0, RecEOF, #0);
  562. LCIDList: TLCIDList;
  563. //==========================================================
  564. // Locale support for all versions of Delphi/C++Builder
  565. function LocaleCallBack(LocaleString: PChar): Integer; stdcall;
  566. begin
  567. LCIDList.Add(Pointer(StrToInt('$'+LocaleString)));
  568. Result := 1;
  569. end;
  570. constructor TLCIDList.Create;
  571. begin
  572. inherited;
  573. end;
  574. procedure TLCIDList.Enumerate;
  575. begin
  576. Clear;
  577. EnumSystemLocales(@LocaleCallBack, LCID_SUPPORTED);
  578. end;
  579. //==========================================================
  580. //============ TIndexPage
  581. //==========================================================
  582. constructor TIndexPage.Create(Parent: TIndexFile);
  583. begin
  584. FIndexFile := Parent;
  585. GetMem(FPageBuffer, FIndexFile.RecordSize);
  586. FLowerPage := nil;
  587. Clear;
  588. end;
  589. destructor TIndexPage.Destroy;
  590. begin
  591. // no locks anymore?
  592. assert(FLockCount = 0);
  593. if (FLowerPage<>nil) then
  594. LowerPage.Free;
  595. WritePage;
  596. FreeMemAndNil(FPageBuffer);
  597. inherited Destroy;
  598. end;
  599. procedure TIndexPage.Clear;
  600. begin
  601. FillChar(PChar(FPageBuffer)^, FIndexFile.RecordSize, 0);
  602. FreeAndNil(FLowerPage);
  603. FUpperPage := nil;
  604. FPageNo := -1;
  605. FEntryNo := -1;
  606. FWeight := 1;
  607. FModified := false;
  608. FEntry := FIndexFile.EntryBof;
  609. FLowPage := 0;
  610. FHighPage := 0;
  611. FLowIndex := 0;
  612. FHighIndex := -1;
  613. FLockCount := 0;
  614. end;
  615. procedure TIndexPage.GetNewPage;
  616. begin
  617. FPageNo := FIndexFile.GetNewPageNo;
  618. end;
  619. procedure TIndexPage.Modified;
  620. begin
  621. FModified := true;
  622. end;
  623. procedure TIndexPage.LockPage;
  624. begin
  625. // already locked?
  626. if FLockCount = 0 then
  627. FIndexFile.LockPage(FPageNo, true);
  628. // increase count
  629. inc(FLockCount);
  630. end;
  631. procedure TIndexPage.UnlockPage;
  632. begin
  633. // still in domain?
  634. assert(FLockCount > 0);
  635. dec(FLockCount);
  636. // unlock?
  637. if FLockCount = 0 then
  638. begin
  639. if FIndexFile.NeedLocks then
  640. WritePage;
  641. FIndexFile.UnlockPage(FPageNo);
  642. end;
  643. end;
  644. procedure TIndexPage.LocalInsert(RecNo: Integer; Buffer: PChar; LowerPageNo: Integer);
  645. // *) assumes there is at least one entry free
  646. var
  647. source, dest: Pointer;
  648. size, lNumEntries, numKeysAvail: Integer;
  649. begin
  650. // lock page if needed; wait if not available, anyone else updating?
  651. LockPage;
  652. // check assertions
  653. lNumEntries := GetNumEntries;
  654. // if this is inner node, we can only store one less than max entries
  655. numKeysAvail := PIndexHdr(FIndexFile.IndexHeader)^.NumKeys - lNumEntries;
  656. if FLowerPage <> nil then
  657. dec(numKeysAvail);
  658. // check if free space
  659. assert(numKeysAvail > 0);
  660. // first free up some space
  661. source := FEntry;
  662. dest := GetEntry(FEntryNo + 1);
  663. size := (lNumEntries - EntryNo) * PIndexHdr(FIndexFile.IndexHeader)^.KeyRecLen;
  664. // if 'rightmost' entry, copy pageno too
  665. if (FLowerPage <> nil) or (numKeysAvail > 1) then
  666. size := size + FIndexFile.EntryHeaderSize;
  667. Move(source^, dest^, size);
  668. // one entry added
  669. Inc(FHighIndex);
  670. IncNumEntries;
  671. // lNumEntries not valid from here
  672. SetEntry(RecNo, Buffer, LowerPageNo);
  673. // done!
  674. UnlockPage;
  675. end;
  676. procedure TIndexPage.LocalDelete;
  677. function IsOnlyEntry(Page: TIndexPage): boolean;
  678. begin
  679. Result := true;
  680. repeat
  681. if Page.HighIndex > 0 then
  682. Result := false;
  683. Page := Page.UpperPage;
  684. until not Result or (Page = nil);
  685. end;
  686. var
  687. source, dest: Pointer;
  688. size, lNumEntries: Integer;
  689. begin
  690. // get num entries
  691. lNumEntries := GetNumEntries;
  692. // is this last entry? if it's not move entries after current one
  693. if EntryNo < FHighIndex then
  694. begin
  695. source := GetEntry(EntryNo + 1);
  696. dest := FEntry;
  697. size := (FHighIndex - EntryNo) * PIndexHdr(FIndexFile.IndexHeader)^.KeyRecLen;
  698. Move(source^, dest^, size);
  699. end else
  700. // no need to update when we're about to remove the only entry
  701. if (UpperPage <> nil) and (FHighIndex > FLowIndex) then
  702. begin
  703. // we are about to remove the last on this page, so update search
  704. // key data of parent
  705. EntryNo := FHighIndex - 1;
  706. UpperPage.SetEntry(0, GetKeyData, FPageNo);
  707. end;
  708. // one entry less now
  709. dec(lNumEntries);
  710. dec(FHighIndex);
  711. SetNumEntries(lNumEntries);
  712. // zero last one out to not get confused about internal or leaf pages
  713. // note: need to decrease lNumEntries and HighIndex first, otherwise
  714. // check on page key consistency will fail
  715. SetRecLowerPageNoOfEntry(FHighIndex+1, 0, 0);
  716. // update bracket indexes
  717. if FHighPage = FPageNo then
  718. dec(FHighBracket);
  719. // check if range violated
  720. if EntryNo > FHighIndex then
  721. EntryNo := FHighIndex;
  722. // check if still entries left, otherwise remove page from parent
  723. if FHighIndex = -1 then
  724. begin
  725. if UpperPage <> nil then
  726. if not IsOnlyEntry(UpperPage) then
  727. UpperPage.LocalDelete;
  728. end;
  729. // go to valid record in lowerpage
  730. if FLowerPage <> nil then
  731. SyncLowerPage;
  732. // flag modified page
  733. FModified := true;
  734. // success!
  735. end;
  736. function TIndexPage.MatchKey: Integer;
  737. // assumes Buffer <> nil
  738. var
  739. keyData: PChar;
  740. begin
  741. // get key data
  742. keyData := GetKeyData;
  743. // use locale dependant compare
  744. Result := FIndexFile.CompareKey(keyData);
  745. end;
  746. function TIndexPage.FindNearest(ARecNo: Integer): Integer;
  747. // pre:
  748. // assumes Key <> nil
  749. // assumes FLowIndex <= FHighIndex + 1
  750. // ARecNo = -2 -> search first key matching Key
  751. // ARecNo = -3 -> search first key greater than Key
  752. // ARecNo > 0 -> search key matching Key and its recno = ARecNo
  753. // post:
  754. // Result < 0 -> key,recno smaller than current entry
  755. // Result = 0 -> key,recno found, FEntryNo = found key entryno
  756. // Result > 0 -> key,recno larger than current entry
  757. var
  758. low, high, current: Integer;
  759. begin
  760. // implement binary search, keys are sorted
  761. low := FLowIndex;
  762. high := GetNumEntries;
  763. // always true: Entry(FEntryNo) = FEntry
  764. // FHighIndex >= 0 because no-entry cases in leaves have been filtered out
  765. // entry HighIndex may not be bigger than rest (in inner node)
  766. // ARecNo = -3 -> search last recno matching key
  767. // need to have: low <= high
  768. // define low - 1 = neg.inf.
  769. // define high = pos.inf
  770. // inv1: (ARecNo<>-3) -> Entry(low-1).Key < Key <= Entry(high).Key
  771. // inv2: (ARecNo =-3) -> Entry(low-1).Key <= Key < Entry(high).Key
  772. // vf: high + 1 - low
  773. while low < high do
  774. begin
  775. current := (low + high) div 2;
  776. FEntry := GetEntry(current);
  777. // calc diff
  778. Result := MatchKey;
  779. // test if we need to go lower or higher
  780. // result < 0 implies key smaller than tested entry
  781. // result = 0 implies key equal to tested entry
  782. // result > 0 implies key greater than tested entry
  783. if (Result < 0) or ((ARecNo<>-3) and (Result=0)) then
  784. high := current
  785. else
  786. low := current+1;
  787. end;
  788. // high will contain first greater-or-equal key
  789. // ARecNo <> -3 -> Entry(high).Key will contain first key that matches -> go to high
  790. // ARecNo = -3 -> Entry(high).Key will contain first key that is greater -> go to high
  791. FEntryNo := -1;
  792. EntryNo := high;
  793. // calc end result: can't inspect high if lowerpage <> nil
  794. // if this is a leaf, we need to find specific recno
  795. if (LowerPage = nil) then
  796. begin
  797. if high > FHighIndex then
  798. begin
  799. Result := 1;
  800. end else begin
  801. Result := MatchKey;
  802. // test if we need to find a specific recno
  803. // result < 0 -> current key greater -> nothing found -> don't search
  804. if (ARecNo > 0) then
  805. begin
  806. // BLS to RecNo
  807. high := FHighIndex + 1;
  808. low := FEntryNo;
  809. // inv: FLowIndex <= FEntryNo <= high <= FHighIndex + 1 /\
  810. // (Ai: FLowIndex <= i < FEntryNo: Entry(i).RecNo <> ARecNo)
  811. while FEntryNo <> high do
  812. begin
  813. // FEntryNo < high, get new entry
  814. if low <> FEntryNo then
  815. begin
  816. FEntry := GetEntry(FEntryNo);
  817. // check if entry key still ok
  818. Result := MatchKey;
  819. end;
  820. // test if out of range or found recno
  821. if (Result <> 0) or (GetRecNo = ARecNo) then
  822. high := FEntryNo
  823. else begin
  824. // default to EOF
  825. inc(FEntryNo);
  826. Result := 1;
  827. end;
  828. end;
  829. end;
  830. end;
  831. end else begin
  832. // FLowerPage <> nil -> high contains entry, can not have empty range
  833. Result := 0;
  834. end;
  835. end;
  836. procedure TIndexPage.GotoInsertEntry;
  837. // assures we really can insert here
  838. begin
  839. if FEntry = FIndexFile.EntryEof then
  840. FEntry := GetEntry(FEntryNo);
  841. end;
  842. procedure TIndexPage.SetEntry(RecNo: Integer; AKey: PChar; LowerPageNo: Integer);
  843. var
  844. keyData: PChar;
  845. {$ifdef TDBF_INDEX_CHECK}
  846. prevKeyData, curKeyData, nextKeyData: PChar;
  847. {$endif}
  848. begin
  849. // get num entries
  850. keyData := GetKeyData;
  851. // check valid entryno: we should be able to insert entries!
  852. assert((EntryNo >= 0) and (EntryNo <= FHighIndex));
  853. if (UpperPage <> nil) and (FEntryNo = FHighIndex) then
  854. UpperPage.SetEntry(0, AKey, FPageNo);
  855. { if PIndexHdr(FIndexFile.IndexHeader).KeyType = 'C' then }
  856. if AKey <> nil then
  857. Move(AKey^, keyData^, PIndexHdr(FIndexFile.IndexHeader)^.KeyLen)
  858. else
  859. PChar(keyData)^ := #0;
  860. {
  861. else
  862. if AKey <> nil then
  863. PDouble(keyData)^ := PDouble(AKey)^
  864. else
  865. PDouble(keyData)^ := 0.0;
  866. }
  867. // set entry info
  868. SetRecLowerPageNo(RecNo, LowerPageNo);
  869. // flag we modified the page
  870. FModified := true;
  871. {$ifdef TDBF_INDEX_CHECK}
  872. // check sorted entry sequence
  873. prevKeyData := GetKeyDataFromEntry(FEntryNo-1);
  874. curKeyData := GetKeyDataFromEntry(FEntryNo+0);
  875. nextKeyData := GetKeyDataFromEntry(FEntryNo+1);
  876. // check if prior entry not greater, 'rightmost' key does not have to match
  877. if (FEntryNo > 0) and ((FLowerPage = nil) or (FEntryNo < FHighIndex)) then
  878. begin
  879. if FIndexFile.CompareKeys(prevKeyData, curKeyData) > 0 then
  880. assert(false);
  881. end;
  882. // check if next entry not smaller
  883. if ((FLowerPage = nil) and (FEntryNo < FHighIndex)) or
  884. ((FLowerPage <> nil) and (FEntryNo < (FHighIndex - 1))) then
  885. begin
  886. if FIndexFile.CompareKeys(curKeyData, nextKeyData) > 0 then
  887. assert(false);
  888. end;
  889. {$endif}
  890. end;
  891. {$ifdef TDBF_UPDATE_FIRST_LAST_NODE}
  892. procedure TIndexPage.SetPrevBlock(NewBlock: Integer);
  893. begin
  894. end;
  895. {$endif}
  896. procedure TIndexPage.Split;
  897. // *) assumes this page is `nearly' full
  898. var
  899. NewPage: TIndexPage;
  900. source, dest: Pointer;
  901. paKeyData: PChar;
  902. size, oldEntryNo: Integer;
  903. splitRight, lNumEntries, numEntriesNew: Integer;
  904. saveLow, saveHigh: Integer;
  905. newRoot: Boolean;
  906. begin
  907. // assure parent exists, if not -> create & lock, else lock it
  908. newRoot := FUpperPage = nil;
  909. if newRoot then
  910. FIndexFile.AddNewLevel
  911. else
  912. FUpperPage.LockPage;
  913. // lock this page for updates
  914. LockPage;
  915. // get num entries
  916. lNumEntries := GetNumEntries;
  917. // calc split pos: split in half
  918. splitRight := lNumEntries div 2;
  919. if (FLowerPage <> nil) and (lNumEntries mod 2 = 1) then
  920. inc(splitRight);
  921. numEntriesNew := lNumEntries - splitRight;
  922. // check if place to insert has least entries
  923. if (numEntriesNew > splitRight) and (EntryNo > splitRight) then
  924. begin
  925. inc(splitRight);
  926. dec(numEntriesNew);
  927. end else if (numEntriesNew < splitRight) and (EntryNo < splitRight) then
  928. begin
  929. dec(splitRight);
  930. inc(numEntriesNew);
  931. end;
  932. // save current entryno
  933. oldEntryNo := EntryNo;
  934. // check if we need to save high / low bound
  935. if FLowPage = FPageNo then
  936. saveLow := FLowIndex
  937. else
  938. saveLow := -1;
  939. if FHighPage = FPageNo then
  940. saveHigh := FHighIndex
  941. else
  942. saveHigh := -1;
  943. // create new page
  944. NewPage := TIndexPageClass(ClassType).Create(FIndexFile);
  945. try
  946. // get page
  947. NewPage.GetNewPage;
  948. {$ifdef TDBF_UPDATE_FIRSTLAST_NODE}
  949. NewPage.SetPrevBlock(NewPage.PageNo - FIndexFile.PagesPerRecord);
  950. {$endif}
  951. // set modified
  952. FModified := true;
  953. NewPage.FModified := true;
  954. // compute source, dest
  955. dest := NewPage.GetEntry(0);
  956. source := GetEntry(splitRight);
  957. size := numEntriesNew * PIndexHdr(FIndexFile.IndexHeader)^.KeyRecLen;
  958. // if inner node, copy rightmost entry too
  959. if FLowerPage <> nil then
  960. size := size + FIndexFile.EntryHeaderSize;
  961. // copy bytes
  962. Move(source^, dest^, size);
  963. // if not inner node, clear possible 'rightmost' entry
  964. if (FLowerPage = nil) then
  965. SetRecLowerPageNoOfEntry(splitRight, 0, 0);
  966. // calc new number of entries of this page
  967. lNumEntries := lNumEntries - numEntriesNew;
  968. // if lower level, then we need adjust for new 'rightmost' node
  969. if FLowerPage <> nil then
  970. begin
  971. // right split, so we need 'new' rightmost node
  972. dec(lNumEntries);
  973. end;
  974. // store new number of nodes
  975. // new page is right page, so update parent to point to new right page
  976. NewPage.SetNumEntries(numEntriesNew);
  977. SetNumEntries(lNumEntries);
  978. // update highindex
  979. FHighIndex := lNumEntries;
  980. if FLowerPage = nil then
  981. dec(FHighIndex);
  982. // get data of last entry on this page
  983. paKeyData := GetKeyDataFromEntry(splitRight - 1);
  984. // reinsert ourself into parent
  985. // FUpperPage.RecurInsert(0, paKeyData, FPageNo);
  986. // we can do this via a localinsert now: we know there is at least one entry
  987. // free in this page and higher up
  988. FUpperPage.LocalInsert(0, paKeyData, FPageNo);
  989. // new page is right page, so update parent to point to new right page
  990. // we can't do this earlier: we will get lost in tree!
  991. FUpperPage.SetRecLowerPageNoOfEntry(FUpperPage.EntryNo+1, 0, NewPage.PageNo);
  992. // NOTE: UpperPage.LowerPage = Self <= inserted FPageNo, not NewPage.PageNo
  993. finally
  994. NewPage.Free;
  995. end;
  996. // done updating: unlock page
  997. UnlockPage;
  998. // save changes to parent
  999. FUpperPage.UnlockPage;
  1000. // unlock new root, unlock header too
  1001. FIndexFile.UnlockHeader;
  1002. // go to entry we left on
  1003. if oldEntryNo >= splitRight then
  1004. begin
  1005. // sync upperpage with right page
  1006. FUpperPage.EntryNo := FUpperPage.EntryNo + 1;
  1007. FEntryNo := oldEntryNo - splitRight;
  1008. FEntry := GetEntry(FEntryNo);
  1009. end else begin
  1010. // in left page = this page
  1011. EntryNo := oldEntryNo;
  1012. end;
  1013. // check if we have to save high / low bound
  1014. // seen the fact that FHighPage = FPageNo -> EntryNo <= FHighIndex, it can in
  1015. // theory not happen that page is advanced to right page and high bound remains
  1016. // on left page, but we won't check for that here
  1017. if saveLow >= splitRight then
  1018. begin
  1019. FLowPage := FPageNo;
  1020. FLowIndex := saveLow - splitRight;
  1021. end;
  1022. if saveHigh >= splitRight then
  1023. begin
  1024. FHighPage := FPageNo;
  1025. FHighIndex := saveHigh - splitRight;
  1026. end;
  1027. end;
  1028. procedure TIndexPage.Delete;
  1029. begin
  1030. LocalDelete;
  1031. end;
  1032. procedure TIndexPage.WritePage;
  1033. begin
  1034. // check if we modified current page
  1035. if FModified and (FPageNo > 0) then
  1036. begin
  1037. FIndexFile.WriteRecord(FPageNo, FPageBuffer);
  1038. FModified := false;
  1039. end;
  1040. end;
  1041. procedure TIndexPage.Flush;
  1042. begin
  1043. WritePage;
  1044. if FLowerPage <> nil then
  1045. FLowerPage.Flush;
  1046. end;
  1047. procedure TIndexPage.RecalcWeight;
  1048. begin
  1049. if FLowerPage <> nil then
  1050. begin
  1051. FWeight := FLowerPage.Weight * PIndexHdr(FIndexFile.IndexHeader)^.NumKeys;
  1052. end else begin
  1053. FWeight := 1;
  1054. end;
  1055. if FUpperPage <> nil then
  1056. FUpperPage.RecalcWeight;
  1057. end;
  1058. procedure TIndexPage.UpdateWeight;
  1059. begin
  1060. if FLowerPage <> nil then
  1061. FLowerPage.UpdateWeight
  1062. else
  1063. RecalcWeight;
  1064. end;
  1065. procedure TIndexPage.SetUpperPage(NewPage: TIndexPage);
  1066. begin
  1067. if FUpperPage <> NewPage then
  1068. begin
  1069. // root height changed: update weights
  1070. FUpperPage := NewPage;
  1071. UpdateWeight;
  1072. end;
  1073. end;
  1074. procedure TIndexPage.SetLowPage(NewPage: Integer);
  1075. begin
  1076. if FLowPage <> NewPage then
  1077. begin
  1078. FLowPage := NewPage;
  1079. UpdateBounds(FLowerPage <> nil);
  1080. end;
  1081. end;
  1082. procedure TIndexPage.SetHighPage(NewPage: Integer);
  1083. begin
  1084. if FHighPage <> NewPage then
  1085. begin
  1086. FHighPage := NewPage;
  1087. UpdateBounds(FLowerPage <> nil);
  1088. end;
  1089. end;
  1090. procedure TIndexPage.UpdateBounds(IsInnerNode: Boolean);
  1091. begin
  1092. // update low / high index range
  1093. if FPageNo = FLowPage then
  1094. FLowIndex := FLowBracket
  1095. else
  1096. FLowIndex := 0;
  1097. if FPageNo = FHighPage then
  1098. FHighIndex := FHighBracket
  1099. else begin
  1100. FHighIndex := GetNumEntries;
  1101. if not IsInnerNode then
  1102. dec(FHighIndex);
  1103. end;
  1104. end;
  1105. function TMdxPage.GetIsInnerNode: Boolean;
  1106. begin
  1107. Result := PMdxPage(FPageBuffer)^.NumEntries < PIndexHdr(FIndexFile.IndexHeader)^.NumKeys;
  1108. // if there is still an entry after the last one, this has to be an inner node
  1109. if Result then
  1110. Result := PMdxEntry(GetEntry(PMdxPage(FPageBuffer)^.NumEntries))^.RecBlockNo <> 0;
  1111. end;
  1112. function TNdxPage.GetIsInnerNode: Boolean;
  1113. begin
  1114. Result := PNdxEntry(GetEntry(0))^.LowerPageNo <> 0;
  1115. end;
  1116. procedure TIndexPage.SetPageNo(NewPageNo: Integer);
  1117. var
  1118. isInnerNode: Boolean;
  1119. begin
  1120. if (NewPageNo <> FPageNo) or FIndexFile.NeedLocks then
  1121. begin
  1122. // save changes
  1123. WritePage;
  1124. // no locks
  1125. assert(FLockCount = 0);
  1126. // goto new page
  1127. FPageNo := NewPageNo;
  1128. // remind ourselves we need to load new entry when page loaded
  1129. FEntryNo := -1;
  1130. if (NewPageNo > 0) and (NewPageNo <= FIndexFile.RecordCount) then
  1131. begin
  1132. // read page from disk
  1133. FIndexFile.ReadRecord(NewPageNo, FPageBuffer);
  1134. // fixup descending tree
  1135. isInnerNode := GetIsInnerNode;
  1136. // update low / high index range
  1137. UpdateBounds(isInnerNode);
  1138. // read inner node if any
  1139. if isInnerNode then
  1140. begin
  1141. if FLowerPage = nil then
  1142. begin
  1143. FLowerPage := TIndexPageClass(ClassType).Create(FIndexFile);
  1144. FLowerPage.UpperPage := Self;
  1145. end;
  1146. // read first entry, don't do this sooner, not created lowerpage yet
  1147. // don't recursively resync all lower pages
  1148. {$ifdef TDBF_INDEX_CHECK}
  1149. end else if FLowerPage <> nil then
  1150. begin
  1151. // FLowerPage.Free;
  1152. // FLowerPage := nil;
  1153. assert(false);
  1154. {$endif}
  1155. end else begin
  1156. // we don't have to check autoresync here because we're already at lowest level
  1157. EntryNo := FLowIndex;
  1158. end;
  1159. end;
  1160. end;
  1161. end;
  1162. procedure TIndexPage.SyncLowerPage;
  1163. // *) assumes FLowerPage <> nil!
  1164. begin
  1165. FLowerPage.PageNo := GetLowerPageNo;
  1166. end;
  1167. procedure TIndexPage.SetEntryNo(value: Integer);
  1168. begin
  1169. // do not bother if no change
  1170. if value <> FEntryNo then
  1171. begin
  1172. // check if out of range
  1173. if (value < FLowIndex) then
  1174. begin
  1175. if FLowerPage = nil then
  1176. FEntryNo := FLowIndex - 1;
  1177. FEntry := FIndexFile.EntryBof;
  1178. end else if value > FHighIndex then begin
  1179. FEntryNo := FHighIndex + 1;
  1180. FEntry := FIndexFile.EntryEof;
  1181. end else begin
  1182. FEntryNo := value;
  1183. FEntry := GetEntry(value);
  1184. // sync lowerpage with entry
  1185. if (FLowerPage <> nil) then
  1186. SyncLowerPage;
  1187. end;
  1188. end;
  1189. end;
  1190. function TIndexPage.PhysicalRecNo: Integer;
  1191. var
  1192. entryRec: Integer;
  1193. begin
  1194. // get num entries
  1195. entryRec := GetRecNo;
  1196. // check if in range
  1197. if (FEntryNo >= FLowIndex) and (FEntryNo <= FHighIndex) then
  1198. Result := entryRec
  1199. else
  1200. Result := -1;
  1201. end;
  1202. function TIndexPage.RecurPrev: Boolean;
  1203. begin
  1204. EntryNo := EntryNo - 1;
  1205. Result := Entry <> FIndexFile.EntryBof;
  1206. if Result then
  1207. begin
  1208. if FLowerPage <> nil then
  1209. begin
  1210. FLowerPage.RecurLast;
  1211. end;
  1212. end else begin
  1213. if FUpperPage<>nil then
  1214. begin
  1215. Result := FUpperPage.RecurPrev;
  1216. end;
  1217. end;
  1218. end;
  1219. function TIndexPage.RecurNext: Boolean;
  1220. begin
  1221. EntryNo := EntryNo + 1;
  1222. Result := Entry <> FIndexFile.EntryEof;
  1223. if Result then
  1224. begin
  1225. if FLowerPage <> nil then
  1226. begin
  1227. FLowerPage.RecurFirst;
  1228. end;
  1229. end else begin
  1230. if FUpperPage<>nil then
  1231. begin
  1232. Result := FUpperPage.RecurNext;
  1233. end;
  1234. end;
  1235. end;
  1236. procedure TIndexPage.RecurFirst;
  1237. begin
  1238. EntryNo := FLowIndex;
  1239. if (FLowerPage<>nil) then
  1240. FLowerPage.RecurFirst;
  1241. end;
  1242. procedure TIndexPage.RecurLast;
  1243. begin
  1244. EntryNo := FHighIndex;
  1245. if (FLowerPage<>nil) then
  1246. FLowerPage.RecurLast;
  1247. end;
  1248. //==============================================================================
  1249. //============ Mdx specific access routines
  1250. //==============================================================================
  1251. function TMdxPage.GetEntry(AEntryNo: Integer): Pointer;
  1252. begin
  1253. // get base + offset
  1254. Result := PChar(@PMdxPage(PageBuffer)^.FirstEntry) + (PIndexHdr(
  1255. IndexFile.IndexHeader)^.KeyRecLen * AEntryNo);
  1256. end;
  1257. function TMdxPage.GetLowerPageNo: Integer;
  1258. // *) assumes LowerPage <> nil
  1259. begin
  1260. // if LowerPage = nil then
  1261. // Result := 0
  1262. // else
  1263. Result := PMdxEntry(Entry)^.RecBlockNo;
  1264. end;
  1265. function TMdxPage.GetKeyData: PChar;
  1266. begin
  1267. Result := @PMdxEntry(Entry)^.KeyData;
  1268. end;
  1269. function TMdxPage.GetNumEntries: Integer;
  1270. begin
  1271. Result := PMdxPage(PageBuffer)^.NumEntries;
  1272. end;
  1273. function TMdxPage.GetKeyDataFromEntry(AEntry: Integer): PChar;
  1274. begin
  1275. Result := @PMdxEntry(GetEntry(AEntry))^.KeyData;
  1276. end;
  1277. function TMdxPage.GetRecNo: Integer;
  1278. begin
  1279. Result := PMdxEntry(Entry)^.RecBlockNo;
  1280. end;
  1281. procedure TMdxPage.SetNumEntries(NewNum: Integer);
  1282. begin
  1283. PMdxPage(PageBuffer)^.NumEntries := NewNum;
  1284. end;
  1285. procedure TMdxPage.IncNumEntries;
  1286. begin
  1287. Inc(PMdxPage(PageBuffer)^.NumEntries);
  1288. end;
  1289. procedure TMdxPage.SetRecLowerPageNo(NewRecNo, NewPageNo: Integer);
  1290. begin
  1291. if FLowerPage = nil then
  1292. PMdxEntry(Entry)^.RecBlockNo := NewRecNo
  1293. else
  1294. PMdxEntry(Entry)^.RecBlockNo := NewPageNo;
  1295. end;
  1296. procedure TMdxPage.SetRecLowerPageNoOfEntry(AEntry, NewRecNo, NewPageNo: Integer);
  1297. begin
  1298. if FLowerPage = nil then
  1299. PMdxEntry(GetEntry(AEntry))^.RecBlockNo := NewRecNo
  1300. else
  1301. PMdxEntry(GetEntry(AEntry))^.RecBlockNo := NewPageNo;
  1302. end;
  1303. {$ifdef TDBF_UPDATE_FIRST_LAST_NODE}
  1304. procedure TMdxPage.SetPrevBlock(NewBlock: Integer);
  1305. begin
  1306. PMdxPage(PageBuffer)^.PrevBlock := NewBlock;
  1307. end;
  1308. {$endif}
  1309. //==============================================================================
  1310. //============ Ndx specific access routines
  1311. //==============================================================================
  1312. function TNdxPage.GetEntry(AEntryNo: Integer): Pointer;
  1313. begin
  1314. // get base + offset
  1315. Result := PChar(@PNdxPage(PageBuffer)^.FirstEntry) + (PIndexHdr(FIndexFile.IndexHeader)^.KeyRecLen * AEntryNo);
  1316. end;
  1317. function TNdxPage.GetLowerPageNo: Integer;
  1318. // *) assumes LowerPage <> nil
  1319. begin
  1320. // if LowerPage = nil then
  1321. // Result := 0
  1322. // else
  1323. Result := PNdxEntry(Entry)^.LowerPageNo
  1324. end;
  1325. function TNdxPage.GetRecNo: Integer;
  1326. begin
  1327. Result := PNdxEntry(Entry)^.RecNo;
  1328. end;
  1329. function TNdxPage.GetKeyData: PChar;
  1330. begin
  1331. Result := @PNdxEntry(Entry)^.KeyData;
  1332. end;
  1333. function TNdxPage.GetKeyDataFromEntry(AEntry: Integer): PChar;
  1334. begin
  1335. Result := @PNdxEntry(GetEntry(AEntry))^.KeyData;
  1336. end;
  1337. function TNdxPage.GetNumEntries: Integer;
  1338. begin
  1339. Result := PNdxPage(PageBuffer)^.NumEntries;
  1340. end;
  1341. procedure TNdxPage.IncNumEntries;
  1342. begin
  1343. Inc(PNdxPage(PageBuffer)^.NumEntries);
  1344. end;
  1345. procedure TNdxPage.SetNumEntries(NewNum: Integer);
  1346. begin
  1347. PNdxPage(PageBuffer)^.NumEntries := NewNum;
  1348. end;
  1349. procedure TNdxPage.SetRecLowerPageNo(NewRecNo, NewPageNo: Integer);
  1350. begin
  1351. PNdxEntry(Entry)^.RecNo := NewRecNo;
  1352. PNdxEntry(Entry)^.LowerPageNo := NewPageNo;
  1353. end;
  1354. procedure TNdxPage.SetRecLowerPageNoOfEntry(AEntry, NewRecNo, NewPageNo: Integer);
  1355. begin
  1356. PNdxEntry(GetEntry(AEntry))^.RecNo := NewRecNo;
  1357. PNdxEntry(GetEntry(AEntry))^.LowerPageNo := NewPageNo;
  1358. end;
  1359. //==============================================================================
  1360. //============ MDX version 4 header access routines
  1361. //==============================================================================
  1362. function TMdx4Tag.GetHeaderPageNo: Integer;
  1363. begin
  1364. Result := PMdx4Tag(Tag)^.HeaderPageNo;
  1365. end;
  1366. function TMdx4Tag.GetTagName: string;
  1367. begin
  1368. Result := PMdx4Tag(Tag)^.TagName;
  1369. end;
  1370. function TMdx4Tag.GetKeyFormat: Byte;
  1371. begin
  1372. Result := PMdx4Tag(Tag)^.KeyFormat;
  1373. end;
  1374. function TMdx4Tag.GetForwardTag1: Byte;
  1375. begin
  1376. Result := PMdx4Tag(Tag)^.ForwardTag1;
  1377. end;
  1378. function TMdx4Tag.GetForwardTag2: Byte;
  1379. begin
  1380. Result := PMdx4Tag(Tag)^.ForwardTag2;
  1381. end;
  1382. function TMdx4Tag.GetBackwardTag: Byte;
  1383. begin
  1384. Result := PMdx4Tag(Tag)^.BackwardTag;
  1385. end;
  1386. function TMdx4Tag.GetReserved: Byte;
  1387. begin
  1388. Result := PMdx4Tag(Tag)^.Reserved;
  1389. end;
  1390. function TMdx4Tag.GetKeyType: Char;
  1391. begin
  1392. Result := PMdx4Tag(Tag)^.KeyType;
  1393. end;
  1394. procedure TMdx4Tag.SetHeaderPageNo(NewPageNo: Integer);
  1395. begin
  1396. PMdx4Tag(Tag)^.HeaderPageNo := NewPageNo;
  1397. end;
  1398. procedure TMdx4Tag.SetTagName(NewName: string);
  1399. begin
  1400. StrPLCopy(PMdx4Tag(Tag)^.TagName, NewName, 10);
  1401. PMdx4Tag(Tag)^.TagName[10] := #0;
  1402. end;
  1403. procedure TMdx4Tag.SetKeyFormat(NewFormat: Byte);
  1404. begin
  1405. PMdx4Tag(Tag)^.KeyFormat := NewFormat;
  1406. end;
  1407. procedure TMdx4Tag.SetForwardTag1(NewTag: Byte);
  1408. begin
  1409. PMdx4Tag(Tag)^.ForwardTag1 := NewTag;
  1410. end;
  1411. procedure TMdx4Tag.SetForwardTag2(NewTag: Byte);
  1412. begin
  1413. PMdx4Tag(Tag)^.ForwardTag2 := NewTag;
  1414. end;
  1415. procedure TMdx4Tag.SetBackwardTag(NewTag: Byte);
  1416. begin
  1417. PMdx4Tag(Tag)^.BackwardTag := NewTag;
  1418. end;
  1419. procedure TMdx4Tag.SetReserved(NewReserved: Byte);
  1420. begin
  1421. PMdx4Tag(Tag)^.Reserved := NewReserved;
  1422. end;
  1423. procedure TMdx4Tag.SetKeyType(NewType: Char);
  1424. begin
  1425. PMdx4Tag(Tag)^.KeyType := NewType;
  1426. end;
  1427. //==============================================================================
  1428. //============ MDX version 7 headertag access routines
  1429. //==============================================================================
  1430. function TMdx7Tag.GetHeaderPageNo: Integer;
  1431. begin
  1432. Result := PMdx7Tag(Tag)^.HeaderPageNo;
  1433. end;
  1434. function TMdx7Tag.GetTagName: string;
  1435. begin
  1436. Result := PMdx7Tag(Tag)^.TagName;
  1437. end;
  1438. function TMdx7Tag.GetKeyFormat: Byte;
  1439. begin
  1440. Result := PMdx7Tag(Tag)^.KeyFormat;
  1441. end;
  1442. function TMdx7Tag.GetForwardTag1: Byte;
  1443. begin
  1444. Result := PMdx7Tag(Tag)^.ForwardTag1;
  1445. end;
  1446. function TMdx7Tag.GetForwardTag2: Byte;
  1447. begin
  1448. Result := PMdx7Tag(Tag)^.ForwardTag2;
  1449. end;
  1450. function TMdx7Tag.GetBackwardTag: Byte;
  1451. begin
  1452. Result := PMdx7Tag(Tag)^.BackwardTag;
  1453. end;
  1454. function TMdx7Tag.GetReserved: Byte;
  1455. begin
  1456. Result := PMdx7Tag(Tag)^.Reserved;
  1457. end;
  1458. function TMdx7Tag.GetKeyType: Char;
  1459. begin
  1460. Result := PMdx7Tag(Tag)^.KeyType;
  1461. end;
  1462. procedure TMdx7Tag.SetHeaderPageNo(NewPageNo: Integer);
  1463. begin
  1464. PMdx7Tag(Tag)^.HeaderPageNo := NewPageNo;
  1465. end;
  1466. procedure TMdx7Tag.SetTagName(NewName: string);
  1467. begin
  1468. StrPLCopy(PMdx7Tag(Tag)^.TagName, NewName, 32);
  1469. PMdx7Tag(Tag)^.TagName[32] := #0;
  1470. end;
  1471. procedure TMdx7Tag.SetKeyFormat(NewFormat: Byte);
  1472. begin
  1473. PMdx7Tag(Tag)^.KeyFormat := NewFormat;
  1474. end;
  1475. procedure TMdx7Tag.SetForwardTag1(NewTag: Byte);
  1476. begin
  1477. PMdx7Tag(Tag)^.ForwardTag1 := NewTag;
  1478. end;
  1479. procedure TMdx7Tag.SetForwardTag2(NewTag: Byte);
  1480. begin
  1481. PMdx7Tag(Tag)^.ForwardTag2 := NewTag;
  1482. end;
  1483. procedure TMdx7Tag.SetBackwardTag(NewTag: Byte);
  1484. begin
  1485. PMdx7Tag(Tag)^.BackwardTag := NewTag;
  1486. end;
  1487. procedure TMdx7Tag.SetReserved(NewReserved: Byte);
  1488. begin
  1489. PMdx7Tag(Tag)^.Reserved := NewReserved;
  1490. end;
  1491. procedure TMdx7Tag.SetKeyType(NewType: Char);
  1492. begin
  1493. PMdx7Tag(Tag)^.KeyType := NewType;
  1494. end;
  1495. //==============================================================================
  1496. //============ TIndexFile
  1497. //==============================================================================
  1498. constructor TIndexFile.Create(ADbfFile: Pointer);
  1499. var
  1500. I: Integer;
  1501. begin
  1502. inherited Create;
  1503. // clear variables
  1504. FOpened := false;
  1505. FRangeActive := false;
  1506. FUpdateMode := umCurrent;
  1507. FModifyMode := mmNormal;
  1508. FTempMode := TDbfFile(ADbfFile).TempMode;
  1509. SelectIndexVars(-1);
  1510. for I := 0 to MaxIndexes - 1 do
  1511. begin
  1512. FParsers[I] := nil;
  1513. FRoots[I] := nil;
  1514. FLeaves[I] := nil;
  1515. FIndexHeaderModified[I] := false;
  1516. end;
  1517. // store pointer to `parent' dbf file
  1518. FDbfFile := ADbfFile;
  1519. end;
  1520. destructor TIndexFile.Destroy;
  1521. begin
  1522. // close file
  1523. Close;
  1524. // call ancestor
  1525. inherited Destroy;
  1526. end;
  1527. procedure TIndexFile.Open;
  1528. var
  1529. I: Integer;
  1530. ext: string;
  1531. localeError: TLocaleError;
  1532. localeSolution: TLocaleSolution;
  1533. DbfLangId: Byte;
  1534. begin
  1535. if not FOpened then
  1536. begin
  1537. // open physical file
  1538. OpenFile;
  1539. // page offsets are not related to header length
  1540. PageOffsetByHeader := false;
  1541. // we need physical page locks
  1542. VirtualLocks := false;
  1543. // not selected index expression => can't edit yet
  1544. FCanEdit := false;
  1545. FUserKey := nil;
  1546. FUserRecNo := -1;
  1547. FHeaderLocked := -1;
  1548. FHeaderPageNo := 0;
  1549. FForceClose := false;
  1550. FForceReadOnly := false;
  1551. FMdxTag := nil;
  1552. // get index type
  1553. ext := UpperCase(ExtractFileExt(FileName));
  1554. if (ext = '.MDX') then
  1555. begin
  1556. FEntryHeaderSize := 4;
  1557. FPageHeaderSize := 8;
  1558. FEntryBof := @Entry_Mdx_BOF;
  1559. FEntryEof := @Entry_Mdx_EOF;
  1560. HeaderSize := 2048;
  1561. RecordSize := 1024;
  1562. PageSize := 512;
  1563. if FileCreated then
  1564. begin
  1565. FIndexVersion := TDbfFile(FDbfFile).DbfVersion;
  1566. if FIndexVersion = xBaseIII then
  1567. FIndexVersion := xBaseIV;
  1568. end else begin
  1569. case PMdxHdr(Header)^.MdxVersion of
  1570. 3: FIndexVersion := xBaseVII;
  1571. else
  1572. FIndexVersion := xBaseIV;
  1573. end;
  1574. end;
  1575. case FIndexVersion of
  1576. xBaseVII:
  1577. begin
  1578. FMdxTag := TMdx7Tag.Create;
  1579. FTempMdxTag := TMdx7Tag.Create;
  1580. end;
  1581. else
  1582. FMdxTag := TMdx4Tag.Create;
  1583. FTempMdxTag := TMdx4Tag.Create;
  1584. end;
  1585. // get mem for all index headers..we're going to cache these
  1586. for I := 0 to MaxIndexes - 1 do
  1587. begin
  1588. GetMem(FIndexHeaders[I], RecordSize);
  1589. FillChar(FIndexHeaders[I]^, RecordSize, 0);
  1590. end;
  1591. // set pointers to first index
  1592. FIndexHeader := FIndexHeaders[0];
  1593. end else begin
  1594. // don't waste memory on another header block: we can just use
  1595. // the pagedfile one, there is only one index in this file
  1596. FIndexVersion := xBaseIII;
  1597. FEntryHeaderSize := 8;
  1598. FPageHeaderSize := 4;
  1599. FEntryBof := @Entry_Ndx_BOF;
  1600. FEntryEof := @Entry_Ndx_EOF;
  1601. HeaderSize := 512;
  1602. RecordSize := 512;
  1603. // have to read header first before we can assign following vars
  1604. FIndexHeaders[0] := Header;
  1605. FIndexHeader := Header;
  1606. // create default root
  1607. FParsers[0] := TDbfParser.Create(FDbfFile);
  1608. FRoots[0] := TNdxPage.Create(Self);
  1609. FCurrentParser := FParsers[0];
  1610. FRoot := FRoots[0];
  1611. FSelectedIndex := 0;
  1612. // parse index expression
  1613. FCurrentParser.ParseExpression(PIndexHdr(FIndexHeader)^.KeyDesc);
  1614. // set index locale
  1615. InternalLocaleID := LCID(lcidBinary);
  1616. end;
  1617. // determine how to open file
  1618. if FileCreated then
  1619. begin
  1620. FillChar(Header^, HeaderSize, 0);
  1621. Clear;
  1622. end else begin
  1623. // determine locale type
  1624. localeError := leNone;
  1625. if (FIndexVersion >= xBaseIV) then
  1626. begin
  1627. // get parent language id
  1628. DbfLangId := GetDbfLanguageId;
  1629. // no ID?
  1630. if (DbfLangId = 0) { and (TDbfFile(FDbfFile).DbfVersion = xBaseIII)} then
  1631. begin
  1632. // if dbf is version 3, no language id, if no MDX language, use binary
  1633. if PMdxHdr(Header)^.Language = 0 then
  1634. InternalLocaleID := lcidBinary
  1635. else
  1636. InternalLocaleID := LangId_To_Locale[PMdxHdr(Header)^.Language];
  1637. end else begin
  1638. // check if MDX - DBF language id's match
  1639. if (PMdxHdr(Header)^.Language = 0) or (PMdxHdr(Header)^.Language = DbfLangId) then
  1640. InternalLocaleID := LangId_To_Locale[DbfLangId]
  1641. else
  1642. localeError := leTableIndexMismatch;
  1643. end;
  1644. // don't overwrite previous error
  1645. if (FLocaleID = DbfLocale_NotFound) and (localeError = leNone) then
  1646. localeError := leUnknown;
  1647. end else begin
  1648. // dbase III always binary?
  1649. InternalLocaleID := lcidBinary;
  1650. end;
  1651. // check if selected locale is available, binary is always available...
  1652. if (localeError <> leNone) and (FLocaleID <> LCID(lcidBinary)) then
  1653. begin
  1654. if LCIDList.IndexOf(Pointer(FLocaleID)) < 0 then
  1655. localeError := leNotAvailable;
  1656. end;
  1657. // check if locale error detected
  1658. if localeError <> leNone then
  1659. begin
  1660. // provide solution, well, solution...
  1661. localeSolution := lsNotOpen;
  1662. // call error handler
  1663. if Assigned(FOnLocaleError) then
  1664. FOnLocaleError(localeError, localeSolution);
  1665. // act to solution
  1666. case localeSolution of
  1667. lsNotOpen: FForceClose := true;
  1668. lsNoEdit: FForceReadOnly := true;
  1669. else
  1670. // `trust' user knows correct locale
  1671. InternalLocaleID := LCID(localeSolution);
  1672. end;
  1673. end;
  1674. // now read info
  1675. if not ForceClose then
  1676. ReadIndexes;
  1677. end;
  1678. // default to update all
  1679. UpdateMode := umAll;
  1680. // flag open
  1681. FOpened := true;
  1682. end;
  1683. end;
  1684. procedure TIndexFile.Close;
  1685. var
  1686. I: Integer;
  1687. begin
  1688. if FOpened then
  1689. begin
  1690. // save headers
  1691. Flush;
  1692. // remove parser reference
  1693. FCurrentParser := nil;
  1694. // free roots
  1695. if FIndexVersion >= xBaseIV then
  1696. begin
  1697. for I := 0 to MaxIndexes - 1 do
  1698. begin
  1699. FreeMemAndNil(FIndexHeaders[I]);
  1700. FreeAndNil(FParsers[I]);
  1701. FreeAndNil(FRoots[I]);
  1702. end;
  1703. end else begin
  1704. FreeAndNil(FRoot);
  1705. end;
  1706. // free mem
  1707. FMdxTag.Free;
  1708. FTempMdxTag.Free;
  1709. // close physical file
  1710. CloseFile;
  1711. // not opened any more
  1712. FOpened := false;
  1713. end;
  1714. end;
  1715. procedure TIndexFile.ClearRoots;
  1716. //
  1717. // *) assumes FIndexVersion >= xBaseIV
  1718. //
  1719. var
  1720. I, prevIndex: Integer;
  1721. begin
  1722. prevIndex := FSelectedIndex;
  1723. for I := 0 to MaxIndexes - 1 do
  1724. begin
  1725. SelectIndexVars(I);
  1726. if FRoot <> nil then
  1727. begin
  1728. // clear this entry
  1729. ClearIndex;
  1730. FLeaves[I] := FRoots[I];
  1731. end;
  1732. end;
  1733. // reselect previously selected index
  1734. SelectIndexVars(prevIndex);
  1735. // deselect index
  1736. end;
  1737. procedure WriteDBFileName(Header: PMdxHdr; HdrFileName: string);
  1738. var
  1739. HdrFileExt: string;
  1740. lPos, lenFileName: integer;
  1741. begin
  1742. HdrFileName := ExtractFileName(HdrFileName);
  1743. HdrFileExt := ExtractFileExt(HdrFileName);
  1744. if Length(HdrFileExt) > 0 then
  1745. begin
  1746. lPos := System.Pos(HdrFileExt, HdrFileName);
  1747. if lPos > 0 then
  1748. SetLength(HdrFileName, lPos - 1);
  1749. end;
  1750. if Length(HdrFileName) > 15 then
  1751. SetLength(HdrFileName, 15);
  1752. lenFileName := Length(HdrFileName);
  1753. Move(PChar(HdrFileName)^, PMdxHdr(Header)^.FileName[0], lenFileName);
  1754. FillChar(PMdxHdr(Header)^.FileName[lenFileName], 15-lenFileName, 0);
  1755. end;
  1756. procedure TIndexFile.Clear;
  1757. var
  1758. year, month, day: Word;
  1759. pos, prevSelIndex: Integer;
  1760. DbfLangId: Byte;
  1761. begin
  1762. // flush cache to prevent reading corrupted data
  1763. Flush;
  1764. // completely erase index
  1765. if FIndexVersion >= xBaseIV then
  1766. begin
  1767. DecodeDate(Now, year, month, day);
  1768. if FIndexVersion = xBaseVII then
  1769. PMdxHdr(Header)^.MdxVersion := 3
  1770. else
  1771. PMdxHdr(Header)^.MdxVersion := 2;
  1772. PMdxHdr(Header)^.Year := year - 1900;
  1773. PMdxHdr(Header)^.Month := month;
  1774. PMdxHdr(Header)^.Day := day;
  1775. WriteDBFileName(PMdxHdr(Header), FileName);
  1776. PMdxHdr(Header)^.BlockSize := 2;
  1777. PMdxHdr(Header)^.BlockAdder := 1024;
  1778. PMdxHdr(Header)^.ProdFlag := 1;
  1779. PMdxHdr(Header)^.NumTags := 48;
  1780. PMdxHdr(Header)^.TagSize := 32;
  1781. // PMdxHdr(Header)^.TagsUsed := 0;
  1782. PMdxHdr(Header)^.Dummy2 := 0;
  1783. PMdxHdr(Header)^.Language := GetDbfLanguageID;
  1784. PMdxHdr(Header)^.NumPages := HeaderSize div PageSize; // = 4
  1785. TouchHeader(Header);
  1786. PMdxHdr(Header)^.TagFlag := 1;
  1787. // use locale id of parent
  1788. DbfLangId := GetDbfLanguageId;
  1789. if DbfLangId = 0 then
  1790. InternalLocaleID := lcidBinary
  1791. else
  1792. InternalLocaleID := LangID_To_Locale[DbfLangId];
  1793. // write index headers
  1794. prevSelIndex := FSelectedIndex;
  1795. for pos := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  1796. begin
  1797. SelectIndexVars(pos);
  1798. FMdxTag.HeaderPageNo := GetNewPageNo;
  1799. WriteRecord(FMdxTag.HeaderPageNo, FIndexHeader);
  1800. end;
  1801. // reselect previously selected index
  1802. SelectIndexVars(prevSelIndex);
  1803. // file header done (tags are included in file header)
  1804. WriteFileHeader;
  1805. // clear roots
  1806. ClearRoots;
  1807. // init vars
  1808. FTagSize := 32;
  1809. FTagOffset := 544;
  1810. // clear entries
  1811. RecordCount := PMdxHdr(Header)^.NumPages;
  1812. end else begin
  1813. // clear single index entry
  1814. ClearIndex;
  1815. RecordCount := PIndexHdr(FIndexHeader)^.NumPages;
  1816. end;
  1817. end;
  1818. procedure TIndexFile.ClearIndex;
  1819. var
  1820. prevHeaderLocked: Integer;
  1821. needHeaderLock: Boolean;
  1822. begin
  1823. // flush cache to prevent reading corrupted data
  1824. Flush;
  1825. // modifying header: lock page
  1826. needHeaderLock := FHeaderLocked <> 0;
  1827. prevHeaderLocked := FHeaderLocked;
  1828. if needHeaderLock then
  1829. begin
  1830. LockPage(0, true);
  1831. FHeaderLocked := 0;
  1832. end;
  1833. // initially, we have 1 page: header
  1834. PIndexHdr(FIndexHeader)^.NumPages := HeaderSize div PageSize;
  1835. // clear memory of root
  1836. FRoot.Clear;
  1837. // get new page for root
  1838. FRoot.GetNewPage;
  1839. // store new root page
  1840. PIndexHdr(FIndexHeader)^.RootPage := FRoot.PageNo;
  1841. {$ifdef TDBF_UPDATE_FIRSTLAST_NODE}
  1842. PIndexHdr(FIndexHeader)^.FirstNode := FRoot.PageNo;
  1843. {$endif}
  1844. // update leaf pointers
  1845. FLeaves[FSelectedIndex] := FRoot;
  1846. FLeaf := FRoot;
  1847. // write new header
  1848. WriteHeader;
  1849. FRoot.Modified;
  1850. FRoot.WritePage;
  1851. // done updating: unlock header
  1852. if needHeaderLock then
  1853. begin
  1854. UnlockPage(0);
  1855. FHeaderLocked := prevHeaderLocked;
  1856. end;
  1857. end;
  1858. procedure TIndexFile.CalcKeyProperties;
  1859. // given KeyLen, this func calcs KeyRecLen and NumEntries
  1860. var
  1861. remainder: Integer;
  1862. begin
  1863. // now adjust keylen to align on DWORD boundaries
  1864. PIndexHdr(FIndexHeader)^.KeyRecLen := PIndexHdr(FIndexHeader)^.KeyLen + FEntryHeaderSize;
  1865. remainder := (PIndexHdr(FIndexHeader)^.KeyRecLen) mod 4;
  1866. if (remainder > 0) then
  1867. PIndexHdr(FIndexHeader)^.KeyRecLen := PIndexHdr(FIndexHeader)^.KeyRecLen + 4 - remainder;
  1868. PIndexHdr(FIndexHeader)^.NumKeys := (RecordSize - FPageHeaderSize) div PIndexHdr(FIndexHeader)^.KeyRecLen;
  1869. end;
  1870. function TIndexFile.GetName: string;
  1871. begin
  1872. // get suitable name of index: if tag name defined use that otherwise filename
  1873. if FIndexVersion >= xBaseIV then
  1874. Result := FIndexName
  1875. else
  1876. Result := FileName;
  1877. end;
  1878. procedure TIndexFile.CreateIndex(FieldDesc, TagName: string; Options: TIndexOptions);
  1879. var
  1880. tagNo: Integer;
  1881. fieldType: Char;
  1882. TempParser: TDbfParser;
  1883. begin
  1884. // check if we have exclusive access to table
  1885. TDbfFile(FDbfFile).CheckExclusiveAccess;
  1886. // parse index expression; if it cannot be parsed, why bother making index?
  1887. TempParser := TDbfParser.Create(FDbfFile);
  1888. try
  1889. TempParser.ParseExpression(FieldDesc);
  1890. // check if result type is correct
  1891. fieldType := 'C';
  1892. case TempParser.ResultType of
  1893. etString: ; { default set above to suppress delphi warning }
  1894. etInteger, etLargeInt, etFloat: fieldType := 'N';
  1895. else
  1896. raise EDbfError.Create(STRING_INVALID_INDEX_TYPE);
  1897. end;
  1898. finally
  1899. TempParser.Free;
  1900. end;
  1901. // select empty index
  1902. if FIndexVersion >= xBaseIV then
  1903. begin
  1904. // get next entry no
  1905. tagNo := PMdxHdr(Header)^.TagsUsed;
  1906. // check if too many indexes
  1907. if tagNo = MaxIndexes then
  1908. raise EDbfError.Create(STRING_TOO_MANY_INDEXES);
  1909. // get memory for root
  1910. if FRoots[tagNo] = nil then
  1911. begin
  1912. FParsers[tagNo] := TDbfParser.Create(FDbfFile);
  1913. FRoots[tagNo] := TMdxPage.Create(Self)
  1914. end else begin
  1915. FreeAndNil(FRoots[tagNo].FLowerPage);
  1916. end;
  1917. // set leaves pointer
  1918. FLeaves[tagNo] := FRoots[tagNo];
  1919. // get pointer to index header
  1920. FIndexHeader := FIndexHeaders[tagNo];
  1921. // load root + leaf
  1922. FCurrentParser := FParsers[tagNo];
  1923. FRoot := FRoots[tagNo];
  1924. FLeaf := FLeaves[tagNo];
  1925. // create new tag
  1926. FTempMdxTag.Tag := CalcTagOffset(tagNo);
  1927. FTempMdxTag.TagName := UpperCase(TagName);
  1928. // if expression then calculate
  1929. FTempMdxTag.KeyFormat := KeyFormat_Data;
  1930. if ixExpression in Options then
  1931. FTempMdxTag.KeyFormat := KeyFormat_Expression;
  1932. // what use have these reference tags?
  1933. FTempMdxTag.ForwardTag1 := 0;
  1934. FTempMdxTag.ForwardTag2 := 0;
  1935. FTempMdxTag.BackwardTag := 0;
  1936. FTempMdxTag.Reserved := 2;
  1937. FTempMdxTag.KeyType := fieldType;
  1938. // save this part of tag, need to save before GetNewPageNo,
  1939. // it will reread header
  1940. WriteFileHeader;
  1941. // store selected index
  1942. FSelectedIndex := tagNo;
  1943. FIndexName := TagName;
  1944. // store new headerno
  1945. FHeaderPageNo := GetNewPageNo;
  1946. FTempMdxTag.HeaderPageNo := FHeaderPageNo;
  1947. // increase number of indexes active
  1948. inc(PMdxHdr(Header)^.TagsUsed);
  1949. // update updatemode
  1950. UpdateMode := umAll;
  1951. // index header updated
  1952. WriteFileHeader;
  1953. end;
  1954. // clear index
  1955. ClearIndex;
  1956. // parse expression, we know it's parseable, we've checked that
  1957. FCurrentParser.ParseExpression(FieldDesc);
  1958. // looked up index expression: now we can edit
  1959. // FIsExpression := ixExpression in Options;
  1960. FCanEdit := not FForceReadOnly;
  1961. // init key variables
  1962. PIndexHdr(FIndexHeader)^.KeyFormat := 0;
  1963. // descending
  1964. if ixDescending in Options then
  1965. PIndexHdr(FIndexHeader)^.KeyFormat := PIndexHdr(FIndexHeader)^.KeyFormat or KeyFormat_Descending;
  1966. // key type
  1967. if fieldType = 'C' then
  1968. PIndexHdr(FIndexHeader)^.KeyFormat := PIndexHdr(FIndexHeader)^.KeyFormat or KeyFormat_String;
  1969. PIndexHdr(FIndexHeader)^.KeyType := fieldType;
  1970. // uniqueness
  1971. PIndexHdr(FIndexHeader)^.Unique := Unique_None;
  1972. if ixPrimary in Options then
  1973. begin
  1974. PIndexHdr(FIndexHeader)^.KeyFormat := PIndexHdr(FIndexHeader)^.KeyFormat or KeyFormat_Distinct or KeyFormat_Unique;
  1975. PIndexHdr(FIndexHeader)^.Unique := Unique_Distinct;
  1976. end else if ixUnique in Options then
  1977. begin
  1978. PIndexHdr(FIndexHeader)^.KeyFormat := PIndexHdr(FIndexHeader)^.KeyFormat or KeyFormat_Unique;
  1979. PIndexHdr(FIndexHeader)^.Unique := Unique_Unique;
  1980. end;
  1981. // keylen is exact length of field
  1982. if fieldType = 'C' then
  1983. PIndexHdr(FIndexHeader)^.KeyLen := FCurrentParser.ResultLen
  1984. else if FIndexVersion >= xBaseIV then
  1985. PIndexHdr(FIndexHeader)^.KeyLen := 12
  1986. else
  1987. PIndexHdr(FIndexHeader)^.KeyLen := 8;
  1988. CalcKeyProperties;
  1989. // key desc
  1990. StrPLCopy(PIndexHdr(FIndexHeader)^.KeyDesc, FieldDesc, 219);
  1991. PIndexHdr(FIndexHeader)^.KeyDesc[219] := #0;
  1992. // init various
  1993. if FIndexVersion >= xBaseIV then
  1994. PIndexHdr(FIndexHeader)^.Dummy := 0 // MDX -> language driver
  1995. else
  1996. PIndexHdr(FIndexHeader)^.Dummy := $5800; // NDX -> same ???
  1997. case fieldType of
  1998. 'C':
  1999. PIndexHdr(FIndexHeader)^.sKeyType := 0;
  2000. 'D':
  2001. PIndexHdr(FIndexHeader)^.sKeyType := 1;
  2002. 'N', 'F':
  2003. if FIndexVersion >= xBaseIV then
  2004. PIndexHdr(FIndexHeader)^.sKeyType := 0
  2005. else
  2006. PIndexHdr(FIndexHeader)^.sKeyType := 1;
  2007. else
  2008. PIndexHdr(FIndexHeader)^.sKeyType := 0;
  2009. end;
  2010. PIndexHdr(FIndexHeader)^.Version := 2; // this is what DB4 writes into file
  2011. PIndexHdr(FIndexHeader)^.Dummy2 := 0;
  2012. PIndexHdr(FIndexHeader)^.Dummy3 := 0;
  2013. PIndexHdr(FIndexHeader)^.ForExist := 0; // false
  2014. PIndexHdr(FIndexHeader)^.KeyExist := 1; // true
  2015. {$ifndef TDBF_UPDATE_FIRSTLAST_NODE}
  2016. // if not defined, init to zero
  2017. PIndexHdr(FIndexHeader)^.FirstNode := 0;
  2018. PIndexHdr(FIndexHeader)^.LastNode := 0;
  2019. {$endif}
  2020. WriteHeader;
  2021. // update internal properties
  2022. UpdateIndexProperties;
  2023. // for searches / inserts / deletes
  2024. FKeyBuffer[PIndexHdr(FIndexHeader)^.KeyLen] := #0;
  2025. end;
  2026. procedure TIndexFile.ReadIndexes;
  2027. var
  2028. I: Integer;
  2029. procedure CheckHeaderIntegrity;
  2030. begin
  2031. if integer(PIndexHdr(FIndexHeader)^.NumKeys * PIndexHdr(FIndexHeader)^.KeyRecLen) > RecordSize then
  2032. begin
  2033. // adjust index header so that integrity is correct
  2034. // WARNING: we can't be sure this gives a correct result, but at
  2035. // least we won't AV (as easily). user will probably have to regenerate this index
  2036. if PIndexHdr(FIndexHeader)^.KeyLen > 100 then
  2037. PIndexHdr(FIndexHeader)^.KeyLen := 100;
  2038. CalcKeyProperties;
  2039. end;
  2040. end;
  2041. begin
  2042. // force header reread
  2043. inherited ReadHeader;
  2044. // examine all indexes
  2045. if FIndexVersion >= xBaseIV then
  2046. begin
  2047. // clear all roots
  2048. ClearRoots;
  2049. // tags are extended at beginning?
  2050. FTagSize := PMdxHdr(Header)^.TagSize;
  2051. FTagOffset := 544 + FTagSize - 32;
  2052. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  2053. begin
  2054. // read page header
  2055. FTempMdxTag.Tag := CalcTagOffset(I);
  2056. ReadRecord(FTempMdxTag.HeaderPageNo, FIndexHeaders[I]);
  2057. // select it
  2058. FIndexHeader := FIndexHeaders[I];
  2059. // create root if needed
  2060. if FRoots[I] = nil then
  2061. begin
  2062. FParsers[I] := TDbfParser.Create(FDbfFile);
  2063. FRoots[I] := TMdxPage.Create(Self);
  2064. end;
  2065. // check header integrity
  2066. CheckHeaderIntegrity;
  2067. // read tree
  2068. FRoots[I].PageNo := PIndexHdr(FIndexHeader)^.RootPage;
  2069. // go to first record
  2070. FRoots[I].RecurFirst;
  2071. // store leaf
  2072. FLeaves[I] := FRoots[I];
  2073. while FLeaves[I].LowerPage <> nil do
  2074. FLeaves[I] := FLeaves[I].LowerPage;
  2075. // parse expression
  2076. FParsers[I].ParseExpression(PIndexHdr(FIndexHeader)^.KeyDesc);
  2077. end;
  2078. end else begin
  2079. // clear root
  2080. FRoot.Clear;
  2081. // check recordsize constraint
  2082. CheckHeaderIntegrity;
  2083. // just one index: read tree
  2084. FRoot.PageNo := PIndexHdr(FIndexHeader)^.RootPage;
  2085. // go to first valid record
  2086. FRoot.RecurFirst;
  2087. // get leaf page
  2088. FLeaf := FRoot;
  2089. while FLeaf.LowerPage <> nil do
  2090. FLeaf := FLeaf.LowerPage;
  2091. // write leaf pointer to first index
  2092. FLeaves[0] := FLeaf;
  2093. // get index properties -> internal props
  2094. UpdateIndexProperties;
  2095. end;
  2096. end;
  2097. procedure TIndexFile.DeleteIndex(const AIndexName: string);
  2098. var
  2099. I, found, numTags, moveItems: Integer;
  2100. tempHeader: Pointer;
  2101. tempRoot, tempLeaf: TIndexPage;
  2102. tempParser: TDbfParser;
  2103. begin
  2104. // check if we have exclusive access to table
  2105. TDbfFile(FDbfFile).CheckExclusiveAccess;
  2106. if FIndexVersion = xBaseIII then
  2107. begin
  2108. Close;
  2109. DeleteFile;
  2110. end else if FIndexVersion >= xBaseIV then
  2111. begin
  2112. // find index
  2113. found := IndexOf(AIndexName);
  2114. if found >= 0 then
  2115. begin
  2116. // just remove this tag by copying memory over it
  2117. numTags := PMdxHdr(Header)^.TagsUsed;
  2118. moveItems := numTags - found - 1;
  2119. // anything to move?
  2120. if moveItems > 0 then
  2121. begin
  2122. // move entries after found one
  2123. Move((Header + FTagOffset + (found+1) * FTagSize)^,
  2124. (Header + FTagOffset + found * FTagSize)^, moveItems * FTagSize);
  2125. // nullify last entry
  2126. FillChar((Header + FTagOffset + numTags * FTagSize)^, FTagSize, 0);
  2127. // index headers, roots, leaves
  2128. tempHeader := FIndexHeaders[found];
  2129. tempParser := FParsers[found];
  2130. tempRoot := FRoots[found];
  2131. tempLeaf := FLeaves[found];
  2132. for I := 0 to moveItems - 1 do
  2133. begin
  2134. FIndexHeaders[found + I] := FIndexHeaders[found + I + 1];
  2135. FParsers[found + I] := FParsers[found + I + 1];
  2136. FRoots[found + I] := FRoots[found + I + 1];
  2137. FLeaves[found + I] := FLeaves[found + I + 1];
  2138. FIndexHeaderModified[found + I] := true;
  2139. end;
  2140. FIndexHeaders[found + moveItems] := tempHeader;
  2141. FParsers[found + moveItems] := tempParser;
  2142. FRoots[found + moveItems] := tempRoot;
  2143. FLeaves[found + moveItems] := tempLeaf;
  2144. FIndexHeaderModified[found + moveItems] := false; // non-existant header
  2145. end;
  2146. // one entry less left
  2147. dec(PMdxHdr(Header)^.TagsUsed);
  2148. // ---*** numTags not valid from here ***---
  2149. // file header changed
  2150. WriteFileHeader;
  2151. // repage index to free space used by deleted index
  2152. // RepageFile;
  2153. end;
  2154. end;
  2155. end;
  2156. procedure TIndexFile.TouchHeader(AHeader: Pointer);
  2157. var
  2158. year, month, day: Word;
  2159. begin
  2160. DecodeDate(Now, year, month, day);
  2161. PMdxHdr(AHeader)^.UpdYear := year - 1900;
  2162. PMdxHdr(AHeader)^.UpdMonth := month;
  2163. PMdxHdr(AHeader)^.UpdDay := day;
  2164. end;
  2165. function TIndexFile.CreateTempFile(BaseName: string): TPagedFile;
  2166. var
  2167. lModifier: Integer;
  2168. begin
  2169. // create temporary in-memory index file
  2170. lModifier := 0;
  2171. FindNextName(BaseName, BaseName, lModifier);
  2172. Result := TPagedFile.Create;
  2173. Result.FileName := BaseName;
  2174. Result.Mode := pfExclusiveCreate;
  2175. Result.AutoCreate := true;
  2176. Result.OpenFile;
  2177. Result.HeaderSize := HeaderSize;
  2178. Result.RecordSize := RecordSize;
  2179. Result.PageSize := PageSize;
  2180. Result.PageOffsetByHeader := false;
  2181. end;
  2182. procedure TIndexFile.RepageFile;
  2183. var
  2184. TempFile: TPagedFile;
  2185. TempIdxHeader: PIndexHdr;
  2186. I, newPageNo: Integer;
  2187. prevIndex: Integer;
  2188. function AllocNewPageNo: Integer;
  2189. begin
  2190. Result := newPageNo;
  2191. Inc(newPageNo, PagesPerRecord);
  2192. if FIndexVersion >= xBaseIV then
  2193. Inc(PMdxHdr(TempFile.Header)^.NumPages, PagesPerRecord);
  2194. Inc(TempIdxHeader^.NumPages, PagesPerRecord);
  2195. end;
  2196. function WriteTree(NewPage: TIndexPage): Integer;
  2197. var
  2198. J: Integer;
  2199. begin
  2200. // get us a page so that page no's are more logically ordered
  2201. Result := AllocNewPageNo;
  2202. // use postorder visiting, first do all children
  2203. if NewPage.LowerPage <> nil then
  2204. begin
  2205. for J := 0 to NewPage.HighIndex do
  2206. begin
  2207. NewPage.EntryNo := J;
  2208. WriteTree(NewPage.LowerPage);
  2209. end;
  2210. end;
  2211. // now create new page for ourselves and write
  2212. // update page pointer in parent
  2213. if NewPage.UpperPage <> nil then
  2214. begin
  2215. if FIndexVersion >= xBaseIV then
  2216. begin
  2217. PMdxEntry(NewPage.UpperPage.Entry)^.RecBlockNo := Result;
  2218. {$ifdef TDBF_UPDATE_FIRSTLAST_NODE}
  2219. // write previous node
  2220. if FRoot = NewPage then
  2221. PMdxPage(NewPage.PageBuffer)^.PrevBlock := 0
  2222. else
  2223. PMdxPage(NewPage.PageBuffer)^.PrevBlock := Result - PagesPerRecord;
  2224. {$endif}
  2225. end else begin
  2226. PNdxEntry(NewPage.UpperPage.Entry)^.LowerPageNo := Result;
  2227. end;
  2228. end;
  2229. // store page
  2230. TempFile.WriteRecord(Result, NewPage.PageBuffer);
  2231. end;
  2232. procedure CopySelectedIndex;
  2233. var
  2234. hdrPageNo: Integer;
  2235. begin
  2236. // copy current index settings
  2237. Move(FIndexHeader^, TempIdxHeader^, RecordSize);
  2238. // clear number of pages
  2239. TempIdxHeader^.NumPages := PagesPerRecord;
  2240. // allocate a page no for header
  2241. hdrPageNo := AllocNewPageNo;
  2242. // use recursive function to write all pages
  2243. TempIdxHeader^.RootPage := WriteTree(FRoot);
  2244. {$ifdef TDBF_UPDATE_FIRSTLAST_NODE}
  2245. TempIdxHeader^.FirstNode := TempIdxHeader^.RootPage;
  2246. {$endif}
  2247. // write index header now we know the root page
  2248. TempFile.WriteRecord(hdrPageNo, TempIdxHeader);
  2249. if FIndexVersion >= xBaseIV then
  2250. begin
  2251. // calculate tag offset in tempfile header
  2252. FTempMdxTag.Tag := PChar(TempFile.Header) + (PChar(CalcTagOffset(I)) - Header);
  2253. FTempMdxTag.HeaderPageNo := hdrPageNo;
  2254. end;
  2255. end;
  2256. begin
  2257. CheckExclusiveAccess;
  2258. prevIndex := FSelectedIndex;
  2259. newPageNo := HeaderSize div PageSize;
  2260. TempFile := CreateTempFile(FileName);
  2261. if FIndexVersion >= xBaseIV then
  2262. begin
  2263. // copy header
  2264. Move(Header^, TempFile.Header^, HeaderSize);
  2265. TouchHeader(TempFile.Header);
  2266. // reset header
  2267. PMdxHdr(TempFile.Header)^.NumPages := HeaderSize div PageSize;
  2268. TempFile.WriteHeader;
  2269. GetMem(TempIdxHeader, RecordSize);
  2270. // now recreate indexes to that file
  2271. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  2272. begin
  2273. // select this index
  2274. SelectIndexVars(I);
  2275. CopySelectedIndex;
  2276. end;
  2277. FreeMem(TempIdxHeader);
  2278. end else begin
  2279. // indexversion = xBaseIII
  2280. TempIdxHeader := PIndexHdr(TempFile.Header);
  2281. CopySelectedIndex;
  2282. end;
  2283. TempFile.WriteHeader;
  2284. TempFile.CloseFile;
  2285. CloseFile;
  2286. // rename temporary file if all went successfull
  2287. if not TempFile.WriteError then
  2288. begin
  2289. SysUtils.DeleteFile(FileName);
  2290. SysUtils.RenameFile(TempFile.FileName, FileName);
  2291. end;
  2292. TempFile.Free;
  2293. DisableForceCreate;
  2294. OpenFile;
  2295. ReadIndexes;
  2296. SelectIndexVars(prevIndex);
  2297. end;
  2298. procedure TIndexFile.CompactFile;
  2299. var
  2300. TempFile: TPagedFile;
  2301. TempIdxHeader: PIndexHdr;
  2302. I, newPageNo: Integer;
  2303. prevIndex: Integer;
  2304. function AllocNewPageNo: Integer;
  2305. begin
  2306. Result := newPageNo;
  2307. Inc(newPageNo, PagesPerRecord);
  2308. if FIndexVersion >= xBaseIV then
  2309. Inc(PMdxHdr(TempFile.Header)^.NumPages, PagesPerRecord);
  2310. Inc(TempIdxHeader^.NumPages, PagesPerRecord);
  2311. end;
  2312. function CreateNewPage: TIndexPage;
  2313. begin
  2314. // create new page + space
  2315. if FIndexVersion >= xBaseIV then
  2316. Result := TMdxPage.Create(Self)
  2317. else
  2318. Result := TNdxPage.Create(Self);
  2319. Result.FPageNo := AllocNewPageNo;
  2320. // set new page properties
  2321. Result.SetNumEntries(0);
  2322. end;
  2323. procedure GetNewEntry(APage: TIndexPage);
  2324. // makes a new entry available and positions current 'pos' on it
  2325. // NOTES: uses TIndexPage *very* carefully
  2326. // - may not read from self (tindexfile)
  2327. // - page.FLowerPage is assigned -> SyncLowerPage may *not* be called
  2328. // - do not set PageNo (= SetPageNo)
  2329. // - do not set EntryNo
  2330. begin
  2331. if APage.HighIndex >= PIndexHdr(FIndexHeader)^.NumKeys-1 then
  2332. begin
  2333. if APage.UpperPage = nil then
  2334. begin
  2335. // add new upperlevel to page
  2336. APage.FUpperPage := CreateNewPage;
  2337. APage.UpperPage.FLowerPage := APage;
  2338. APage.UpperPage.FEntryNo := 0;
  2339. APage.UpperPage.FEntry := EntryEof;
  2340. APage.UpperPage.GotoInsertEntry;
  2341. APage.UpperPage.LocalInsert(0, APage.Key, APage.PageNo);
  2342. // non-leaf pages need 'rightmost' key; numentries = real# - 1
  2343. APage.UpperPage.SetNumEntries(0);
  2344. end;
  2345. // page done, store
  2346. TempFile.WriteRecord(APage.FPageNo, APage.PageBuffer);
  2347. // allocate new page
  2348. APage.FPageNo := AllocNewPageNo;
  2349. // clear
  2350. APage.SetNumEntries(0);
  2351. APage.FHighIndex := -1;
  2352. APage.FLowIndex := 0;
  2353. // clear 'right-most' blockno
  2354. APage.SetRecLowerPageNoOfEntry(0, 0, 0);
  2355. // get new entry in upper page for current new apage
  2356. GetNewEntry(APage.UpperPage);
  2357. APage.UpperPage.LocalInsert(0, nil, 0);
  2358. // non-leaf pages need 'rightmost' key; numentries = real# - 1
  2359. if APage.UpperPage.EntryNo = 0 then
  2360. APage.UpperPage.SetNumEntries(0);
  2361. end;
  2362. APage.FEntryNo := APage.HighIndex+1;
  2363. APage.FEntry := EntryEof;
  2364. APage.GotoInsertEntry;
  2365. end;
  2366. procedure CopySelectedIndex;
  2367. var
  2368. APage: TIndexPage;
  2369. hdrPageNo: Integer;
  2370. begin
  2371. // copy current index settings
  2372. Move(FIndexHeader^, TempIdxHeader^, RecordSize);
  2373. // clear number of pages
  2374. TempIdxHeader^.NumPages := PagesPerRecord;
  2375. // allocate a page no for header
  2376. hdrPageNo := AllocNewPageNo;
  2377. // copy all records
  2378. APage := CreateNewPage;
  2379. FLeaf.RecurFirst;
  2380. while not (FRoot.Entry = FEntryEof) do
  2381. begin
  2382. GetNewEntry(APage);
  2383. APage.LocalInsert(FLeaf.PhysicalRecNo, FLeaf.Key, 0);
  2384. FLeaf.RecurNext;
  2385. end;
  2386. // flush remaining (partially filled) pages
  2387. repeat
  2388. TempFile.WriteRecord(APage.FPageNo, APage.PageBuffer);
  2389. if APage.UpperPage <> nil then
  2390. APage := APage.UpperPage
  2391. else break;
  2392. until false;
  2393. // copy index header + root page
  2394. TempIdxHeader^.RootPage := APage.PageNo;
  2395. {$ifdef TDBF_UPDATE_FIRSTLAST_NODE}
  2396. TempIdxHeader^.FirstNode := APage.PageNo;
  2397. {$endif}
  2398. // write index header now we know the root page
  2399. TempFile.WriteRecord(hdrPageNo, TempIdxHeader);
  2400. if FIndexVersion >= xBaseIV then
  2401. begin
  2402. // calculate tag offset in tempfile header
  2403. FTempMdxTag.Tag := PChar(TempFile.Header) + (PChar(CalcTagOffset(I)) - Header);
  2404. FTempMdxTag.HeaderPageNo := hdrPageNo;
  2405. end;
  2406. end;
  2407. begin
  2408. CheckExclusiveAccess;
  2409. prevIndex := FSelectedIndex;
  2410. newPageNo := HeaderSize div PageSize;
  2411. TempFile := CreateTempFile(FileName);
  2412. if FIndexVersion >= xBaseIV then
  2413. begin
  2414. // copy header
  2415. Move(Header^, TempFile.Header^, HeaderSize);
  2416. TouchHeader(TempFile.Header);
  2417. // reset header
  2418. PMdxHdr(TempFile.Header)^.NumPages := HeaderSize div PageSize;
  2419. TempFile.WriteHeader;
  2420. GetMem(TempIdxHeader, RecordSize);
  2421. // now recreate indexes to that file
  2422. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  2423. begin
  2424. // select this index
  2425. SelectIndexVars(I);
  2426. CopySelectedIndex;
  2427. end;
  2428. FreeMem(TempIdxHeader);
  2429. end else begin
  2430. // indexversion = xBaseIII
  2431. TempIdxHeader := PIndexHdr(TempFile.Header);
  2432. CopySelectedIndex;
  2433. end;
  2434. TempFile.WriteHeader;
  2435. TempFile.CloseFile;
  2436. CloseFile;
  2437. // rename temporary file if all went successfull
  2438. if not TempFile.WriteError then
  2439. begin
  2440. SysUtils.DeleteFile(FileName);
  2441. SysUtils.RenameFile(TempFile.FileName, FileName);
  2442. end;
  2443. TempFile.Free;
  2444. DisableForceCreate;
  2445. OpenFile;
  2446. ReadIndexes;
  2447. SelectIndexVars(prevIndex);
  2448. end;
  2449. procedure TIndexFile.PrepareRename(NewFileName: string);
  2450. begin
  2451. if FIndexVersion >= xBaseIV then
  2452. begin
  2453. WriteDBFileName(PMdxHdr(Header), NewFileName);
  2454. WriteFileHeader;
  2455. end;
  2456. end;
  2457. function TIndexFile.GetNewPageNo: Integer;
  2458. var
  2459. needLockHeader: Boolean;
  2460. begin
  2461. // update header -> lock it if not already locked
  2462. needLockHeader := FHeaderLocked <> 0;
  2463. if needLockHeader then
  2464. begin
  2465. // lock header page
  2466. LockPage(0, true);
  2467. // someone else could be inserting records at the same moment
  2468. if NeedLocks then
  2469. inherited ReadHeader;
  2470. end;
  2471. if FIndexVersion >= xBaseIV then
  2472. begin
  2473. Result := PMdxHdr(Header)^.NumPages;
  2474. PMdxHdr(Header)^.NumPages := PMdxHdr(Header)^.NumPages + PagesPerRecord;
  2475. {$ifdef TDBF_UPDATE_FIRSTLAST_NODE}
  2476. // adjust high page
  2477. PIndexHdr(FIndexHeader)^.LastNode := Result;
  2478. {$endif}
  2479. WriteFileHeader;
  2480. end else begin
  2481. Result := PIndexHdr(FIndexHeader)^.NumPages;
  2482. end;
  2483. PIndexHdr(FIndexHeader)^.NumPages := PIndexHdr(FIndexHeader)^.NumPages + PagesPerRecord;
  2484. WriteHeader;
  2485. // done updating header -> unlock if locked
  2486. if needLockHeader then
  2487. UnlockPage(0);
  2488. end;
  2489. procedure TIndexFile.Insert(RecNo: Integer; Buffer: PChar); {override;}
  2490. var
  2491. I, curSel: Integer;
  2492. begin
  2493. // check if updating all or only current
  2494. FUserRecNo := RecNo;
  2495. if (FUpdateMode = umAll) or (FSelectedIndex = -1) then
  2496. begin
  2497. // remember currently selected index
  2498. curSel := FSelectedIndex;
  2499. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  2500. begin
  2501. SelectIndexVars(I);
  2502. InsertKey(Buffer);
  2503. end;
  2504. // restore previous selected index
  2505. SelectIndexVars(curSel);
  2506. end else begin
  2507. InsertKey(Buffer);
  2508. end;
  2509. // check range, disabled by insert
  2510. ResyncRange(true);
  2511. end;
  2512. function TIndexFile.CheckKeyViolation(Buffer: PChar): Boolean;
  2513. var
  2514. I, curSel: Integer;
  2515. begin
  2516. Result := false;
  2517. FUserRecNo := -2;
  2518. if FIndexVersion = xBaseIV then
  2519. begin
  2520. curSel := FSelectedIndex;
  2521. I := 0;
  2522. while (I < PMdxHdr(Header)^.TagsUsed) and not Result do
  2523. begin
  2524. SelectIndexVars(I);
  2525. if FUniqueMode = iuDistinct then
  2526. begin
  2527. FUserKey := ExtractKeyFromBuffer(Buffer);
  2528. Result := FindKey(false) = 0;
  2529. end;
  2530. Inc(I);
  2531. end;
  2532. SelectIndexVars(curSel);
  2533. end else begin
  2534. if FUniqueMode = iuDistinct then
  2535. begin
  2536. FUserKey := ExtractKeyFromBuffer(Buffer);
  2537. Result := FindKey(false) = 0;
  2538. end;
  2539. end;
  2540. end;
  2541. function TIndexFile.PrepareKey(Buffer: PChar; ResultType: TExpressionType): PChar;
  2542. var
  2543. FloatRec: TFloatRec;
  2544. I, IntSrc, NumDecimals: Integer;
  2545. ExtValue: Extended;
  2546. BCDdigit: Byte;
  2547. {$ifdef SUPPORT_INT64}
  2548. Int64Src: Int64;
  2549. {$endif}
  2550. begin
  2551. // need to convert numeric?
  2552. Result := Buffer;
  2553. if PIndexHdr(FIndexHeader)^.KeyType in ['N', 'F'] then
  2554. begin
  2555. if FIndexVersion = xBaseIII then
  2556. begin
  2557. // DB3 -> index always 8 byte float, if original integer, convert to double
  2558. case ResultType of
  2559. etInteger:
  2560. begin
  2561. FUserNumeric := PInteger(Result)^;
  2562. Result := PChar(@FUserNumeric);
  2563. end;
  2564. {$ifdef SUPPORT_INT64}
  2565. etLargeInt:
  2566. begin
  2567. FUserNumeric := PLargeInt(Result)^;
  2568. Result := PChar(@FUserNumeric);
  2569. end;
  2570. {$endif}
  2571. end;
  2572. end else begin
  2573. // DB4 MDX
  2574. NumDecimals := 0;
  2575. case ResultType of
  2576. etInteger:
  2577. begin
  2578. IntSrc := PInteger(Result)^;
  2579. // handle zero differently: no decimals
  2580. if IntSrc <> 0 then
  2581. NumDecimals := GetStrFromInt(IntSrc, @FloatRec.Digits[0])
  2582. else
  2583. NumDecimals := 0;
  2584. FloatRec.Negative := IntSrc < 0;
  2585. end;
  2586. {$ifdef SUPPORT_INT64}
  2587. etLargeInt:
  2588. begin
  2589. Int64Src := PLargeInt(Result)^;
  2590. if Int64Src <> 0 then
  2591. NumDecimals := GetStrFromInt64(Int64Src, @FloatRec.Digits[0])
  2592. else
  2593. NumDecimals := 0;
  2594. FloatRec.Negative := Int64Src < 0;
  2595. end;
  2596. {$endif}
  2597. etFloat:
  2598. begin
  2599. ExtValue := PDouble(Result)^;
  2600. FloatToDecimal(FloatRec, ExtValue, {$ifndef FPC_VERSION}fvExtended,{$endif} 9999, 15);
  2601. if ExtValue <> 0.0 then
  2602. NumDecimals := StrLen(@FloatRec.Digits[0])
  2603. else
  2604. NumDecimals := 0;
  2605. // maximum number of decimals possible to encode in BCD is 16
  2606. if NumDecimals > 16 then
  2607. NumDecimals := 16;
  2608. end;
  2609. end;
  2610. case ResultType of
  2611. etInteger {$ifdef SUPPORT_INT64}, etLargeInt{$endif}:
  2612. begin
  2613. FloatRec.Exponent := NumDecimals;
  2614. // MDX-BCD does not count ending zeroes as `data' space length
  2615. while (NumDecimals > 0) and (FloatRec.Digits[NumDecimals-1] = '0') do
  2616. Dec(NumDecimals);
  2617. // null-terminate string
  2618. FloatRec.Digits[NumDecimals] := #0;
  2619. end;
  2620. end;
  2621. // write 'header', contains number of digits before decimal separator
  2622. FUserBCD[0] := $34 + FloatRec.Exponent;
  2623. // clear rest of BCD
  2624. FillChar(FUserBCD[1], SizeOf(FUserBCD)-1, 0);
  2625. // store number of bytes used (in number of bits + 1)
  2626. FUserBCD[1] := (((NumDecimals+1) div 2) * 8) + 1;
  2627. // where to store decimal dot position? now implicitly in first byte
  2628. // store negative sign
  2629. if FloatRec.Negative then
  2630. FUserBCD[1] := FUserBCD[1] or $80;
  2631. // convert string to BCD
  2632. I := 0;
  2633. while I < NumDecimals do
  2634. begin
  2635. // only one byte left?
  2636. if FloatRec.Digits[I+1] = #0 then
  2637. BCDdigit := 0
  2638. else
  2639. BCDdigit := Byte(FloatRec.Digits[I+1]) - Byte('0');
  2640. // pack two bytes into bcd
  2641. FUserBCD[2+(I div 2)] := ((Byte(FloatRec.Digits[I]) - Byte('0')) shl 4) or BCDdigit;
  2642. // goto next 2 bytes
  2643. Inc(I, 2);
  2644. end;
  2645. // set result pointer to BCD
  2646. Result := PChar(@FUserBCD[0]);
  2647. end;
  2648. end;
  2649. end;
  2650. function TIndexFile.ExtractKeyFromBuffer(Buffer: PChar): PChar;
  2651. begin
  2652. // execute expression to get key
  2653. Result := PrepareKey(FCurrentParser.ExtractFromBuffer(Buffer), FCurrentParser.ResultType);
  2654. end;
  2655. procedure TIndexFile.InsertKey(Buffer: PChar);
  2656. begin
  2657. // ignore deleted records
  2658. if (FModifyMode = mmNormal) and (FUniqueMode = iuDistinct) and (Buffer^ = '*') then
  2659. exit;
  2660. // check proper index and modifiability
  2661. if FCanEdit and (PIndexHdr(FIndexHeader)^.KeyLen <> 0) then
  2662. begin
  2663. // get key from buffer
  2664. FUserKey := ExtractKeyFromBuffer(Buffer);
  2665. // patch through
  2666. InsertCurrent;
  2667. end;
  2668. end;
  2669. procedure TIndexFile.InsertCurrent;
  2670. // insert in current index
  2671. // assumes: FUserKey is an OEM key
  2672. var
  2673. lSearchKey: array[0..100] of Char;
  2674. OemKey: PChar;
  2675. begin
  2676. // only insert if not recalling or mode = distinct
  2677. // modify = mmDeleteRecall /\ unique <> distinct -> key already present
  2678. if (FModifyMode <> mmDeleteRecall) or (FUniqueMode = iuDistinct) then
  2679. begin
  2680. // translate OEM key to ANSI key for searching
  2681. OemKey := FUserKey;
  2682. if KeyType = 'C' then
  2683. begin
  2684. FUserKey := @lSearchKey[0];
  2685. TranslateToANSI(OemKey, FUserKey);
  2686. end;
  2687. // temporarily remove range to find correct location of key
  2688. ResetRange;
  2689. // find this record as closely as possible
  2690. // if result = 0 then key already exists
  2691. // if unique index, then don't insert key if already present
  2692. if (FindKey(true) <> 0) or (FUniqueMode = iuNormal) then
  2693. begin
  2694. // switch to oem key
  2695. FUserKey := OemKey;
  2696. // if we found eof, write to pagebuffer
  2697. FLeaf.GotoInsertEntry;
  2698. // insert requested entry, we know there is an entry available
  2699. FLeaf.LocalInsert(FUserRecNo, FUserKey, 0);
  2700. end else begin
  2701. // key already exists -> test possible key violation
  2702. if FUniqueMode = iuDistinct then
  2703. begin
  2704. // raising -> reset modify mode
  2705. FModifyMode := mmNormal;
  2706. InsertError;
  2707. end;
  2708. end;
  2709. end;
  2710. end;
  2711. procedure TIndexFile.InsertError;
  2712. var
  2713. InfoKey: string;
  2714. begin
  2715. // prepare info for user
  2716. InfoKey := FUserKey;
  2717. SetLength(InfoKey, KeyLen);
  2718. raise EDbfError.CreateFmt(STRING_KEY_VIOLATION, [GetName, PhysicalRecNo, TrimRight(InfoKey)]);
  2719. end;
  2720. procedure TIndexFile.Delete(RecNo: Integer; Buffer: PChar);
  2721. var
  2722. I, curSel: Integer;
  2723. begin
  2724. // check if updating all or only current
  2725. FUserRecNo := RecNo;
  2726. if (FUpdateMode = umAll) or (FSelectedIndex = -1) then
  2727. begin
  2728. // remember currently selected index
  2729. curSel := FSelectedIndex;
  2730. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  2731. begin
  2732. SelectIndexVars(I);
  2733. DeleteKey(Buffer);
  2734. end;
  2735. // restore previous selected index
  2736. SelectIndexVars(curSel);
  2737. end else begin
  2738. DeleteKey(Buffer);
  2739. end;
  2740. // range may be changed
  2741. ResyncRange(true);
  2742. end;
  2743. procedure TIndexFile.DeleteKey(Buffer: PChar);
  2744. begin
  2745. if FCanEdit and (PIndexHdr(FIndexHeader)^.KeyLen <> 0) then
  2746. begin
  2747. // get key from record buffer
  2748. FUserKey := ExtractKeyFromBuffer(Buffer);
  2749. // call function
  2750. DeleteCurrent;
  2751. end;
  2752. end;
  2753. procedure TIndexFile.DeleteCurrent;
  2754. // deletes from current index
  2755. var
  2756. lSearchKey: array[0..100] of Char;
  2757. OemKey: PChar;
  2758. begin
  2759. // only delete if not delete record or mode = distinct
  2760. // modify = mmDeleteRecall /\ unique = distinct -> key needs to be deleted from index
  2761. if (FModifyMode <> mmDeleteRecall) or (FUniqueMode = iuDistinct) then
  2762. begin
  2763. // prevent "confined" view of index while deleting
  2764. ResetRange;
  2765. // search correct entry to delete
  2766. if FLeaf.PhysicalRecNo <> FUserRecNo then
  2767. begin
  2768. // translate OEM key to ANSI key for searching
  2769. OemKey := FUserKey;
  2770. if KeyType = 'C' then
  2771. begin
  2772. FUserKey := @lSearchKey[0];
  2773. TranslateToANSI(OemKey, FUserKey);
  2774. end;
  2775. FindKey(false);
  2776. end;
  2777. // delete selected entry
  2778. FLeaf.Delete;
  2779. end;
  2780. end;
  2781. procedure TIndexFile.Update(RecNo: Integer; PrevBuffer, NewBuffer: PChar);
  2782. var
  2783. I, curSel: Integer;
  2784. begin
  2785. // check if updating all or only current
  2786. FUserRecNo := RecNo;
  2787. if (FUpdateMode = umAll) or (FSelectedIndex = -1) then
  2788. begin
  2789. // remember currently selected index
  2790. curSel := FSelectedIndex;
  2791. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  2792. begin
  2793. SelectIndexVars(I);
  2794. UpdateCurrent(PrevBuffer, NewBuffer);
  2795. end;
  2796. // restore previous selected index
  2797. SelectIndexVars(curSel);
  2798. end else begin
  2799. UpdateCurrent(PrevBuffer, NewBuffer);
  2800. end;
  2801. // check range, disabled by delete/insert
  2802. if (FRoot.LowPage = 0) and (FRoot.HighPage = 0) then
  2803. ResyncRange(true);
  2804. end;
  2805. procedure TIndexFile.UpdateCurrent(PrevBuffer, NewBuffer: PChar);
  2806. var
  2807. TempBuffer: array [0..100] of Char;
  2808. begin
  2809. if FCanEdit and (PIndexHdr(FIndexHeader)^.KeyLen <> 0) then
  2810. begin
  2811. // get key from newbuffer
  2812. FUserKey := ExtractKeyFromBuffer(NewBuffer);
  2813. Move(FUserKey^, TempBuffer, PIndexHdr(FIndexHeader)^.KeyLen);
  2814. // get key from prevbuffer
  2815. FUserKey := ExtractKeyFromBuffer(PrevBuffer);
  2816. // compare to see if anything changed
  2817. if CompareKeys(@TempBuffer[0], FUserKey) <> 0 then
  2818. begin
  2819. // first set userkey to key to delete
  2820. // FUserKey = KeyFrom(PrevBuffer)
  2821. DeleteCurrent;
  2822. // now set userkey to key to insert
  2823. FUserKey := @TempBuffer[0];
  2824. InsertCurrent;
  2825. end;
  2826. end;
  2827. end;
  2828. procedure TIndexFile.AddNewLevel;
  2829. var
  2830. lNewPage: TIndexPage;
  2831. pKeyData: PChar;
  2832. begin
  2833. // create new page + space
  2834. if FIndexVersion >= xBaseIV then
  2835. lNewPage := TMdxPage.Create(Self)
  2836. else
  2837. lNewPage := TNdxPage.Create(Self);
  2838. lNewPage.GetNewPage;
  2839. // lock this new page; will be unlocked by caller
  2840. lNewPage.LockPage;
  2841. // lock index header; will be unlocked by caller
  2842. LockPage(FHeaderPageNo, true);
  2843. FHeaderLocked := FHeaderPageNo;
  2844. // modify header
  2845. PIndexHdr(FIndexHeader)^.RootPage := lNewPage.PageNo;
  2846. // set new page properties
  2847. lNewPage.SetNumEntries(0);
  2848. lNewPage.EntryNo := 0;
  2849. lNewPage.GotoInsertEntry;
  2850. {$ifdef TDBF_UPDATE_FIRST_LAST_NODE}
  2851. lNewPage.SetPrevBlock(lNewPage.PageNo - PagesPerRecord);
  2852. {$endif}
  2853. pKeyData := FRoot.GetKeyDataFromEntry(0);
  2854. lNewPage.FLowerPage := FRoot;
  2855. lNewPage.FHighIndex := 0;
  2856. lNewPage.SetEntry(0, pKeyData, FRoot.PageNo);
  2857. // update root pointer
  2858. FRoot.UpperPage := lNewPage;
  2859. FRoots[FSelectedIndex] := lNewPage;
  2860. FRoot := lNewPage;
  2861. // write new header
  2862. WriteRecord(FHeaderPageNo, FIndexHeader);
  2863. end;
  2864. procedure TIndexFile.UnlockHeader;
  2865. begin
  2866. if FHeaderLocked <> -1 then
  2867. begin
  2868. UnlockPage(FHeaderLocked);
  2869. FHeaderLocked := -1;
  2870. end;
  2871. end;
  2872. procedure TIndexFile.ResyncRoot;
  2873. begin
  2874. if FIndexVersion >= xBaseIV then
  2875. begin
  2876. // read header page
  2877. inherited ReadRecord(FHeaderPageNo, FIndexHeader);
  2878. end else
  2879. inherited ReadHeader;
  2880. // reread tree
  2881. FRoot.PageNo := PIndexHdr(FIndexHeader)^.RootPage;
  2882. end;
  2883. function TIndexFile.SearchKey(Key: PChar; SearchType: TSearchKeyType): Boolean;
  2884. var
  2885. findres, currRecNo: Integer;
  2886. begin
  2887. // save current position
  2888. currRecNo := SequentialRecNo;
  2889. // search, these are always from the root: no need for first
  2890. findres := Find(-2, Key);
  2891. // test result
  2892. case SearchType of
  2893. stEqual:
  2894. Result := findres = 0;
  2895. stGreaterEqual:
  2896. Result := findres <= 0;
  2897. stGreater:
  2898. begin
  2899. if findres = 0 then
  2900. begin
  2901. // find next record that is greater
  2902. // NOTE: MatchKey assumes key to search for is already specified
  2903. // in FUserKey, it is because we have called Find
  2904. repeat
  2905. Result := WalkNext;
  2906. until not Result or (MatchKey(Key) <> 0);
  2907. end else
  2908. Result := findres < 0;
  2909. end;
  2910. else
  2911. Result := false;
  2912. end;
  2913. // search failed -> restore previous position
  2914. if not Result then
  2915. SequentialRecNo := currRecNo;
  2916. end;
  2917. function TIndexFile.Find(RecNo: Integer; Buffer: PChar): Integer;
  2918. begin
  2919. // execute find
  2920. FUserRecNo := RecNo;
  2921. FUserKey := Buffer;
  2922. Result := FindKey(false);
  2923. end;
  2924. function TIndexFile.FindKey(AInsert: boolean): Integer;
  2925. //
  2926. // if you set Insert = true, you need to re-enable range after insert!!
  2927. //
  2928. var
  2929. TempPage, NextPage: TIndexPage;
  2930. numEntries, numKeysAvail, done, searchRecNo: Integer;
  2931. begin
  2932. // reread index header (to discover whether root page changed)
  2933. if NeedLocks then
  2934. ResyncRoot;
  2935. // if distinct or unique index -> every entry only occurs once ->
  2936. // does not matter which recno we search -> search recno = -2 ->
  2937. // extra info = recno
  2938. if (FUniqueMode = iuNormal) then
  2939. begin
  2940. // if inserting, search last entry matching key
  2941. if AInsert then
  2942. searchRecNo := -3
  2943. else
  2944. searchRecNo := FUserRecNo
  2945. end else begin
  2946. searchRecNo := -2;
  2947. end;
  2948. // start from root
  2949. TempPage := FRoot;
  2950. repeat
  2951. // find key
  2952. done := 0;
  2953. Result := TempPage.FindNearest(searchRecNo);
  2954. if TempPage.LowerPage = nil then
  2955. begin
  2956. // if key greater than last, try next leaf
  2957. if (Result > 0) and (searchRecNo > 0) then
  2958. begin
  2959. // find first parent in tree so we can advance to next item
  2960. NextPage := TempPage;
  2961. repeat
  2962. NextPage := NextPage.UpperPage;
  2963. until (NextPage = nil) or (NextPage.EntryNo < NextPage.HighIndex);
  2964. // found page?
  2965. if NextPage <> nil then
  2966. begin
  2967. // go to parent
  2968. TempPage := NextPage;
  2969. TempPage.EntryNo := TempPage.EntryNo + 1;
  2970. // resync rest of tree
  2971. TempPage.LowerPage.RecurFirst;
  2972. // go to lower page to continue search
  2973. TempPage := TempPage.LowerPage;
  2974. // check if still more lowerpages
  2975. if TempPage.LowerPage <> nil then
  2976. begin
  2977. // flag we need to traverse down further
  2978. done := 2;
  2979. end else begin
  2980. // this is next child, we don't know if found
  2981. done := 1;
  2982. end;
  2983. end;
  2984. end;
  2985. end else begin
  2986. // need to traverse lower down
  2987. done := 2;
  2988. end;
  2989. // check if we need to split page
  2990. // done = 1 -> not found entry on insert path yet
  2991. if AInsert and (done <> 1) then
  2992. begin
  2993. // now we are on our path to destination where entry is to be inserted
  2994. // check if this page is full, then split it
  2995. numEntries := TempPage.NumEntries;
  2996. // if this is inner node, we can only store one less than max entries
  2997. numKeysAvail := PIndexHdr(FIndexHeader)^.NumKeys - numEntries;
  2998. if TempPage.LowerPage <> nil then
  2999. dec(numKeysAvail);
  3000. // too few available -> split
  3001. if numKeysAvail = 0 then
  3002. TempPage.Split;
  3003. end;
  3004. // do we need to go lower down?
  3005. if done = 2 then
  3006. TempPage := TempPage.LowerPage;
  3007. until done = 0;
  3008. end;
  3009. function TIndexFile.MatchKey(UserKey: PChar): Integer;
  3010. begin
  3011. // BOF and EOF always false
  3012. if FLeaf.Entry = FEntryBof then
  3013. Result := 1
  3014. else
  3015. if FLeaf.Entry = FEntryEof then
  3016. Result := -1
  3017. else begin
  3018. FUserKey := UserKey;
  3019. Result := FLeaf.MatchKey;
  3020. end;
  3021. end;
  3022. procedure TIndexFile.SetRange(LowRange, HighRange: PChar);
  3023. begin
  3024. Move(LowRange^, FLowBuffer[0], KeyLen);
  3025. Move(HighRange^, FHighBuffer[0], KeyLen);
  3026. FRangeActive := true;
  3027. ResyncRange(true);
  3028. end;
  3029. procedure TIndexFile.RecordDeleted(RecNo: Integer; Buffer: PChar);
  3030. begin
  3031. // are we distinct -> then delete record from index
  3032. FModifyMode := mmDeleteRecall;
  3033. Delete(RecNo, Buffer);
  3034. FModifyMode := mmNormal;
  3035. end;
  3036. procedure TIndexFile.RecordRecalled(RecNo: Integer; Buffer: PChar);
  3037. begin
  3038. // are we distinct -> then reinsert record in index
  3039. FModifyMode := mmDeleteRecall;
  3040. Insert(RecNo, Buffer);
  3041. FModifyMode := mmNormal;
  3042. end;
  3043. procedure TIndexFile.SetLocaleID(const NewID: LCID);
  3044. {$ifdef WIN32}
  3045. var
  3046. InfoStr: array[0..7] of Char;
  3047. {$endif}
  3048. begin
  3049. FLocaleID := NewID;
  3050. if NewID = lcidBinary then
  3051. begin
  3052. // no conversion on binary sort order
  3053. FLocaleCP := FCodePage;
  3054. end else begin
  3055. // get default ansi codepage for comparestring
  3056. {$ifdef WIN32}
  3057. GetLocaleInfo(NewID, LOCALE_IDEFAULTANSICODEPAGE, InfoStr, 8);
  3058. FLocaleCP := StrToIntDef(InfoStr, GetACP);
  3059. {$else}
  3060. FLocaleCP := GetACP;
  3061. {$endif}
  3062. end;
  3063. end;
  3064. procedure TIndexFile.SetPhysicalRecNo(RecNo: Integer);
  3065. begin
  3066. // check if already at specified recno
  3067. if FLeaf.PhysicalRecNo = RecNo then
  3068. exit;
  3069. // check record actually exists
  3070. if TDbfFile(FDbfFile).IsRecordPresent(RecNo) then
  3071. begin
  3072. // read buffer of this RecNo
  3073. TDbfFile(FDbfFile).ReadRecord(RecNo, TDbfFile(FDbfFile).PrevBuffer);
  3074. // extract key
  3075. FUserKey := ExtractKeyFromBuffer(TDbfFile(FDbfFile).PrevBuffer);
  3076. // translate to a search key
  3077. if KeyType = 'C' then
  3078. TranslateToANSI(FUserKey, FUserKey);
  3079. // find this key
  3080. FUserRecNo := RecNo;
  3081. FindKey(false);
  3082. end;
  3083. end;
  3084. procedure TIndexFile.SetUpdateMode(NewMode: TIndexUpdateMode);
  3085. begin
  3086. // if there is only one index, don't waste time and just set single
  3087. if (FIndexVersion = xBaseIII) or (PMdxHdr(Header)^.TagsUsed <= 1) then
  3088. FUpdateMode := umCurrent
  3089. else
  3090. FUpdateMode := NewMode;
  3091. end;
  3092. procedure TIndexFile.WalkFirst;
  3093. begin
  3094. // search first node
  3095. FRoot.RecurFirst;
  3096. // out of index - BOF
  3097. FLeaf.EntryNo := FLeaf.EntryNo - 1;
  3098. end;
  3099. procedure TIndexFile.WalkLast;
  3100. begin
  3101. // search last node
  3102. FRoot.RecurLast;
  3103. // out of index - EOF
  3104. // we need to skip two entries to go out-of-bound
  3105. FLeaf.EntryNo := FLeaf.EntryNo + 2;
  3106. end;
  3107. procedure TIndexFile.First;
  3108. begin
  3109. // resync tree
  3110. Resync(false);
  3111. WalkFirst;
  3112. end;
  3113. procedure TIndexFile.Last;
  3114. begin
  3115. // resync tree
  3116. Resync(false);
  3117. WalkLast;
  3118. end;
  3119. procedure TIndexFile.ResyncRange(KeepPosition: boolean);
  3120. var
  3121. Result: Boolean;
  3122. currRecNo: integer;
  3123. begin
  3124. if not FRangeActive then
  3125. exit;
  3126. // disable current range if any
  3127. // init to 0 to suppress delphi warning
  3128. currRecNo := 0;
  3129. if KeepPosition then
  3130. currRecNo := SequentialRecNo;
  3131. ResetRange;
  3132. // search lower bound
  3133. Result := SearchKey(FLowBuffer, stGreaterEqual);
  3134. if not Result then
  3135. begin
  3136. // not found? -> make empty range
  3137. WalkLast;
  3138. end;
  3139. // set lower bound
  3140. SetBracketLow;
  3141. // search upper bound
  3142. Result := SearchKey(FHighBuffer, stGreater);
  3143. // if result true, then need to get previous item <=>
  3144. // last of equal/lower than key
  3145. if Result then
  3146. begin
  3147. Result := WalkPrev;
  3148. if not Result then
  3149. begin
  3150. // cannot go prev -> empty range
  3151. WalkFirst;
  3152. end;
  3153. end else begin
  3154. // not found -> EOF found, go EOF, then to last record
  3155. WalkLast;
  3156. WalkPrev;
  3157. end;
  3158. // set upper bound
  3159. SetBracketHigh;
  3160. if KeepPosition then
  3161. SequentialRecNo := currRecNo;
  3162. end;
  3163. procedure TIndexFile.Resync(Relative: boolean);
  3164. begin
  3165. if NeedLocks then
  3166. begin
  3167. if not Relative then
  3168. begin
  3169. ResyncRoot;
  3170. ResyncRange(false);
  3171. end else begin
  3172. // resyncing tree implies resyncing range
  3173. ResyncTree;
  3174. end;
  3175. end;
  3176. end;
  3177. procedure TIndexFile.ResyncTree;
  3178. var
  3179. action, recno: integer;
  3180. begin
  3181. // if at BOF or EOF, then we need to resync by first or last
  3182. // remember where the cursor was
  3183. // init to 0 to suppress delphi warning
  3184. recno := 0;
  3185. if FLeaf.Entry = FEntryBof then
  3186. begin
  3187. action := 0;
  3188. end else if FLeaf.Entry = FEntryEof then begin
  3189. action := 1;
  3190. end else begin
  3191. // read current key into buffer
  3192. Move(FLeaf.Key^, FKeyBuffer, PIndexHdr(FIndexHeader)^.KeyLen);
  3193. // translate to searchable key
  3194. if KeyType = 'C' then
  3195. TranslateToANSI(FKeyBuffer, FKeyBuffer);
  3196. recno := FLeaf.PhysicalRecNo;
  3197. action := 2;
  3198. end;
  3199. // we now know cursor position, resync possible range
  3200. ResyncRange(false);
  3201. // go to cursor position
  3202. case action of
  3203. 0: WalkFirst;
  3204. 1: WalkLast;
  3205. 2:
  3206. begin
  3207. // search current in-mem key on disk
  3208. if (Find(recno, FKeyBuffer) <> 0) then
  3209. begin
  3210. // houston, we've got a problem!
  3211. // our `current' record has gone. we need to find it
  3212. // find it by using physical recno
  3213. PhysicalRecNo := recno;
  3214. end;
  3215. end;
  3216. end;
  3217. end;
  3218. function TIndexFile.WalkPrev: boolean;
  3219. var
  3220. curRecNo: Integer;
  3221. begin
  3222. // save current recno, find different next!
  3223. curRecNo := FLeaf.PhysicalRecNo;
  3224. repeat
  3225. // return false if we are at first entry
  3226. Result := FLeaf.RecurPrev;
  3227. until not Result or (curRecNo <> FLeaf.PhysicalRecNo);
  3228. end;
  3229. function TIndexFile.WalkNext: boolean;
  3230. var
  3231. curRecNo: Integer;
  3232. begin
  3233. // save current recno, find different prev!
  3234. curRecNo := FLeaf.PhysicalRecNo;
  3235. repeat
  3236. // return false if we are at last entry
  3237. Result := FLeaf.RecurNext;
  3238. until not Result or (curRecNo <> FLeaf.PhysicalRecNo);
  3239. end;
  3240. function TIndexFile.Prev: Boolean;
  3241. begin
  3242. // resync in-mem tree with tree on disk
  3243. Resync(true);
  3244. Result := WalkPrev;
  3245. end;
  3246. function TIndexFile.Next: Boolean;
  3247. begin
  3248. // resync in-mem tree with tree on disk
  3249. Resync(true);
  3250. Result := WalkNext;
  3251. end;
  3252. function TIndexFile.GetKeyLen: Integer;
  3253. begin
  3254. Result := PIndexHdr(FIndexHeader)^.KeyLen;
  3255. end;
  3256. function TIndexFile.GetKeyType: Char;
  3257. begin
  3258. Result := PIndexHdr(FIndexHeader)^.KeyType;
  3259. end;
  3260. function TIndexFile.GetPhysicalRecNo: Integer;
  3261. begin
  3262. Result := FLeaf.PhysicalRecNo;
  3263. end;
  3264. function TIndexFile.GetSequentialRecordCount: Integer;
  3265. begin
  3266. Result := FRoot.Weight * (FRoot.HighIndex + 1);
  3267. end;
  3268. function TIndexFile.GetSequentialRecNo: Integer;
  3269. var
  3270. TempPage: TIndexPage;
  3271. begin
  3272. // check if at BOF or EOF, special values
  3273. if FLeaf.EntryNo < FLeaf.LowIndex then begin
  3274. Result := RecBOF;
  3275. end else if FLeaf.EntryNo > FLeaf.HighIndex then begin
  3276. Result := RecEOF;
  3277. end else begin
  3278. // first record is record 1
  3279. Result := 1;
  3280. TempPage := FRoot;
  3281. repeat
  3282. inc(Result, TempPage.EntryNo * TempPage.Weight);
  3283. TempPage := TempPage.LowerPage;
  3284. until TempPage = nil;
  3285. end;
  3286. end;
  3287. procedure TIndexFile.SetSequentialRecNo(RecNo: Integer);
  3288. var
  3289. TempPage: TIndexPage;
  3290. gotoEntry: Integer;
  3291. begin
  3292. // use our weighting system to quickly go to a seq recno
  3293. // recno starts at 1, entries at zero
  3294. Dec(RecNo);
  3295. TempPage := FRoot;
  3296. repeat
  3297. // don't div by zero
  3298. assert(TempPage.Weight > 0);
  3299. gotoEntry := RecNo div TempPage.Weight;
  3300. RecNo := RecNo mod TempPage.Weight;
  3301. // do we have this much entries?
  3302. if (TempPage.HighIndex < gotoEntry) then
  3303. begin
  3304. // goto next entry in upper page if not
  3305. // if recurnext fails, we have come at the end of the index
  3306. if (TempPage.UpperPage <> nil) and TempPage.UpperPage.RecurNext then
  3307. begin
  3308. // lower recno to get because we skipped an entry
  3309. TempPage.EntryNo := TempPage.LowIndex;
  3310. RecNo := 0;
  3311. end else begin
  3312. // this can only happen if too big RecNo was entered, go to last
  3313. TempPage.RecurLast;
  3314. // terminate immediately
  3315. TempPage := FLeaf;
  3316. end;
  3317. end else begin
  3318. TempPage.EntryNo := gotoEntry;
  3319. end;
  3320. // get lower node
  3321. TempPage := TempPage.LowerPage;
  3322. until TempPage = nil;
  3323. end;
  3324. procedure TIndexFile.SetBracketLow;
  3325. var
  3326. TempPage: TIndexPage;
  3327. begin
  3328. // set current record as lower bound
  3329. TempPage := FRoot;
  3330. repeat
  3331. TempPage.LowBracket := TempPage.EntryNo;
  3332. TempPage.LowPage := TempPage.PageNo;
  3333. TempPage := TempPage.LowerPage;
  3334. until TempPage = nil;
  3335. end;
  3336. procedure TIndexFile.SetBracketHigh;
  3337. var
  3338. TempPage: TIndexPage;
  3339. begin
  3340. // set current record as lower bound
  3341. TempPage := FRoot;
  3342. repeat
  3343. TempPage.HighBracket := TempPage.EntryNo;
  3344. TempPage.HighPage := TempPage.PageNo;
  3345. TempPage := TempPage.LowerPage;
  3346. until TempPage = nil;
  3347. end;
  3348. procedure TIndexFile.CancelRange;
  3349. begin
  3350. FRangeActive := false;
  3351. ResetRange;
  3352. end;
  3353. procedure TIndexFile.ResetRange;
  3354. var
  3355. TempPage: TIndexPage;
  3356. begin
  3357. // disable lower + upper bound
  3358. TempPage := FRoot;
  3359. repeat
  3360. // set a page the index should never reach
  3361. TempPage.LowPage := 0;
  3362. TempPage.HighPage := 0;
  3363. TempPage := TempPage.LowerPage;
  3364. until TempPage = nil;
  3365. end;
  3366. function MemComp(P1, P2: Pointer; const Length: Integer): Integer;
  3367. var
  3368. I: Integer;
  3369. begin
  3370. for I := 0 to Length - 1 do
  3371. begin
  3372. // still equal?
  3373. if PByte(P1)^ <> PByte(P2)^ then
  3374. begin
  3375. Result := Integer(PByte(P1)^) - Integer(PByte(P2)^);
  3376. exit;
  3377. end;
  3378. // go to next byte
  3379. Inc(PChar(P1));
  3380. Inc(PChar(P2));
  3381. end;
  3382. // memory equal
  3383. Result := 0;
  3384. end;
  3385. function TIndexFile.CompareKeys(Key1, Key2: PChar): Integer;
  3386. begin
  3387. // call compare routine
  3388. Result := FCompareKeys(Key1, Key2);
  3389. // if descending then reverse order
  3390. if FIsDescending then
  3391. Result := -Result;
  3392. end;
  3393. function TIndexFile.CompareKeysNumericNDX(Key1, Key2: PChar): Integer;
  3394. var
  3395. v1,v2: Double;
  3396. begin
  3397. v1 := PDouble(Key1)^;
  3398. v2 := PDouble(Key2)^;
  3399. if v1 > v2 then Result := 1
  3400. else if v1 < v2 then Result := -1
  3401. else Result := 0;
  3402. end;
  3403. function TIndexFile.CompareKeysNumericMDX(Key1, Key2: PChar): Integer;
  3404. var
  3405. neg1, neg2: Boolean;
  3406. begin
  3407. // first byte - $34 contains dot position
  3408. neg1 := (Byte(Key1[1]) and $80) <> 0;
  3409. neg2 := (Byte(Key2[1]) and $80) <> 0;
  3410. // check if both negative or both positive
  3411. if neg1 = neg2 then
  3412. begin
  3413. // check alignment
  3414. if Key1[0] = Key2[0] then
  3415. begin
  3416. // no alignment needed -> have same alignment
  3417. Result := MemComp(Key1+2, Key2+2, 10-2);
  3418. end else begin
  3419. // greater 10-power implies bigger number except for zero
  3420. if (Byte(Key1[0]) = $01) and (Byte(Key1[1]) = $34) then
  3421. Result := -1
  3422. else
  3423. if (Byte(Key2[0]) = $01) and (Byte(Key2[1]) = $34) then
  3424. Result := 1
  3425. else
  3426. Result := Byte(Key1[0]) - Byte(Key2[0]);
  3427. end;
  3428. // negate result if both negative
  3429. if neg1 and neg2 then
  3430. Result := -Result;
  3431. end else if neg1 {-> not neg2} then
  3432. Result := -1
  3433. else { not neg1 and neg2 }
  3434. Result := 1;
  3435. end;
  3436. function TIndexFile.CompareKeysString(Key1, Key2: PChar): Integer;
  3437. var
  3438. Key1T, Key2T: array [0..100] of Char;
  3439. FromCP, ToCP: Integer;
  3440. begin
  3441. if FLocaleID = LCID(lcidBinary) then
  3442. begin
  3443. Result := StrLComp(Key1, Key2, KeyLen)
  3444. end else begin
  3445. FromCP := FCodePage;
  3446. ToCP := FLocaleCP;
  3447. TranslateString(FromCP, ToCP, Key1, Key1T, KeyLen);
  3448. TranslateString(FromCP, ToCP, Key2, Key2T, KeyLen);
  3449. Result := CompareString(FLocaleID, 0, Key1T, KeyLen, Key2T, KeyLen);
  3450. if Result > 0 then
  3451. Dec(Result, 2);
  3452. end
  3453. end;
  3454. function TIndexFile.CompareKey(Key: PChar): Integer;
  3455. begin
  3456. // call compare routine
  3457. Result := FCompareKey(Key);
  3458. // if descending then reverse order
  3459. if FIsDescending then
  3460. Result := -Result;
  3461. end;
  3462. function TIndexFile.CompareKeyNumericNDX(Key: PChar): Integer;
  3463. begin
  3464. Result := CompareKeysNumericNDX(FUserKey, Key);
  3465. end;
  3466. function TIndexFile.CompareKeyNumericMDX(Key: PChar): Integer;
  3467. begin
  3468. Result := CompareKeysNumericMDX(FUserKey, Key);
  3469. end;
  3470. procedure TIndexFile.TranslateToANSI(Src, Dest: PChar);
  3471. begin
  3472. { FromCP = FCodePage; }
  3473. { ToCP = FLocaleCP; }
  3474. TranslateString(FCodePage, FLocaleCP, Src, Dest, KeyLen);
  3475. end;
  3476. function TIndexFile.CompareKeyString(Key: PChar): Integer;
  3477. var
  3478. KeyT: array [0..100] of Char;
  3479. begin
  3480. if FLocaleID = LCID(lcidBinary) then
  3481. begin
  3482. Result := StrLComp(FUserKey, Key, KeyLen)
  3483. end else begin
  3484. TranslateToANSI(Key, KeyT);
  3485. Result := CompareString(FLocaleID, 0, FUserKey, KeyLen, KeyT, KeyLen);
  3486. if Result > 0 then
  3487. Dec(Result, 2);
  3488. end
  3489. end;
  3490. function TIndexFile.IndexOf(const AIndexName: string): Integer;
  3491. // *) assumes FIndexVersion >= xBaseIV
  3492. var
  3493. I: Integer;
  3494. begin
  3495. // get index of this index :-)
  3496. Result := -1;
  3497. I := 0;
  3498. while (I < PMdxHdr(Header)^.TagsUsed) and (Result < 0) do
  3499. begin
  3500. FTempMdxTag.Tag := CalcTagOffset(I);
  3501. if AnsiCompareText(AIndexName, FTempMdxTag.TagName) = 0 then
  3502. Result := I;
  3503. inc(I);
  3504. end;
  3505. end;
  3506. procedure TIndexFile.SetIndexName(const AIndexName: string);
  3507. var
  3508. found: Integer;
  3509. begin
  3510. // we can only select a different index if we are MDX
  3511. if FIndexVersion >= xBaseIV then
  3512. begin
  3513. // find index
  3514. found := IndexOf(AIndexName);
  3515. end else
  3516. found := 0;
  3517. // we can now select by index
  3518. if found >= 0 then
  3519. SelectIndexVars(found);
  3520. end;
  3521. function TIndexFile.CalcTagOffset(AIndex: Integer): Pointer;
  3522. begin
  3523. Result := PChar(Header) + FTagOffset + AIndex * FTagSize;
  3524. end;
  3525. procedure TIndexFile.SelectIndexVars(AIndex: Integer);
  3526. // *) assumes index is in range
  3527. begin
  3528. if AIndex >= 0 then
  3529. begin
  3530. // get pointer to index header
  3531. FIndexHeader := FIndexHeaders[AIndex];
  3532. // load root + leaf
  3533. FCurrentParser := FParsers[AIndex];
  3534. FRoot := FRoots[AIndex];
  3535. FLeaf := FLeaves[AIndex];
  3536. // if xBaseIV then we need to store where pageno of current header
  3537. if FIndexVersion >= xBaseIV then
  3538. begin
  3539. FMdxTag.Tag := CalcTagOffset(AIndex);
  3540. FIndexName := FMdxTag.TagName;
  3541. FHeaderPageNo := FMdxTag.HeaderPageNo;
  3542. // does dBase actually use this flag?
  3543. // FIsExpression := FMdxTag.KeyFormat = KeyFormat_Expression;
  3544. end else begin
  3545. // how does dBase III store whether it is expression?
  3546. // FIsExpression := true;
  3547. end;
  3548. // retrieve properties
  3549. UpdateIndexProperties;
  3550. end else begin
  3551. // not a valid index
  3552. FIndexName := EmptyStr;
  3553. end;
  3554. // store selected index
  3555. FSelectedIndex := AIndex;
  3556. FCanEdit := not FForceReadOnly;
  3557. end;
  3558. procedure TIndexFile.UpdateIndexProperties;
  3559. begin
  3560. // get properties
  3561. FIsDescending := (PIndexHdr(FIndexHeader)^.KeyFormat and KeyFormat_Descending) <> 0;
  3562. FUniqueMode := iuNormal;
  3563. if (PIndexHdr(FIndexHeader)^.KeyFormat and KeyFormat_Unique) <> 0 then
  3564. FUniqueMode := iuUnique;
  3565. if (PIndexHdr(FIndexHeader)^.KeyFormat and KeyFormat_Distinct) <> 0 then
  3566. FUniqueMode := iuDistinct;
  3567. // select key compare routine
  3568. if PIndexHdr(FIndexHeader)^.KeyType = 'C' then
  3569. begin
  3570. FCompareKeys := CompareKeysString;
  3571. FCompareKey := CompareKeyString;
  3572. end else
  3573. if FIndexVersion >= xBaseIV then
  3574. begin
  3575. FCompareKeys := CompareKeysNumericMDX;
  3576. FCompareKey := CompareKeyNumericMDX;
  3577. end else begin
  3578. FCompareKeys := CompareKeysNumericNDX;
  3579. FCompareKey := CompareKeyNumericNDX;
  3580. end;
  3581. end;
  3582. procedure TIndexFile.Flush;
  3583. var
  3584. I: Integer;
  3585. begin
  3586. // save changes to pages
  3587. if FIndexVersion >= xBaseIV then
  3588. begin
  3589. for I := 0 to MaxIndexes - 1 do
  3590. begin
  3591. if FIndexHeaderModified[I] then
  3592. WriteIndexHeader(I);
  3593. if FRoots[I] <> nil then
  3594. FRoots[I].Flush
  3595. end;
  3596. end else begin
  3597. if FRoot <> nil then
  3598. FRoot.Flush;
  3599. end;
  3600. // save changes to header
  3601. FlushHeader;
  3602. inherited;
  3603. end;
  3604. (*
  3605. function TIndexFile.GetIndexCount: Integer;
  3606. begin
  3607. if FIndexVersion = xBaseIII then
  3608. Result := 1
  3609. else
  3610. if FIndexVersion = xBaseIV then
  3611. Result := PMdxHdr(Header).TagsUsed;
  3612. else
  3613. Result := 0;
  3614. end;
  3615. *)
  3616. procedure TIndexFile.GetIndexNames(const AList: TStrings);
  3617. var
  3618. I: Integer;
  3619. begin
  3620. // only applicable to MDX files
  3621. if FIndexVersion >= xBaseIV then
  3622. begin
  3623. for I := 0 to PMdxHdr(Header)^.TagsUsed - 1 do
  3624. begin
  3625. FTempMdxTag.Tag := CalcTagOffset(I);
  3626. AList.AddObject(FTempMdxTag.TagName, Self);
  3627. end;
  3628. end;
  3629. end;
  3630. procedure TIndexFile.GetIndexInfo(const AIndexName: string; IndexDef: TDbfIndexDef);
  3631. var
  3632. SaveIndexName: string;
  3633. begin
  3634. // remember current index
  3635. SaveIndexName := IndexName;
  3636. // select index
  3637. IndexName := AIndexName;
  3638. // copy properties
  3639. IndexDef.IndexFile := AIndexName;
  3640. IndexDef.Expression := PIndexHdr(FIndexHeader)^.KeyDesc;
  3641. IndexDef.Options := [];
  3642. IndexDef.Temporary := true;
  3643. if FIsDescending then
  3644. IndexDef.Options := IndexDef.Options + [ixDescending];
  3645. IndexDef.Options := IndexDef.Options + [ixExpression];
  3646. case FUniqueMode of
  3647. iuUnique: IndexDef.Options := IndexDef.Options + [ixUnique];
  3648. iuDistinct: IndexDef.Options := IndexDef.Options + [ixPrimary];
  3649. end;
  3650. // reselect previous index
  3651. IndexName := SaveIndexName;
  3652. end;
  3653. function TIndexFile.GetExpression: string;
  3654. begin
  3655. if FCurrentParser <> nil then
  3656. Result := FCurrentParser.Expression
  3657. else
  3658. Result := EmptyStr;
  3659. end;
  3660. function TIndexFile.GetDbfLanguageId: Byte;
  3661. begin
  3662. // check if parent DBF version 7, get language id
  3663. if (TDbfFile(FDbfFile).DbfVersion = xBaseVII) then
  3664. begin
  3665. // get language id of parent dbf
  3666. Result := GetLangId_From_LangName(TDbfFile(FDbfFile).LanguageStr);
  3667. end else begin
  3668. // dBase IV has language id in header
  3669. Result := TDbfFile(FDbfFile).LanguageID;
  3670. end;
  3671. end;
  3672. procedure TIndexFile.WriteHeader; {override;}
  3673. begin
  3674. // if NDX, then this means file header
  3675. if FIndexVersion >= xBaseIV then
  3676. if NeedLocks then
  3677. WriteIndexHeader(FSelectedIndex)
  3678. else
  3679. FIndexHeaderModified[FSelectedIndex] := true
  3680. else
  3681. WriteFileHeader;
  3682. end;
  3683. procedure TIndexFile.WriteFileHeader;
  3684. begin
  3685. inherited WriteHeader;
  3686. end;
  3687. procedure TIndexFile.WriteIndexHeader(AIndex: Integer);
  3688. begin
  3689. FTempMdxTag.Tag := CalcTagOffset(AIndex);
  3690. WriteRecord(FTempMdxTag.HeaderPageNo, FIndexHeaders[AIndex]);
  3691. FIndexHeaderModified[AIndex] := false;
  3692. end;
  3693. //==========================================================
  3694. //============ TDbfIndexDef
  3695. //==========================================================
  3696. constructor TDbfIndexDef.Create(ACollection: TCollection); {override;}
  3697. begin
  3698. inherited Create(ACollection);
  3699. FTemporary := false;
  3700. end;
  3701. destructor TDbfIndexDef.Destroy; {override;}
  3702. begin
  3703. inherited Destroy;
  3704. end;
  3705. procedure TDbfIndexDef.Assign(Source: TPersistent);
  3706. begin
  3707. // we can't do anything with it if not a TDbfIndexDef
  3708. if Source is TDbfIndexDef then
  3709. begin
  3710. FIndexName := TDbfIndexDef(Source).IndexFile;
  3711. FExpression := TDbfIndexDef(Source).Expression;
  3712. FOptions := TDbfIndexDef(Source).Options;
  3713. end else
  3714. inherited;
  3715. end;
  3716. procedure TDbfIndexDef.SetIndexName(NewName: string);
  3717. begin
  3718. FIndexName := AnsiUpperCase(Trim(NewName));
  3719. end;
  3720. procedure TDbfIndexDef.SetExpression(NewField: string);
  3721. begin
  3722. FExpression := AnsiUpperCase(Trim(NewField));
  3723. end;
  3724. initialization
  3725. {
  3726. Entry_Mdx_BOF.RecBlockNo := RecBOF;
  3727. Entry_Mdx_BOF.KeyData := #0;
  3728. Entry_Mdx_EOF.RecBlockNo := RecEOF;
  3729. Entry_Mdx_EOF.KeyData := #0;
  3730. Entry_Ndx_BOF.LowerPageNo := 0;
  3731. Entry_Ndx_BOF.RecNo := RecBOF;
  3732. Entry_Ndx_BOF.KeyData := #0;
  3733. Entry_Ndx_EOF.LowerPageNo := 0;
  3734. Entry_Ndx_EOF.RecNo := RecEOF;
  3735. Entry_Ndx_EOF.KeyData := #0;
  3736. }
  3737. LCIDList := TLCIDList.Create;
  3738. LCIDList.Enumerate;
  3739. finalization
  3740. LCIDList.Free;
  3741. end.