dbf.pas 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895
  1. unit dbf;
  2. {===============================================================================
  3. || TDbf Component || http://tdbf.netfirms.com ||
  4. ===============================================================================}
  5. interface
  6. uses
  7. {$ifdef fpc}
  8. SysUtils, Classes, db;
  9. {$else}
  10. Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  11. Db, DsgnIntf, ExptIntf;
  12. {$endif}
  13. // If you got a compilation error here or asking for dsgntf.pas, then just add
  14. // this file in your project:
  15. // dsgnintf.pas in 'C:\Program Files\Borland\Delphi5\Source\Toolsapi\dsgnintf.pas'
  16. const
  17. _MAJOR_VERSION = 3;
  18. _MINOR_VERSION = 007;
  19. {$ifdef VER100} // Delphi 3
  20. {$define DELPHI_3}
  21. {$endif}
  22. {$ifdef VER110} // CBuilder 3
  23. {$define DELPHI_3}
  24. {$endif}
  25. {$ifdef unix}
  26. DirSeparator = '/';
  27. {$else}
  28. DirSeparator = '\';
  29. {$endif}
  30. //====================================================================
  31. // Delphi is a bit to permissive for me, I mean protected doesn't work within
  32. // one unit. So i decided that convention:
  33. // private member begins by '_'
  34. // It's forbidden to access any '_something' except from the class where it
  35. // is defined. To check that, I just have to look for '._' anywhere in the code.
  36. //====================================================================
  37. type
  38. //====================================================================
  39. //=== Common exceptions and constants
  40. //====================================================================
  41. EBinaryDataSetError = class (Exception);
  42. EFieldToLongError = class (Exception);
  43. xBaseVersion = (xBaseIII,xBaseIV,xBaseV);
  44. //====================================================================
  45. //=== Utility classes
  46. //====================================================================
  47. TPagedFile = class(TObject)
  48. protected
  49. Stream : TStream;
  50. HeaderSize : Integer;
  51. RecordSize : Integer;
  52. _cntuse:integer;
  53. _Filename:string;
  54. public
  55. constructor Create(const FileName: string; Mode: Word);
  56. destructor Destroy; override;
  57. procedure Release;
  58. function CalcRecordCount:Integer;
  59. procedure _Seek(page:Integer);
  60. procedure ReadRecord(IntRecNum:Integer;Buffer:Pointer);
  61. procedure WriteRecord(IntRecNum:Integer;Buffer:Pointer);
  62. end;
  63. //====================================================================
  64. //=== Dbf support (first part)
  65. //====================================================================
  66. rDbfHdr = record
  67. VerDBF : byte; // 0
  68. Year : byte; // 1
  69. Month : byte; // 2
  70. Day : byte; // 3
  71. RecordCount : Integer; // 4-7
  72. FullHdrSize : word; // 8-9
  73. RecordSize : word; // 10-11
  74. Dummy1 : Word; // 12-13
  75. IncTrans : byte; // 14
  76. Encrypt : byte; // 15
  77. Dummy2 : Integer; // 16-19
  78. Dummy3 : array[20..27] of byte; // 20-27
  79. MDXFlag : char; // 28
  80. Language : char; // 29
  81. dummy4 : word; // 30-31
  82. end;
  83. //====================================================================
  84. TMyFieldInfo = class
  85. public
  86. FieldName:string;
  87. Size:Integer;
  88. Prec:Integer;
  89. Offset:Integer;
  90. end;
  91. //====================================================================
  92. TDbfFile = class(TPagedFile)
  93. protected
  94. _RecordBufferSize:integer;
  95. _DataHdr : rDbfHdr;
  96. _DbfVersion : xBaseVersion;
  97. _MyFieldInfos: TList;
  98. public
  99. constructor Create(const FileName: string; Mode: Word);
  100. destructor Destroy; override;
  101. function RecordCount:integer;
  102. procedure CreateFieldDefs(FieldDefs:TFieldDefs);
  103. procedure ClearMyFieldInfos;
  104. procedure DbfFile_CreateTable(FieldDefs:TFieldDefs);
  105. procedure DbfFile_PackTable;
  106. function GetFieldInfo(FieldName:string):TMyFieldInfo;
  107. function GetFieldData(Column:Integer;DataType:TFieldType; Src,Dst: Pointer): Boolean;
  108. procedure SetFieldData(Column:integer;DataType:TFieldType; Src,Dst: Pointer);
  109. procedure WriteHeader;
  110. end;
  111. //====================================================================
  112. //=== Index support
  113. //====================================================================
  114. TIndex = class;
  115. //====================================================================
  116. rNdxHdr = record
  117. startpage : Integer; // 0..3
  118. nbPage : Integer; // 4..7
  119. keyformat: Char; //8
  120. keytype : char; //9
  121. dummy : Word; // 10..11
  122. keylen : Word; // 12..13
  123. nbkey : Word; // 14..15
  124. skeytype : Word; // 16..17
  125. keyreclen : Word; // 18..19
  126. dummy2 : Word; // 20..21
  127. dummy3 : Byte; // 22
  128. Unique : Byte; // 23
  129. KeyDesc : array[0..255] of char; // 24...
  130. end;
  131. rMdxTag = record
  132. pageno : Integer; // 0..3
  133. tagname : array [0..11] of char; // 4..14
  134. keyformat : byte; // 15
  135. forwardTag1 : char; // 16
  136. forwardTag2 : byte; // 17
  137. backwardTag : byte; // 18
  138. dummy : byte; // 19
  139. keytype : byte; // 20
  140. end;
  141. NdxKeyType = (N,C);
  142. PNdxPage = ^rNdxPage;
  143. rNdxPage = record
  144. NbEntries : longint; // 0..3 lower page
  145. Entries : ARRAY [0..507] OF char;
  146. end;
  147. PNdxentry = ^rNdxentry;
  148. rNdxentry = record
  149. _LowerPage : longint; // 0..3 lower page
  150. RecNo : Longint; // 4..7 recno
  151. case NdxKeyType of
  152. N: ( NKey: double);
  153. C: ( CKey: array [0..503] of char);
  154. end;
  155. //====================================================================
  156. rMdxHdr = record
  157. MdxHdr : byte; // 0
  158. Year : byte; // 1
  159. Month : byte; // 2
  160. Day : byte; // 3
  161. FileName : array[0..15] of char; // 4..19 of byte
  162. BlockSize : word; // 20 21
  163. BlockAdder : word; // 22 23
  164. IndexFlag : byte; // 24
  165. NoTag : byte; // 25
  166. TagSize : byte; // 26
  167. Dummy1 : byte; // 27
  168. TagUsed : word; // 28..29
  169. Dummy2 : word; // 30..31
  170. NbPage : Integer; // 32..35
  171. FreePage : Integer; // 36..39
  172. BlockFree : Integer; // 40..43
  173. UpdYear : byte; // 44
  174. UpdMonth : byte; // 45
  175. UpdDay : byte; // 46
  176. end;
  177. //====================================================================
  178. TIndexFile = class(TPagedFile)
  179. protected
  180. _IndexVersion : xBaseVersion;
  181. _MdxHdr : rMdxHdr;
  182. public
  183. constructor Create(const FileName: string; Mode: Word);
  184. destructor Destroy; override;
  185. end;
  186. //====================================================================
  187. PIndexPosInfo = ^TIndexPage;
  188. TIndexPage = class
  189. protected
  190. _Index : TIndex;
  191. _PageNo : Integer;
  192. _EntryNo : Integer;
  193. Entry : PNdxentry;
  194. _LowerLevel : TIndexPage;
  195. _UpperLevel : TIndexPage;
  196. _PageBuff:rNdxPage;
  197. procedure LocalFirst;
  198. procedure LocalLast;
  199. function LocalPrev:boolean;
  200. function LocalNext:boolean;
  201. function LastEntryNo:integer;
  202. function LocalInsert(Recno:Integer; Buffer:PChar; LowerPage:integer):boolean;
  203. function LocalDelete:boolean;
  204. function GetPEntry(EntryNo:integer):PNdxEntry;
  205. procedure First;
  206. procedure Last;
  207. function Prev:boolean;
  208. function Next:boolean;
  209. procedure Write;
  210. procedure AddNewLevel;
  211. public
  212. constructor Create(Parent:TIndex);
  213. destructor Destroy; override;
  214. procedure SetPageNo(page:Integer);
  215. procedure SetEntryNo(entryno:Integer);
  216. procedure WritePage(Page:integer);
  217. function FindNearest(Recno:integer; Key:PChar):integer;
  218. function Insert(Recno:integer; Buffer:pchar; LowerPage:integer):boolean;
  219. procedure SetEntry(Recno:integer; key:pchar; LowerPage:integer);
  220. function Delete:boolean;
  221. function LowerLevel : TIndexPage;
  222. end;
  223. //====================================================================
  224. TIndex = class(TObject)
  225. protected
  226. _IndexFile:TIndexFile;
  227. _NdxHdr:rNdxHdr;
  228. _Root:TIndexPage;
  229. _TagPosition:Integer;
  230. _FieldPos : integer;
  231. _FieldLen : integer;
  232. _NbLevel : integer;
  233. _RootPage: integer;
  234. function Pos:TIndexPage;
  235. public
  236. IndexRecNo:integer;
  237. function Prev:boolean;
  238. function Next:boolean;
  239. procedure First;
  240. procedure Last;
  241. function Find(Recno:integer; Buffer:PChar; var pPos:TIndexPage):integer;
  242. procedure Insert(Recno:integer; Buffer:PChar);
  243. function Delete:boolean;
  244. procedure GotoKey(Recno:integer; Buffer:PChar);
  245. procedure Update(Recno: integer; PrevBuffer,NewBuffer: PChar);
  246. // procedure ResyncInd;
  247. function GetRealRecNo: Integer;
  248. constructor Create(Parent:TIndexFile; RootPage:integer;CreateIt:boolean);
  249. procedure InitFieldDef(dbfFile:TDbfFile;FieldDesc:string);
  250. destructor Destroy; override;
  251. // optionnal
  252. function GuessRecordCount: Integer;
  253. function GuessRecNo: Integer;
  254. end;
  255. //====================================================================
  256. //=== Memo and binary fields support
  257. //====================================================================
  258. rDbtHdr = record
  259. NextBlock:Longint;
  260. Dummy : array [4..7] of byte;
  261. _dbfFile : array [0..7] of Byte; //8..15
  262. bVer : Byte; //16
  263. Dummy2 : array [17..19] of byte;
  264. BlockLen: Word;
  265. end;
  266. //====================================================================
  267. TDbtFile = class(TPagedFile)
  268. protected
  269. _DbtVersion:xBaseVersion;
  270. _MemoHdr:rDbtHdr;
  271. public
  272. constructor Create(const FileName: string; Mode: Word; Ver:xBaseVersion);
  273. procedure ReadMemo(recno:Integer;Dst:TStream);
  274. procedure WriteMemo(var MemoRecno:Integer;ReadSize:Integer;Src:TStream);
  275. end;
  276. //====================================================================
  277. TMyBlobFile = class(TMemoryStream)
  278. public
  279. Mode: TBlobStreamMode;
  280. Field:TField;
  281. MemoRecno:Integer;
  282. ReadSize:Integer;
  283. constructor Create(ModeVal:TBlobStreamMode; FieldVal:TField);
  284. destructor destroy; override;
  285. end;
  286. //====================================================================
  287. //=== Dbf support 2
  288. //====================================================================
  289. rFieldHdrIII = record
  290. FieldName : array[0..10] of char;
  291. FieldType : char; // 11
  292. Dummy : array[12..15] of byte;
  293. FieldSize : byte; // 16
  294. FieldPrecision : byte; //17
  295. dummy2 : array[18..31] of byte;
  296. end;
  297. //====================================================================
  298. rFieldHdrV = record
  299. FieldName : array[0..10] of char;
  300. Dummy0 : array[11..31] of byte;
  301. FieldType : char; // 32
  302. FieldSize : byte; // 33
  303. FieldPrecision : byte; //34
  304. dummy2 : array[35..47] of byte;
  305. end;
  306. //====================================================================
  307. PBookMarkData = ^rBookMarkData;
  308. rBookmarkData = record
  309. RecNo:longint;
  310. end;
  311. //====================================================================
  312. rBeforeRecord = record
  313. BookmarkData: rBookmarkData;
  314. BookmarkFlag: TBookmarkFlag;
  315. //... record come here
  316. end;
  317. //====================================================================
  318. pDbfRecord = ^rDbfRecord;
  319. rDbfRecord = record
  320. BookmarkData: rBookmarkData;
  321. BookmarkFlag: TBookmarkFlag;
  322. DeletedFlag : char;
  323. Fields : array[0..4000] of char;
  324. end;
  325. //====================================================================
  326. PRecInfo = ^TRecInfo;
  327. TRecInfo = record
  328. Bookmark: Longint;
  329. IdxBookmark: Longint;
  330. BookmarkFlag: TBookmarkFlag;
  331. end;
  332. //====================================================================
  333. pRecordHdr = ^tRecordHdr;
  334. tRecordHdr = record
  335. DeletedFlag : char;
  336. end;
  337. // and at LEAST the most useful class : TDbf
  338. //====================================================================
  339. TDbf = class(TDataSet)
  340. private
  341. _ShowDeleted:boolean;
  342. _TableName: string; // table path and file name
  343. _RunTimePath: string; // table path and file name
  344. _DesignTimePath: string; // table path and file name
  345. _ReadOnly : Boolean;
  346. _FilterBuffer:pchar;
  347. _PrevBuffer:pchar;
  348. _IndexFiles:TStrings;
  349. protected
  350. function _FullRecordSize:integer;
  351. function _FilterRecord(Buffer: PChar): Boolean;
  352. procedure _OpenFiles(CreateIt:boolean);
  353. procedure _CloseFiles;
  354. procedure _ResyncIndexes(Buffer: PChar);
  355. function _GetIndexName: string;
  356. procedure _SetIndexName(const Value: string);
  357. function _GetIndex(filename:string):TIndex;
  358. function _GetPath:string;
  359. function _ComponentInfo:string;
  360. public
  361. { my own methods and properties}
  362. { most looks like ttable functions but they are not tdataset related
  363. I use the same syntax to facilitate the conversion between bde and tdbf }
  364. easyfilter:string;
  365. procedure CreateTable; //(FieldDefs:TFieldDefs);
  366. procedure DeleteIndex(const AName: string);
  367. property IndexName: string read _GetIndexName write _SetIndexName;
  368. {$ifdef DELPHI_3}
  369. procedure AddIndex(const IndexName, Fields: String; Options: TIndexOptions);
  370. {$else}
  371. {$ifndef FPC}
  372. procedure AddIndex(const IndexName, Fields: String; Options: TIndexOptions; const DescFields: String='');
  373. {$else}
  374. procedure AddIndex(const AnIndexName, IndexFields: String; Options: TIndexOptions);
  375. procedure AddIndex(const AnIndexName, IndexFields: String; Options: TIndexOptions; const DescFields: String);
  376. {$endif}
  377. {$endif}
  378. procedure CloseIndexFile(const IndexFileName: string);
  379. procedure OpenIndexFile(AnIndexName:string);
  380. procedure PackTable;
  381. public
  382. { abstract methods }
  383. function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override; {virtual abstract}
  384. {virtual methods (mostly optionnal) }
  385. function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override; {virtual}
  386. {$ifdef DELPHI_3}
  387. procedure Translate(Src, Dest: PChar; ToOem: Boolean); override; {virtual}
  388. {$else}
  389. function Translate(Src, Dest: PChar; ToOem: Boolean): Integer; override; {virtual}
  390. {$endif}
  391. procedure ClearCalcFields(Buffer : PChar); override;
  392. protected
  393. { abstract methods }
  394. function AllocRecordBuffer: PChar; override; {virtual abstract}
  395. procedure FreeRecordBuffer(var Buffer: PChar); override; {virtual abstract}
  396. procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override; {virtual abstract}
  397. function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override; {virtual abstract}
  398. function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; {virtual abstract}
  399. function GetRecordSize: Word; override; {virtual abstract}
  400. procedure InternalAddRecord(Buffer: Pointer; DoAppend: Boolean); override; {virtual abstract}
  401. procedure InternalClose; override; {virtual abstract}
  402. procedure InternalDelete; override; {virtual abstract}
  403. procedure InternalFirst; override; {virtual abstract}
  404. procedure InternalGotoBookmark(ABookmark: Pointer); override; {virtual abstract}
  405. procedure InternalHandleException; override; {virtual abstract}
  406. procedure InternalInitFieldDefs; override; {virtual abstract}
  407. procedure InternalInitRecord(Buffer: PChar); override; {virtual abstract}
  408. procedure InternalLast; override; {virtual abstract}
  409. procedure InternalOpen; override; {virtual abstract}
  410. procedure InternalPost; override; {virtual abstract}
  411. procedure InternalSetToRecord(Buffer: PChar); override; {virtual abstract}
  412. function IsCursorOpen: Boolean; override; {virtual abstract}
  413. procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override; {virtual abstract}
  414. procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override; {virtual abstract}
  415. procedure SetFieldData(Field: TField; Buffer: Pointer); override; {virtual abstract}
  416. {virtual methods (mostly optionnal) }
  417. function GetRecordCount: Integer; override; {virtual}
  418. function GetRecNo: Integer; override; {virtual}
  419. procedure SetRecNo(Value: Integer); override; {virual}
  420. public
  421. constructor Create(AOwner: TComponent); override;
  422. destructor Destroy; override;
  423. published
  424. property ComponentInfo: string read _ComponentInfo;
  425. property TableName: string read _TableName write _TableName;
  426. property RunTimePath: string read _RunTimePath write _RunTimePath;
  427. property DesignTimePath: string read _DesignTimePath write _DesignTimePath;
  428. property ReadOnly : Boolean read _ReadOnly write _Readonly default False;
  429. property ShowDeleted:boolean read _ShowDeleted write _ShowDeleted;
  430. // redeclared data set properties
  431. property Active;
  432. property Filtered;
  433. property BeforeOpen;
  434. property AfterOpen;
  435. property BeforeClose;
  436. property AfterClose;
  437. property BeforeInsert;
  438. property AfterInsert;
  439. property BeforeEdit;
  440. property AfterEdit;
  441. property BeforePost;
  442. property AfterPost;
  443. property BeforeCancel;
  444. property AfterCancel;
  445. property BeforeDelete;
  446. property AfterDelete;
  447. property BeforeScroll;
  448. property AfterScroll;
  449. property OnCalcFields;
  450. property OnDeleteError;
  451. property OnEditError;
  452. property OnFilterRecord;
  453. property OnNewRecord;
  454. property OnPostError;
  455. //my datas....
  456. protected
  457. _IsCursorOpen:boolean;
  458. _PhysicalRecno:integer;
  459. _CurIndex: TIndex;
  460. _Indexes:TList; // index
  461. _indexFile : TIndexFile;
  462. _dbtFile : TDbtFile;
  463. public
  464. _dbfFile:TDbfFile;
  465. property PhysicalRecno:integer read _PhysicalRecno;
  466. function _RecordDataSize:integer;
  467. end;
  468. {$ifndef fpc}
  469. procedure Register;
  470. {$endif}
  471. var
  472. tDbf_TrimFields : boolean;
  473. implementation
  474. var
  475. _PagedFiles : TList;
  476. //====================================================================
  477. // Some types and consts which are not useful in the interface.
  478. //====================================================================
  479. (*
  480. * tSmallint 16 bits = -32768 to 32767
  481. * 123456 = 6 digit max
  482. * ftInteger 32 bits = -2147483648 to 2147483647
  483. * 12345678901 = 11 digits max
  484. * ftLargeInt 64 bits = -9223372036854775808 to 9223372036854775807
  485. * 12345678901234567890 = 20 digits max
  486. *)
  487. const
  488. DIGITS_SMALLINT = 6;
  489. DIGITS_INTEGER = 11;
  490. DIGITS_LARGEINT = 20;
  491. sDBF_DEC_SEP= '.';
  492. type
  493. rAfterHdrIII = record // Empty
  494. end;
  495. rAfterHdrV = record
  496. Dummy : array[32..67] of byte;
  497. end;
  498. PMdxTag = ^rMdxTag;
  499. rMdxTagHdr = record
  500. RootPage : longint;// 0..3
  501. FilePages : longint;// 4..7
  502. KeyFormat : byte; // 8
  503. KeyType : char; // 9
  504. dummy : word; // 10..11
  505. IndexKeyLength : word; // 12..13
  506. MaxNbKeys : word; // 14..15
  507. SecondKeyType : word; // 16..17
  508. IndexKeyItemLen : word; // 18..19
  509. dummy2 : array [20..22] of byte;
  510. UniqueFlag : byte; // 23
  511. end;
  512. rAfterHdrV3 = record
  513. Dummy : array[12..31] of byte;
  514. end;
  515. rAfterHdrV4 = record
  516. Dummy : array[12..67] of byte;
  517. end;
  518. rFieldHdrV3 = record
  519. FieldName : array[0..10] of char;
  520. FieldType : char; // 11
  521. Dummy : array[12..15] of byte;
  522. FieldSize : byte; // 16
  523. FieldPrecision : byte; //17
  524. dummy2 : array[18..31] of byte;
  525. end;
  526. rFieldHdrV4 = record
  527. FieldName : array[0..10] of char;
  528. Dummy0 : array[11..31] of byte;
  529. FieldType : char; // 32
  530. FieldSize : byte; // 33
  531. FieldPrecision : byte; //34
  532. dummy2 : array[35..47] of byte;
  533. end;
  534. PDouble = ^double;
  535. //====================================================================
  536. // Now some common functions and procedure
  537. //====================================================================
  538. // ****************************************************************************
  539. // International separator
  540. // thanks to Bruno Depero from Italy
  541. // and Andreas Wöllenstein from Denmark
  542. function DbfStrToFloat(s: string): Extended;
  543. var iPos: integer;
  544. eValue: extended;
  545. begin
  546. iPos:= Pos(sDBF_DEC_SEP, s);
  547. if iPos> 0 then
  548. s[iPos]:= DecimalSeparator;
  549. {$ifndef fpc}
  550. if TextToFloat(pchar(s), eValue, fvExtended) then
  551. {$else}
  552. Val(s,eValue,Ipos);
  553. If Ipos=0 then
  554. {$endif}
  555. Result:= eValue
  556. else Result:= 0;
  557. end;
  558. function FloatToDbfStr(f: Extended; size, prec: integer): string;
  559. var iPos: integer;
  560. begin
  561. Result:= FloatToStrF(f, ffFixed, Size, prec);
  562. iPos:= Pos(DecimalSeparator, Result);
  563. if iPos> 0 then
  564. Result[iPos]:= sDBF_DEC_SEP;
  565. end;
  566. procedure MyMove(Source, Dest:PChar; Count: Integer);
  567. var
  568. c:char;
  569. i:integer;
  570. begin
  571. i:=0;
  572. while i<Count do begin
  573. c:=PChar(Source)[i];
  574. if c=#0 then break;
  575. PChar(Dest)[i]:=c;
  576. Inc(i);
  577. end;
  578. while i<Count do begin
  579. PChar(Dest)[i]:=' ';
  580. Inc(i);
  581. end;
  582. end;
  583. //====================================================================
  584. // TPagedFile
  585. //====================================================================
  586. function GetPagedFile(FileName: string):TPagedFile;
  587. var
  588. idx:integer;
  589. idf:TPagedFile;
  590. begin
  591. FileName:=LowerCase(FileName);
  592. for idx:=0 to _PagedFiles.Count-1 do begin
  593. idf:= TPagedFile(_PagedFiles[idx]);
  594. if idf._FileName=FileName then begin
  595. result:=idf;
  596. exit;
  597. end;
  598. end;
  599. result:=nil;
  600. end;
  601. procedure TPagedFile.Release;
  602. var
  603. i: integer;
  604. begin
  605. dec(_cntuse);
  606. if _cntuse<=0 then begin
  607. i:=_PagedFiles.IndexOf(self);
  608. if i>=0 then _PagedFiles.Delete(i);
  609. Free;
  610. end;
  611. end;
  612. function TPagedFile.CalcRecordCount:Integer;
  613. begin
  614. if RecordSize = 0 then Result:=0
  615. else Result:=(Stream.Size - HeaderSize) div RecordSize;
  616. end;
  617. constructor TPagedFile.Create(const FileName: string; Mode: Word);
  618. begin
  619. if filename='' then Stream:=TMemoryStream.Create()
  620. else begin
  621. Stream:=TFileStream.Create(FileName,Mode);
  622. end;
  623. HeaderSize:=0;
  624. RecordSize:=0;
  625. _cntuse:=0;
  626. _filename:=lowercase(filename);
  627. _PagedFiles.Add(Self);
  628. end;
  629. destructor TPagedFile.Destroy;
  630. begin
  631. Stream.Free;
  632. Stream:=nil;
  633. inherited;
  634. end;
  635. procedure TPagedFile._Seek(page:Integer);
  636. var
  637. p:Integer;
  638. begin
  639. p:=HeaderSize + (RecordSize * page );
  640. Stream.Position := p;
  641. end;
  642. Procedure TPagedFile.ReadRecord(IntRecNum:Integer; Buffer:Pointer);
  643. begin
  644. _Seek(IntRecNum);
  645. Stream.Read(Buffer^,RecordSize);
  646. end;
  647. procedure TPagedFile.WriteRecord(IntRecNum:Integer; Buffer:Pointer);
  648. begin
  649. _Seek(IntRecNum);
  650. Stream.Write(Buffer^, RecordSize);
  651. end;
  652. //====================================================================
  653. // TDbfFile
  654. //====================================================================
  655. constructor TDbfFile.Create(const FileName: string; Mode: Word);
  656. var
  657. lRecordCount:Integer;
  658. begin
  659. _MyFieldInfos:=TList.Create;
  660. // check if the file exists
  661. inherited Create(Filename, Mode);
  662. if Mode = fmCreate then begin
  663. FillChar(_DataHdr,sizeof(_DataHdr),0);
  664. HeaderSize:=0;
  665. RecordSize:=0;
  666. _DataHdr.VerDBF:=$03; // Default version xBaseIV without memo
  667. _DataHdr.Language:='X';
  668. end else begin
  669. Stream.Seek(0,soFromBeginning);
  670. Stream.ReadBuffer (_DataHdr, SizeOf(_DataHdr));
  671. case _DataHdr.VerDBF of
  672. $03,$83: _DbfVersion:=xBaseIII;
  673. $04,$8B,$8E,$7B: _DbfVersion:=xBaseIV;
  674. $05 : _DbfVersion:=xbaseV;
  675. else
  676. _DbfVersion:=xBaseIV; // My favorite...
  677. end;
  678. HeaderSize:=_DataHdr.FullHdrSize;
  679. RecordSize:=_DataHdr.RecordSize;
  680. lRecordCount:=CalcRecordCount;
  681. if _DataHdr.RecordCount <> lRecordCount then begin
  682. {$ifndef fpc}
  683. ShowMessage('Invalid Record Count,'+^M+
  684. 'RecordCount in Hdr : '+IntToStr(_DataHdr.RecordCount)+^M+
  685. 'expected : '+IntToStr(lRecordCount));
  686. {$endif}
  687. _DataHdr.RecordCount := lRecordCount;
  688. end;
  689. end;
  690. end;
  691. destructor TDbfFile.Destroy;
  692. begin
  693. inherited;
  694. ClearMyFieldInfos;
  695. _MyFieldInfos.Free;
  696. _MyFieldInfos:=nil;
  697. end;
  698. function TDbfFile.RecordCount:integer;
  699. begin
  700. if RecordSize=0 then result:=0
  701. else result:=(Stream.Size - HeaderSize) div RecordSize;
  702. if result<0 then result:=0;
  703. end;
  704. procedure TDbfFile.ClearMyFieldInfos;
  705. var
  706. i:Integer;
  707. begin
  708. for i:=0 to _MyFieldInfos.Count-1 do begin
  709. TMyFieldInfo(_MyFieldInfos.Items[i]).Free;
  710. end;
  711. _MyFieldInfos.Clear;
  712. end;
  713. procedure TDbfFile.CreateFieldDefs(FieldDefs:TFieldDefs);
  714. var
  715. lColumnCount,lHeaderSize,lFieldSize:Integer;
  716. Il : Integer;
  717. lFieldOffset : Integer;
  718. fn:string;
  719. ft:TFieldType;
  720. fs,nfs,fd:Integer;
  721. MyFieldInfo:TMyFieldInfo;
  722. lFieldHdrIII:rFieldHdrIII;
  723. lFieldHdrV:rFieldHdrV;
  724. function ToFieldType(dbasetype:char;fs,fd:Integer):TFieldType;
  725. begin
  726. case dbasetype of
  727. 'C' :
  728. begin
  729. Result:=ftString;
  730. end;
  731. 'L' :
  732. begin
  733. Result:=ftBoolean;
  734. end;
  735. 'F' :
  736. begin
  737. Result:=ftFloat;
  738. end;
  739. 'N' :
  740. begin
  741. if fd=0 then begin
  742. if fs <= DIGITS_SMALLINT then begin
  743. Result:=ftSmallInt;
  744. end else begin
  745. {$ifdef DELPHI_3}
  746. Result:=ftInteger;
  747. {$else}
  748. if fs <= DIGITS_INTEGER then Result:=ftInteger
  749. else Result:=ftLargeInt;
  750. {$endif}
  751. end;
  752. end else begin
  753. Result:=ftFloat;
  754. end;
  755. end;
  756. 'D' :
  757. begin
  758. Result:=ftDate;
  759. end;
  760. 'M' :
  761. begin
  762. Result:=ftMemo;
  763. end;
  764. else
  765. begin
  766. Result:=ftString;
  767. end;
  768. end; //case
  769. end;
  770. begin
  771. ClearMyFieldInfos;
  772. if _DbfVersion>=xBaseV then begin
  773. lHeaderSize:=SizeOf(rAfterHdrV) + SizeOf(rDbfHdr);
  774. lFieldSize:=SizeOf(rFieldHdrV);
  775. end else begin
  776. lHeaderSize:=SizeOf(rAfterHdrIII) + SizeOf(rDbfHdr);
  777. lFieldSize:=SizeOf(rFieldHdrIII);
  778. end;
  779. lColumnCount:= (_DataHdr.FullHdrSize - lHeaderSize) div lFieldSize;
  780. if (lColumnCount <= 0) or (lColumnCount > 255) then
  781. Raise eBinaryDataSetError.Create('Invalid field count : ' + IntToStr(lColumnCount) + ' (must be between 1 and 255)');
  782. lFieldOffset := 1;
  783. Stream.Position := lHeaderSize;
  784. for Il:=0 to lColumnCount-1 do begin
  785. if _DbfVersion>=xBaseV then begin
  786. Stream.ReadBuffer(lFieldHdrV,SizeOf(lFieldHdrV));
  787. fn:=PCHAR(@lFieldHdrV.FieldName[0]);
  788. fs:=lFieldHdrV.FieldSize;
  789. fd:=lFieldHdrV.FieldPrecision;
  790. nfs:=fs;
  791. ft:=ToFieldType(lFieldHdrV.FieldType,nfs,fd);
  792. end else begin
  793. Stream.ReadBuffer(lFieldHdrIII,SizeOf(lFieldHdrIII));
  794. fn:=PCHAR(@lFieldHdrIII.FieldName[0]);
  795. fs:=lFieldHdrIII.FieldSize;
  796. fd:=lFieldHdrIII.FieldPrecision;
  797. nfs:=fs;
  798. ft:=ToFieldType(lFieldHdrIII.FieldType,nfs,fd);
  799. end;
  800. // first create the bde field
  801. if ft in [ftString,ftBCD] then fieldDefs.Add(fn,ft,fs,false)
  802. else fieldDefs.Add(fn,ft,0,false);
  803. // then create the for our own fieldinfo
  804. MyFieldInfo:=TMyFieldInfo.Create;
  805. MyFieldInfo.Offset:=lFieldOffset;
  806. MyFieldInfo.Size:=fs;
  807. MyFieldInfo.Prec:=fd;
  808. MyFieldInfo.FieldName:=lowercase(fn);
  809. _MyFieldInfos.Add(MyFieldInfo);
  810. Inc(lFieldOffset,fs);
  811. end;
  812. if (lFieldOffset <> _DataHdr.RecordSize) then begin
  813. {$ifndef fpc}
  814. ShowMessage('Invalid Record Size,'+^M+
  815. 'Record Size in Hdr : '+IntToStr(_DataHdr.RecordSize)+^M+
  816. 'Expected : '+IntToStr(lFieldOffset));
  817. {$endif}
  818. _DataHdr.RecordSize := lFieldOffset;
  819. end;
  820. end;
  821. procedure TDbfFile.DbfFile_CreateTable(FieldDefs:TFieldDefs);
  822. var
  823. ix:Integer;
  824. lFieldHdrIII:rFieldHdrIII;
  825. lType:Char;
  826. lSize,lPrec:Integer;
  827. Offs:Integer;
  828. lterminator:Byte;
  829. begin
  830. // first reset file.
  831. Stream.Size:= 0;
  832. Stream.Position:=SizeOf(rDbfHdr) + SizeOf(rAfterHdrIII);
  833. Offs:=1; // deleted mark count 1.
  834. for Ix:=0 to FieldDefs.Count-1 do
  835. begin
  836. with FieldDefs.Items[Ix] do
  837. begin
  838. FillChar(lFieldHdrIII,SizeOf(lFieldHdrIII),#0);
  839. lPrec:=0;
  840. case DataType of
  841. ftString:
  842. begin
  843. ltype:='C';
  844. lSize := Size;
  845. end;
  846. ftBoolean:
  847. begin
  848. ltype:='L';
  849. lSize := 1;
  850. end;
  851. ftSmallInt:
  852. begin
  853. ltype:='N';
  854. lSize := 6;
  855. end;
  856. ftInteger:
  857. begin
  858. ltype:='N';
  859. lSize := 11;
  860. end;
  861. ftCurrency:
  862. begin
  863. ltype:='N';
  864. lSize := 20;
  865. lPrec := 2;
  866. end;
  867. {$ifndef DELPHI_3}
  868. ftLargeInt:
  869. begin
  870. ltype:='N';
  871. lSize := 20;
  872. lPrec := 0;
  873. end;
  874. {$endif}
  875. ftFloat:
  876. begin
  877. ltype:='N';
  878. lSize := 20;
  879. lPrec := 4;
  880. end;
  881. ftDate:
  882. begin
  883. ltype:='D';
  884. lSize := 8;
  885. end;
  886. ftMemo:
  887. begin
  888. ltype:='M';
  889. lSize := 10;
  890. end;
  891. else
  892. begin
  893. raise EBinaryDataSetError.Create(
  894. 'InitFieldDefs: Unsupported field type');
  895. end;
  896. end; // case
  897. lFieldHdrIII.FieldType:=ltype; //DataType;
  898. StrPCopy(lFieldHdrIII.FieldName,FieldDefs.Items[Ix].Name);
  899. lFieldHdrIII.FieldSize:=lSize;
  900. lFieldHdrIII.FieldPrecision:=lPrec;
  901. Stream.Write(lFieldHdrIII,SizeOf(lFieldHdrIII));
  902. Inc(Offs,lSize);
  903. end;
  904. end;
  905. // end of header
  906. lterminator := $0d;
  907. Stream.Write(lterminator,SizeOf(lterminator));
  908. // update header
  909. _DataHdr.RecordSize := Offs;
  910. _DataHdr.FullHdrSize := Stream.Position;
  911. RecordSize := _DataHdr.RecordSize;
  912. HeaderSize := _DataHdr.FullHdrSize;
  913. // write the updated header
  914. WriteHeader;
  915. end;
  916. procedure TDbfFile.DbfFile_PackTable;
  917. var
  918. first,last:integer;
  919. p: Pointer;
  920. begin
  921. // Non tested.
  922. if (RecordSize <> 0) then
  923. begin
  924. first:=0;
  925. last:=CalcRecordCount-1;
  926. GetMem(p, RecordSize);
  927. try
  928. while first<last do begin
  929. // first find the first hole
  930. while first<last do begin
  931. ReadRecord(first, p);
  932. if (pRecordHdr(p)^.DeletedFlag <> ' ') then break;
  933. inc(first);
  934. end;
  935. // now find last one non deleted.
  936. while first<last do begin
  937. ReadRecord(last, p);
  938. if (pRecordHdr(p)^.DeletedFlag = ' ') then break;
  939. dec(last);
  940. end;
  941. if first<last then begin
  942. // found a non deleted record to put in the hole.
  943. WriteRecord(first, p);
  944. inc(first);
  945. dec(last);
  946. end;
  947. end;
  948. last:=CalcRecordCount;
  949. Stream.Size:=(last+1) * RecordSize + HeaderSize;
  950. finally
  951. FreeMem(p);
  952. end;
  953. end;
  954. end;
  955. function TDbfFile.GetFieldInfo(FieldName:string):TMyFieldInfo;
  956. var
  957. i:Integer;
  958. lfi:TMyFieldInfo;
  959. begin
  960. FieldName:=LowerCase(FieldName);
  961. for i:=0 to _MyFieldInfos.Count-1 do begin
  962. lfi:=TMyFieldInfo(_MyFieldInfos.Items[i]);
  963. if lfi.FieldName = FieldName then begin
  964. result:=lfi;
  965. exit;
  966. end;
  967. end;
  968. result:=nil;
  969. end;
  970. function TDbfFile.GetFieldData(Column:Integer;DataType:TFieldType; Src,Dst:Pointer): Boolean;
  971. var
  972. FieldOffset: Integer;
  973. FieldSize: Integer;
  974. s:string;
  975. d:TDateTime;
  976. ld,lm,ly: word;
  977. MyFieldInfo:TMyFieldInfo;
  978. function TrimStr(const s: string): string;
  979. var
  980. iPos: integer;
  981. begin
  982. if DataType=ftString then
  983. begin
  984. if tDbf_TrimFields then Result:=Trim(s)
  985. else Result:=TrimRight(s);
  986. end
  987. else Result:= Trim(s);
  988. end;
  989. procedure CorrectYear(var wYear: word);
  990. var wD, wM, wY, CenturyBase: word;
  991. {$ifdef DELPHI_3}
  992. // Delphi 3 standard-behavior no change possible
  993. const TwoDigitYearCenturyWindow= 0;
  994. {$endif}
  995. begin
  996. if wYear>= 100 then
  997. Exit;
  998. DecodeDate(Date, wY, wm, wD);
  999. // use Delphi-Date-Window
  1000. CenturyBase := wY{must be CurrentYear} - TwoDigitYearCenturyWindow;
  1001. Inc(wYear, CenturyBase div 100 * 100);
  1002. if (TwoDigitYearCenturyWindow > 0) and (wYear < CenturyBase) then
  1003. Inc(wYear, 100);
  1004. end;
  1005. begin
  1006. MyFieldInfo:=TMyFieldInfo(_MyFieldInfos.Items[Column]);
  1007. FieldOffset := MyFieldInfo.Offset;
  1008. FieldSize := MyFieldInfo.Size;
  1009. SetString(s, PChar(Src) + FieldOffset, FieldSize );
  1010. s:=TrimStr(s);
  1011. result:=length(s)>0; // return if field is empty
  1012. if Result and (Dst<>nil) then// data not needed if Result= FALSE or Dst=nil
  1013. case DataType of
  1014. ftBoolean:
  1015. begin
  1016. // in DBase- FileDescription lowercase t is allowed too
  1017. // with asking for Result= TRUE s must be longer then 0
  1018. // else it happens an AV, maybe field is NULL
  1019. if (UpCase(s[1])='T') then Word(Dst^) := 1
  1020. else Word(Dst^) := 0;
  1021. end;
  1022. ftInteger, ftSmallInt{$ifndef DELPHI_3},ftLargeInt{$endif}:
  1023. begin
  1024. case DataType of
  1025. ftSmallInt : SmallInt(Dst^):= StrToIntDef(s, 0);
  1026. {$ifndef DELPHI_3}
  1027. ftLargeint : LargeInt(Dst^):= StrToInt64Def(s, 0);
  1028. {$endif}
  1029. else // ftInteger :
  1030. Integer(Dst^):= StrToIntDef(s, 0);
  1031. end; // case
  1032. end;
  1033. ftFloat:
  1034. begin
  1035. Extended(Dst^) := DBFStrToFloat(s);
  1036. end;
  1037. ftCurrency:
  1038. begin
  1039. Extended(Dst^) := DBFStrToFloat(s);
  1040. end;
  1041. ftDate:
  1042. begin
  1043. ld:=StrToIntDef(Copy(s,7,2),1);
  1044. lm:=StrToIntDef(Copy(s,5,2),1);
  1045. ly:=StrToIntDef(Copy(s,1,4),0);
  1046. if ld=0 then ld:=1;
  1047. if lm=0 then lm:=1;
  1048. // if (ly<1900) or (ly>2100) then ly:=1900;
  1049. // Year from 0001 to 9999 is possible
  1050. // everyting else is an error, an empty string too
  1051. // Do DateCorrection with Delphis possibillities for one or two digits
  1052. if (ly< 100) and (Length(Trim(Copy(s,1,4)))in [1, 2]) then CorrectYear(ly);
  1053. try
  1054. d:=EncodeDate(ly,lm,ld);
  1055. if Assigned(Dst) then Integer(Dst^) := DateTimeToTimeStamp(d).Date;
  1056. except
  1057. Integer(Dst^) := 0;
  1058. end;
  1059. end;
  1060. ftString: begin
  1061. StrPCopy(Dst,s);
  1062. end;
  1063. end;
  1064. end;
  1065. procedure TDbfFile.SetFieldData(Column:integer;DataType:TFieldType; Src,Dst:Pointer);
  1066. var
  1067. FieldSize,FieldPrec: Integer;
  1068. s:string;
  1069. fl:Double;
  1070. ts:TTimeStamp;
  1071. MyFieldInfo:TMyFieldInfo;
  1072. begin
  1073. MyFieldInfo:=TMyFieldInfo(_MyFieldInfos.Items[Column]);
  1074. FieldSize := MyFieldInfo.Size;
  1075. FieldPrec := MyFieldInfo.Prec;
  1076. Dst:=PChar(Dst)+MyFieldInfo.Offset;
  1077. if src<>nil then begin
  1078. case DataType of
  1079. ftBoolean:
  1080. begin
  1081. if Word(Src^) = 1 then s:='T'
  1082. else s:='F';
  1083. end;
  1084. ftInteger, ftSmallInt {$ifndef DELPHI_3},ftLargeInt{$endif}:
  1085. begin
  1086. case DataType of
  1087. ftSmallInt : s:= IntToStr(SmallInt(Src^));
  1088. {$ifndef DELPHI_3}
  1089. ftLargeInt: s:= IntToStr(LargeInt(Src^));
  1090. {$endif}
  1091. else //ftInteger
  1092. s:= IntToStr(Integer(Src^));
  1093. end;
  1094. // left filling
  1095. if Length(s)<FieldSize then s:=StringOfChar(' ',FieldSize-Length(s)) + s;
  1096. end;
  1097. ftFloat,ftCurrency:
  1098. begin
  1099. fl := Double(Src^);
  1100. s:=FloatToDbfStr(fl,FieldSize,FieldPrec);
  1101. if Length(s)<FieldSize then s:=StringOfChar(' ',FieldSize-Length(s)) + s;
  1102. end;
  1103. ftDate:
  1104. begin
  1105. ts.Time:=0;
  1106. ts.Date:=Integer(Src^);
  1107. s:= FormatDateTime('yyyymmdd', TimeStampToDateTime(ts));
  1108. end;
  1109. ftString:
  1110. begin
  1111. s:=PChar(Src); // finish with first 0
  1112. end;
  1113. end; // case
  1114. end; // if src<>nil (thanks andreas)
  1115. if Length(s)<FieldSize then begin
  1116. s:=s+StringOfChar(' ',FieldSize-Length(s));
  1117. end else if (Length(s)>FieldSize) then begin
  1118. if DataType= ftString then begin
  1119. // never raise for strings to long, its not customary
  1120. // TTable never raises
  1121. SetLength(s, FieldSize)
  1122. end else begin
  1123. raise eFieldToLongError.Create('Fielddata too long :' + IntToStr(Length(s))
  1124. + ' (must be between 1 and ' + IntToStr(FieldSize) + ').');
  1125. end;
  1126. end;
  1127. Move(PChar(s)^, Dst^, FieldSize);
  1128. end;
  1129. procedure TDbfFile.WriteHeader;
  1130. var
  1131. SystemTime: TSystemTime;
  1132. lAfterHdrIII:rAfterHdrIII;
  1133. lAfterHdrV:rAfterHdrV;
  1134. lterminator:Byte;
  1135. begin
  1136. Assert(Stream<>nil,'_dbfFile=Nil');
  1137. Stream.Position:=0;
  1138. GetLocalTime(SystemTime);
  1139. {$ifndef fpc}
  1140. _DataHdr.Year := SystemTime.wYear - 1900;
  1141. _DataHdr.Month := SystemTime.wMonth;
  1142. _DataHdr.Day := SystemTime.wDay;
  1143. {$else}
  1144. _DataHdr.Year := SystemTime.Year - 1900;
  1145. _DataHdr.Month := SystemTime.Month;
  1146. _DataHdr.Day := SystemTime.Day;
  1147. {$endif}
  1148. Stream.Seek(0,soFromBeginning);
  1149. Stream.WriteBuffer (_DataHdr, SizeOf(_DataHdr));
  1150. _DataHdr.RecordCount := CalcRecordCount;
  1151. if _DbfVersion >= xBaseV then begin
  1152. FillChar(lAfterHdrV,SizeOf(lAfterHdrV),0);
  1153. Stream.WriteBuffer (lAfterHdrV, SizeOf(lAfterHdrV));
  1154. end else begin
  1155. FillChar(lAfterHdrIII,SizeOf(lAfterHdrIII),0);
  1156. Stream.WriteBuffer (lAfterHdrIII, SizeOf(lAfterHdrIII));
  1157. end;
  1158. _Seek(_DataHdr.RecordCount); // last byte usually...
  1159. lterminator := $1A;
  1160. Stream.Write(lterminator,SizeOf(lterminator));
  1161. end;
  1162. function TDbf._ComponentInfo:string;
  1163. begin
  1164. Result:='TDbf V' + IntToStr(_MAJOR_VERSION) + '.' + IntToStr(_MINOR_VERSION);
  1165. end;
  1166. procedure TDbf._OpenFiles(CreateIt:boolean);
  1167. var
  1168. fileopenmode : integer;
  1169. lPath,lFilename,lIndexName,lMemoName : string;
  1170. isAbsolute:boolean;
  1171. design,doreadonly:boolean;
  1172. begin
  1173. design:=(csDesigning in ComponentState);
  1174. doreadonly:=design or _ReadOnly;
  1175. lPath:=_GetPath;
  1176. isAbsolute:=((length(_TableName)>=1) and (_TableName[1]='\'))
  1177. or ((length(_TableName)>=2) and (_TableName[2]=':'));
  1178. if isAbsolute then lfilename:=_TableName
  1179. else lFilename:=lPath+_TableName;
  1180. lFilename:=ChangeFileExt(lFilename,'.dbf');
  1181. lIndexName:=ChangeFileExt(lFilename,'.mdx');
  1182. lMemoName:=ChangeFileExt(lFilename,'.dbt');
  1183. // check if the file exists
  1184. _dbfFile:=TDbfFile(GetPagedFile(lFileName));
  1185. _indexFile:=TIndexFile(GetPagedFile(lIndexName));
  1186. _dbtFile:=TDbtFile(GetPagedFile(lMemoName));
  1187. if CreateIt then begin
  1188. if _dbfFile=nil then _dbfFile:=TDbfFile.Create(lFileName,fmCreate);
  1189. //if _indexfile=nil then _indexFile := TIndexFile.Create(lIndexName, fmCreate);
  1190. if _dbtfile=nil then _dbtFile := TDbtFile.Create(lMemoName, fmCreate,_dbfFile._DbfVersion);
  1191. end else if not FileExists(lFileName) then begin
  1192. raise eBinaryDataSetError.Create ('Open: Table file not found : ' + lFileName);
  1193. end else begin
  1194. if DoReadOnly then
  1195. fileopenmode := fmOpenRead + fmShareDenyNone
  1196. else
  1197. fileopenmode := fmOpenReadWrite + fmShareDenyWrite;
  1198. if _dbfFile=nil then _dbfFile := TDBFFile.Create(lFileName, fileopenmode);
  1199. if (_indexFile=nil) and FileExists (lIndexName) then begin
  1200. _indexFile := TIndexFile.Create(lIndexName, fileopenmode);
  1201. end;
  1202. if (_dbtFile=nil) and FileExists (lMemoName) then begin
  1203. _dbtFile := TDbtFile.Create(lMemoName, fileopenmode,_dbfFile._DbfVersion);
  1204. end;
  1205. end;
  1206. _PrevBuffer:=AllocRecordBuffer;
  1207. _IsCursorOpen:=true;
  1208. end;
  1209. function TDbf._GetPath:string;
  1210. var
  1211. lPath:string;
  1212. begin
  1213. if (csDesigning in ComponentState) then begin
  1214. lPath:=_DesignTimePath;
  1215. end else begin
  1216. if ((length(_RunTimePath)>=1) and (_RunTimePath[1]=DirSeparator))
  1217. or ((length(_RunTimePath)>=2) and (_RunTimePath[2]=':'))
  1218. then begin
  1219. // if the _RunTimePath is absolute...
  1220. // it is either \ or \blahblah or c:\
  1221. lPath:=_RunTimePath;
  1222. end else begin
  1223. {$ifndef fpc}
  1224. lPath:=extractfilepath(Application.Exename)+_RunTimePath;
  1225. {$else}
  1226. lPath:=extractfilepath(paramstr(0))+_RunTimePath;
  1227. {$endif}
  1228. end;
  1229. end;
  1230. lPath:=ExpandFileName(trim(lPath));
  1231. if (length(lPath)>0) and (lPath[length(lPath)]<>DirSeparator) then lPath:=lPath+DirSeparator;
  1232. result:=lPath;
  1233. end;
  1234. procedure TDbf._CloseFiles;
  1235. var
  1236. i:integer;
  1237. begin
  1238. if _dbfFile<>nil then begin
  1239. if not _ReadOnly then _dbfFile.WriteHeader;
  1240. _dbfFile.Release;
  1241. _dbfFile:=nil;
  1242. end;
  1243. if _indexFile<>nil then begin
  1244. _indexFile.Release;
  1245. _indexFile:=nil;
  1246. end;
  1247. if _dbtFile<>nil then begin
  1248. _dbtFile.Release;
  1249. _dbtFile:=nil;
  1250. end;
  1251. if _indexes<>nil then begin
  1252. for i:=0 to _Indexes.Count-1 do begin
  1253. TIndex(_Indexes[i]).Free;
  1254. end;
  1255. _Indexes.Clear;
  1256. _CurIndex:=nil;
  1257. end;
  1258. if (_PrevBuffer<>nil) then begin
  1259. FreeRecordBuffer(_PrevBuffer);
  1260. _PrevBuffer:=nil;
  1261. end;
  1262. _IsCursorOpen:=false;
  1263. end;
  1264. procedure TDbf._SetIndexName(const Value: string);
  1265. begin
  1266. _CurIndex:=_GetIndex(Value);
  1267. Resync([]);
  1268. end;
  1269. function TDbf._GetIndexName: string;
  1270. begin
  1271. if _CurIndex=nil then Result:=''
  1272. else Result:=_CurIndex._IndexFile._Filename;
  1273. end;
  1274. function TDbf._GetIndex(filename:string):TIndex;
  1275. var
  1276. i:integer;
  1277. lindex:TIndex;
  1278. begin
  1279. result:=nil;
  1280. filename:=lowercase(_GetPath + filename);
  1281. for i:=0 to _indexes.Count-1 do begin
  1282. lindex:=TIndex(_indexes.Items[i]);
  1283. if lindex._IndexFile._Filename=filename then begin
  1284. result:=lindex;
  1285. exit;
  1286. end;
  1287. end;
  1288. end;
  1289. //==========================================================
  1290. //============ TMyBlobFile
  1291. //==========================================================
  1292. constructor TMyBlobFile.Create(ModeVal:TBlobStreamMode;FieldVal:TField);
  1293. begin
  1294. Mode:=ModeVal;
  1295. Field:=FieldVal;
  1296. end;
  1297. destructor TMyBlobFile.destroy;
  1298. var
  1299. Dbf:TDbf;
  1300. begin
  1301. if (Mode=bmWrite) then begin
  1302. Size:=Position; // Strange but it leave tailing trash bytes if I do not write that.
  1303. Dbf:=TDbf(Field.DataSet);
  1304. Dbf._dbtFile.WriteMemo(MemoRecno,ReadSize,Self);
  1305. Dbf._dbfFile.SetFieldData(Field.FieldNo-1,
  1306. ftInteger,@MemoRecno,@pDbfRecord(TDbf(Field.DataSet).ActiveBuffer)^.deletedflag);
  1307. // seems not bad
  1308. {$ifndef fpc}
  1309. // FPC doesn't allow to call protected methods ?!!
  1310. Dbf.SetModified(true);
  1311. {$endif}
  1312. // but would that be better
  1313. //if not (State in [dsCalcFields, dsFilter, dsNewValue]) then begin
  1314. // DataEvent(deFieldChange, Longint(Field));
  1315. //end;
  1316. end;
  1317. inherited;
  1318. end;
  1319. //====================================================================
  1320. // TDbf = TDataset Descendant.
  1321. //====================================================================
  1322. constructor TDbf.Create(AOwner: TComponent); {override;}
  1323. begin
  1324. inherited create(aOwner);
  1325. BookmarkSize:=sizeof(rBookmarkData);
  1326. _RunTimePath:='.';
  1327. _IsCursorOpen:=false;
  1328. _Indexes:=TList.Create;
  1329. _CurIndex:=nil;
  1330. _IndexFiles:=TStringList.Create;
  1331. end;
  1332. destructor TDbf.Destroy; {override;}
  1333. var
  1334. i:integer;
  1335. begin
  1336. inherited;
  1337. _CurIndex:=nil;
  1338. for i:=0 to _Indexes.Count-1 do begin
  1339. TIndex(_Indexes[i]).Free;
  1340. end;
  1341. _Indexes.Free;
  1342. _IndexFiles.Free;
  1343. // _MemIndex.Free;
  1344. end;
  1345. function TDbf._FilterRecord(Buffer: PChar): Boolean;
  1346. var
  1347. SaveState: TDatasetState;
  1348. s:string;
  1349. begin
  1350. Result:=True;
  1351. if Length(easyfilter)<>0 then begin
  1352. SetString(s,buffer,RecordSize);
  1353. s:=LowerCase(s);
  1354. if Pos(easyfilter,s)=0 then begin
  1355. Result:=False;
  1356. Exit;
  1357. end;
  1358. end;
  1359. if not Assigned(OnFilterRecord) then Exit;
  1360. if not Filtered then Exit;
  1361. _FilterBuffer:=buffer;
  1362. SaveState:=SetTempState(dsFilter);
  1363. OnFilterRecord(self,Result);
  1364. RestoreState(SaveState);
  1365. end;
  1366. function TDbf._RecordDataSize:integer;
  1367. begin
  1368. if _dbfFile=nil then result:=0
  1369. else result:=_dbfFile.RecordSize;
  1370. end;
  1371. function TDbf._FullRecordSize:integer;
  1372. begin
  1373. result:=sizeof(rBeforeRecord) + _RecordDataSize + CalcFieldsSize;
  1374. end;
  1375. function TDbf.AllocRecordBuffer: PChar; {override virtual abstract from TDataset}
  1376. begin
  1377. result:=StrAlloc(_FullRecordSize);
  1378. InternalInitRecord(result);
  1379. end;
  1380. procedure TDbf.FreeRecordBuffer(var Buffer: PChar); {override virtual abstract from TDataset}
  1381. begin
  1382. StrDispose(Buffer);
  1383. end;
  1384. procedure TDbf.GetBookmarkData(Buffer: PChar; Data: Pointer); {override virtual abstract from TDataset}
  1385. var
  1386. prec:pDbfRecord;
  1387. begin
  1388. prec:=pDbfRecord(Buffer);
  1389. pBookMarkData(Data)^:=prec^.BookMarkData;
  1390. end;
  1391. function TDbf.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; {override virtual abstract from TDataset}
  1392. var
  1393. prec:pDbfRecord;
  1394. begin
  1395. prec:=pDbfRecord(Buffer);
  1396. result:=prec^.BookMarkFlag;
  1397. end;
  1398. function TDbf.GetFieldData(Field: TField; Buffer: Pointer): Boolean; {override virtual abstract from TDataset}
  1399. var
  1400. ptr:pointer;
  1401. begin
  1402. Result := False;
  1403. if State=dsFilter then begin
  1404. Ptr:=_FilterBuffer;
  1405. end else if State = dsCalcFields then begin
  1406. // ***** calc fields ***** set correct buffer
  1407. ptr := @(pDbfRecord(CalcBuffer)^.deletedflag);
  1408. end else begin
  1409. if IsEmpty then exit;
  1410. ptr:=@(pDbfRecord(ActiveBuffer)^.deletedflag);
  1411. end;
  1412. if Field.FieldNo>0 then begin
  1413. Result:=_dbfFile.GetFieldData(Field.FieldNo - 1,Field.DataType,ptr,Buffer);
  1414. end else begin { calculated fields.... }
  1415. Inc(PChar(Ptr), Field.Offset + GetRecordSize);
  1416. {$ifndef fpc}
  1417. Result := Boolean(PChar(Ptr)[0]);
  1418. {$else}
  1419. Result := (Pchar(ptr)[0]<>#0);
  1420. {$endif}
  1421. if Result and (Buffer <> nil) then
  1422. Move(PChar(Ptr)[1], Buffer^, Field.DataSize);
  1423. end;
  1424. end;
  1425. function TDbf.GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; {override virtual abstract from TDataset}
  1426. var
  1427. Acceptable : Boolean;
  1428. prec:pDBFRecord;
  1429. begin
  1430. prec:=pDBFRecord(Buffer);
  1431. if _dbfFile.RecordCount < 1 then
  1432. Result := grEOF
  1433. else repeat
  1434. result := grOk;
  1435. case GetMode of
  1436. gmCurrent :
  1437. begin
  1438. if prec^.BookmarkData.Recno=_PhysicalRecno then begin
  1439. exit; // try to fasten a bit...
  1440. end;
  1441. end;
  1442. gmNext :
  1443. begin
  1444. if _curIndex<>nil then begin
  1445. Acceptable:=_curIndex.Next;
  1446. end else begin
  1447. inc(_PhysicalRecno);
  1448. Acceptable:=(_PhysicalRecno<_dbfFile.RecordCount);
  1449. end;
  1450. if Acceptable then begin
  1451. result:= grOk;
  1452. end else begin
  1453. InternalLast;
  1454. result:= grEOF
  1455. end;
  1456. end;
  1457. gmPrior :
  1458. begin
  1459. if _curIndex<>nil then begin
  1460. Acceptable:=_curIndex.Prev;
  1461. end else begin
  1462. dec(_PhysicalRecno);
  1463. Acceptable:=(_PhysicalRecno>=0);
  1464. end;
  1465. if Acceptable then begin
  1466. result:= grOk;
  1467. end else begin
  1468. InternalFirst;
  1469. result:= grBOF
  1470. end;
  1471. end;
  1472. end;
  1473. if result=grOk then begin
  1474. if _curIndex<>nil then _PhysicalRecno:=_CurIndex.GetRealRecNo;
  1475. if (_PhysicalRecno>=_dbfFile.RecordCount)
  1476. or (_PhysicalRecno<0) then begin
  1477. result:=grError;
  1478. end else begin
  1479. _dbfFile.ReadRecord(_PhysicalRecno,@prec^.DeletedFlag);
  1480. result:=grOk;
  1481. end;
  1482. if Result = grOK then begin
  1483. ClearCalcFields(Buffer);
  1484. GetCalcFields(Buffer);
  1485. prec^.BookmarkFlag := bfCurrent;
  1486. prec^.BookmarkData.Recno:=PhysicalRecno;
  1487. end else if (Result = grError) and DoCheck then
  1488. raise eBinaryDataSetError.Create ('GetRecord: Invalid record');
  1489. end;
  1490. Acceptable := (_ShowDeleted or (prec^.DeletedFlag = ' '))
  1491. and _FilterRecord(Buffer);
  1492. if (GetMode=gmCurrent) and Not Acceptable then Result := grError;
  1493. until (Result <> grOK) or Acceptable;
  1494. end;
  1495. function TDbf.GetRecordSize: Word; {override virtual abstract from TDataset}
  1496. begin
  1497. Result := _RecordDataSize; // data only
  1498. end;
  1499. procedure TDbf.InternalAddRecord(Buffer: Pointer; DoAppend: Boolean); {override virtual abstract from TDataset}
  1500. begin
  1501. end;
  1502. procedure TDbf.InternalClose; {override virtual abstract from TDataset}
  1503. begin
  1504. _CloseFiles;
  1505. // disconnect field objects
  1506. BindFields(False);
  1507. // destroy field object (if not persistent)
  1508. if DefaultFields then
  1509. DestroyFields;
  1510. end;
  1511. procedure TDbf.InternalDelete; {override virtual abstract from TDataset}
  1512. begin
  1513. // CheckActive;
  1514. pRecordHdr(ActiveBuffer)^.DeletedFlag := '*'; //_DataHdr.LastDeleted;
  1515. _dbfFile.WriteRecord(_PhysicalRecNo,ActiveBuffer);
  1516. Resync([]);
  1517. end;
  1518. procedure TDbf.InternalFirst; {override virtual abstract from TDataset}
  1519. begin
  1520. if _dbfFile.RecordCount=0 then InternalLast
  1521. else if _curindex=nil then _PhysicalRecno:=-1
  1522. else _curIndex.First;
  1523. end;
  1524. procedure TDbf.InternalGotoBookmark(ABookmark: Pointer); {override virtual abstract from TDataset}
  1525. var
  1526. RecInfo: TRecInfo;
  1527. begin
  1528. RecInfo := TRecInfo(ABookmark^);
  1529. if (RecInfo.Bookmark >= 0) and (RecInfo.Bookmark < _dbfFile.RecordCount) then begin
  1530. _PhysicalRecno:=RecInfo.Bookmark;
  1531. end else
  1532. raise eBinaryDataSetError.Create ('Bookmark ' +
  1533. IntToStr (RecInfo.Bookmark) + ' not found');
  1534. end;
  1535. procedure TDbf.InternalHandleException; {override virtual abstract from TDataset}
  1536. begin
  1537. {$ifndef fpc}
  1538. Application.HandleException(Self);
  1539. {$endif}
  1540. end;
  1541. procedure TDbf.InternalInitFieldDefs; {override virtual abstract from TDataset}
  1542. begin
  1543. FieldDefs.Clear;
  1544. with FieldDefs do
  1545. begin
  1546. if IsCursorOpen then begin
  1547. _dbfFile.CreateFieldDefs(FieldDefs);
  1548. end else begin
  1549. _OpenFiles(false);
  1550. _dbfFile.CreateFieldDefs(FieldDefs);
  1551. Close();
  1552. end;
  1553. end;
  1554. end;
  1555. procedure TDbf.InternalInitRecord(Buffer: PChar); {override virtual abstract from TDataset}
  1556. var
  1557. prec:pDbfRecord;
  1558. begin
  1559. prec:=pDbfRecord(Buffer);
  1560. prec^.BookmarkData.RecNo:=-1;
  1561. prec^.BookmarkFlag:=TBookmarkFlag(0);
  1562. fillchar(prec^.DeletedFlag,_RecordDataSize,' ');
  1563. end;
  1564. procedure TDbf.InternalLast; {override virtual abstract from TDataset}
  1565. begin
  1566. if _curindex=nil then _PhysicalRecno:=_dbfFile.RecordCount
  1567. else _curIndex.Last;
  1568. end;
  1569. procedure TDbf.InternalOpen; {override virtual abstract from TDataset}
  1570. begin
  1571. _OpenFiles(false);
  1572. // if there are no persistent field objects,
  1573. InternalInitFieldDefs;
  1574. // create the fields dynamically
  1575. if DefaultFields then begin
  1576. CreateFields;
  1577. end;
  1578. BindFields (True);
  1579. // connect the TField objects with the actual fields
  1580. InternalFirst;
  1581. end;
  1582. procedure TDbf.InternalPost; {override virtual abstract from TDataset}
  1583. var
  1584. prec:pDbfRecord;
  1585. lIndex:TIndex;
  1586. i:integer;
  1587. begin
  1588. CheckActive;
  1589. prec:=pDbfRecord(ActiveBuffer);
  1590. prec^.DeletedFlag:=' ';
  1591. if State = dsEdit then
  1592. begin
  1593. // replace data with new data
  1594. if _indexes.Count>0 then begin
  1595. _dbfFile.ReadRecord(_PhysicalRecno,_PrevBuffer);
  1596. for i:=0 to _indexes.Count-1 do begin
  1597. lindex:=TIndex(_indexes.Items[i]);
  1598. lindex.Update(_PhysicalRecno,_PrevBuffer,@prec^.DeletedFlag);
  1599. end;
  1600. end;
  1601. end else begin
  1602. // append
  1603. _PhysicalRecno:=_dbfFile._DataHdr.RecordCount;
  1604. inc(_dbfFile._DataHdr.RecordCount);
  1605. if _indexes.Count>0 then begin
  1606. _dbfFile.ReadRecord(_PhysicalRecno,_PrevBuffer);
  1607. for i:=0 to _indexes.Count-1 do begin
  1608. lindex:=TIndex(_indexes.Items[i]);
  1609. lindex.Insert(_PhysicalRecno,@prec^.DeletedFlag);
  1610. end;
  1611. end;
  1612. end;
  1613. _dbfFile.WriteRecord(_PhysicalRecno,@prec^.DeletedFlag);
  1614. end;
  1615. procedure TDbf.CreateTable; //(FieldDefs:TFieldDefs);
  1616. var
  1617. ix:integer;
  1618. begin
  1619. CheckInactive;
  1620. // InternalInitFieldDefs;
  1621. if FieldDefs.Count = 0 then
  1622. begin
  1623. for Ix := 0 to FieldCount - 1 do
  1624. begin
  1625. with Fields[Ix] do
  1626. begin
  1627. if FieldKind = fkData then
  1628. FieldDefs.Add(FieldName,DataType,Size,Required);
  1629. end;
  1630. end;
  1631. end;
  1632. _OpenFiles(true);
  1633. try
  1634. _dbfFile.DbfFile_CreateTable(FieldDefs);
  1635. finally
  1636. // close the file
  1637. _CloseFiles;
  1638. end;
  1639. end;
  1640. procedure TDbf.PackTable;
  1641. begin
  1642. _dbfFile.dbfFile_PackTable;
  1643. Resync([]);
  1644. end;
  1645. function TDbf.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; {override virtual}
  1646. var
  1647. Memoi:array[1..32] of char;
  1648. lBlob:TMyBlobFile;
  1649. begin
  1650. lBlob:=TMyBlobFile.Create(Mode,Field);
  1651. if _dbfFile.GetFieldData(Field.FieldNo-1, ftString,@pDbfRecord(ActiveBuffer)^.deletedflag,@Memoi[1]) then begin
  1652. lBlob.MemoRecno:=StrToIntDef(Memoi,0);
  1653. _dbtFile.ReadMemo(lBlob.MemoRecno,lBlob);
  1654. lBlob.ReadSize:=lBlob.Size;
  1655. end else lBlob.MemoRecno:=0;
  1656. Result:=lBlob;
  1657. end;
  1658. {$ifdef DELPHI_3}
  1659. procedure TDbf.Translate(Src, Dest: PChar; ToOem: Boolean); {override virtual}
  1660. begin
  1661. if (Src <> nil) and (Dest<>nil) then begin
  1662. if ToOem then CharToOem(Src,Dest)
  1663. else OemToChar(Src,Dest);
  1664. end;
  1665. end;
  1666. {$else}
  1667. {$ifndef fpc}
  1668. function TDbf.Translate(Src, Dest: PChar; ToOem: Boolean): Integer; {override virtual}
  1669. begin
  1670. if (Src <> nil) and (Dest<>nil) then begin
  1671. if ToOem then CharToOem(Src,Dest)
  1672. else OemToChar(Src,Dest);
  1673. result:= StrLen(Dest);
  1674. end else result:=0;
  1675. end;
  1676. {$else}
  1677. function TDbf.Translate(Src, Dest: PChar; ToOem: Boolean): Integer; {override virtual}
  1678. begin
  1679. end;
  1680. {$endif}
  1681. {$endif}
  1682. procedure TDbf.ClearCalcFields(Buffer: PChar);
  1683. begin
  1684. FillChar(Buffer[_dbfFile.RecordSize], CalcFieldsSize, 0);
  1685. end;
  1686. procedure TDbf.InternalSetToRecord(Buffer: PChar); {override virtual abstract from TDataset}
  1687. var
  1688. prec:pDbfRecord;
  1689. begin
  1690. if Buffer=nil then exit;
  1691. prec:=pDbfRecord(Buffer);
  1692. _PhysicalRecno:=prec^.BookmarkData.RecNo;
  1693. _ResyncIndexes(Buffer);
  1694. end;
  1695. procedure TDbf._ResyncIndexes(Buffer: PChar);
  1696. var
  1697. i:integer;
  1698. lindex:TIndex;
  1699. begin
  1700. if _indexes.Count>0 then begin
  1701. _dbfFile.ReadRecord(_PhysicalRecno,_PrevBuffer);
  1702. for i:=0 to _indexes.Count-1 do begin
  1703. lindex:=TIndex(_indexes.Items[i]);
  1704. lindex.GotoKey(_physicalRecno,nil);
  1705. end;
  1706. end;
  1707. end;
  1708. function TDbf.IsCursorOpen: Boolean; {override virtual abstract from TDataset}
  1709. begin
  1710. result:=_IsCursorOpen;
  1711. end;
  1712. procedure TDbf.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); {override virtual abstract from TDataset}
  1713. var
  1714. prec:pDbfRecord;
  1715. begin
  1716. prec:=pDbfRecord(Buffer);
  1717. prec^.BookMarkFlag:=Value;
  1718. end;
  1719. procedure TDbf.SetBookmarkData(Buffer: PChar; Data: Pointer); {override virtual abstract from TDataset}
  1720. var
  1721. prec:pDbfRecord;
  1722. begin
  1723. prec:=pDbfRecord(Buffer);
  1724. prec^.BookMarkData:=pBookMarkData(Data)^;
  1725. end;
  1726. procedure TDbf.SetFieldData(Field: TField; Buffer: Pointer); {override virtual abstract from TDataset}
  1727. var
  1728. prec:pDbfRecord;
  1729. dst:pointer;
  1730. begin
  1731. if (Field.FieldNo >= 0) then begin
  1732. prec:=pDbfRecord(ActiveBuffer);
  1733. dst:=@prec^.DeletedFlag;
  1734. _dbfFile.SetFieldData(Field.FieldNo - 1,Field.DataType,Buffer,Dst);
  1735. end else begin { ***** fkCalculated, fkLookup ***** }
  1736. prec:=pDbfRecord(CalcBuffer);
  1737. dst:=@prec^.DeletedFlag;
  1738. Inc(integer(dst), GetRecordSize + Field.Offset);
  1739. Boolean(dst^) := LongBool(Buffer);
  1740. if Boolean(dst^) then begin
  1741. Inc(integer(dst), 1);
  1742. Move(Buffer^, dst^, Field.DataSize);
  1743. end;
  1744. end; { end of ***** fkCalculated, fkLookup ***** }
  1745. if not (State in [dsCalcFields, dsFilter, dsNewValue]) then begin
  1746. DataEvent(deFieldChange, Longint(Field));
  1747. end;
  1748. end;
  1749. // this function is just for the grid scrollbars
  1750. // it doesn't have to be perfectly accurate, but fast.
  1751. function TDbf.GetRecordCount: Integer; {override virtual}
  1752. begin
  1753. if _curIndex=nil then begin
  1754. result:=_dbfFile.RecordCount;
  1755. end else begin
  1756. result:=_curIndex.GuessRecordCount;
  1757. end;
  1758. end;
  1759. // this function is just for the grid scrollbars
  1760. // it doesn't have to be perfectly accurate, but fast.
  1761. function TDbf.GetRecNo: Integer; {override virtual}
  1762. begin
  1763. UpdateCursorPos;
  1764. if _curIndex=nil then begin
  1765. result:=_PhysicalRecno+1;
  1766. end else begin
  1767. result:=_curIndex.GuessRecNo;
  1768. end;
  1769. end;
  1770. procedure TDbf.SetRecNo(Value: Integer); {override virual}
  1771. begin
  1772. if _curIndex=nil then begin
  1773. _PhysicalRecno:=Value-1;
  1774. end else begin
  1775. //result:=_curIndex.GuessRecNo;
  1776. end;
  1777. Resync([rmExact]);
  1778. end;
  1779. procedure TDBf.DeleteIndex(const AName: string);
  1780. begin
  1781. // I must admit that is seems a bit expeditive.
  1782. // but I does implement this method because TTable does
  1783. DeleteFile(_GetPath + Name);
  1784. end;
  1785. procedure TDbf.CloseIndexFile(const IndexFileName: string);
  1786. var
  1787. lindex:tindex;
  1788. begin
  1789. lindex:=_GetIndex(IndexFileName);
  1790. if lindex<>nil then begin
  1791. lindex.Free;
  1792. _indexes.Delete(_indexes.IndexOf(lindex));
  1793. if _curindex = lindex then begin
  1794. _curindex:=nil;
  1795. resync([]);
  1796. end;
  1797. end;
  1798. end;
  1799. procedure TDbf.OpenIndexFile(AnIndexName:string);
  1800. var
  1801. lIndexFile:TIndexFile;
  1802. lIndex:TIndex;
  1803. begin
  1804. lindex:=_GetIndex(IndexName);
  1805. if lindex=nil then begin
  1806. IndexName:=lowercase(_GetPath + IndexName);
  1807. lIndexFile:=TIndexFile(GetPagedFile(IndexName));
  1808. if lIndexFile=nil then begin
  1809. lIndexFile:=TIndexFile.Create(IndexName,fmOpenReadWrite + fmShareDenyWrite);
  1810. end;
  1811. lIndex:=TIndex.Create(lIndexFile,0,false);
  1812. _Indexes.Add(lIndex);
  1813. lIndex.InitFieldDef(_DbfFile,lIndex._NdxHdr.KeyDesc);
  1814. end;
  1815. end;
  1816. (*
  1817. procedure TDbfFile.DbfFile_PackTable;
  1818. var
  1819. begin
  1820. end;
  1821. *)
  1822. {$ifdef fpc}
  1823. procedure TDbf.AddIndex(const AnIndexName, IndexFields: String; Options: TIndexOptions);
  1824. begin
  1825. AddIndex(indexName,IndexFields,options,'');
  1826. end;
  1827. {$endif}
  1828. {$ifdef DELPHI_3}
  1829. procedure TDbf.AddIndex(const IndexName, Fields: String; Options: TIndexOptions);
  1830. var
  1831. DescFields:string;
  1832. {$else}
  1833. {$ifndef fpc}
  1834. procedure TDbf.AddIndex(const IndexName, Fields: String; Options: TIndexOptions; const DescFields: String='');
  1835. var
  1836. {$else}
  1837. procedure TDbf.AddIndex(const AnIndexName, IndexFields: String; Options: TIndexOptions; const DescFields: String);
  1838. var
  1839. {$endif}
  1840. {$endif}
  1841. lfilename:string;
  1842. lIndexFile:TIndexFile;
  1843. lIndex:TIndex;
  1844. cur,thelast:integer;
  1845. begin
  1846. lfilename:=lowercase(_GetPath+IndexName);
  1847. lIndexFile:=TIndexFile(GetPagedFile(lfilename));
  1848. if lIndexFile<>nil then exit;
  1849. lIndexFile:=TIndexFile.Create(lfilename,fmCreate);
  1850. lIndex:=TIndex.Create(lIndexFile,0,true);
  1851. {$ifndef fpc}
  1852. lIndex.InitFieldDef(_DbfFile,Fields);
  1853. {$else}
  1854. lIndex.InitFieldDef(_DbfFile,IndexFields);
  1855. {$endif}
  1856. with lIndex._NdxHdr do begin
  1857. startpage:=1;
  1858. nbPage:=1;
  1859. keyformat:=#0;
  1860. keytype:='C';
  1861. dummy:=$5800;
  1862. keylen:=lindex._FieldLen;
  1863. nbkey:=(512-8) div (lindex._FieldLen+8);
  1864. keyreclen:=lindex._FieldLen+8;
  1865. Unique:=0;
  1866. KeyDesc[0]:=' ';
  1867. {$ifndef fpc}
  1868. StrLCopy(KeyDesc,PChar(UpperCase(Fields)),255);
  1869. {$else}
  1870. StrLCopy(KeyDesc,PChar(UpperCase(IndexFields)),255);
  1871. {$endif}
  1872. end;
  1873. lindex._IndexFile._Seek(lindex._RootPage);
  1874. lindex._IndexFile.Stream.Write(lindex._NdxHdr,SizeOf(lindex._NdxHdr));
  1875. cur:=0;
  1876. thelast:=_DbfFile.CalcRecordCount;
  1877. while cur<thelast do begin
  1878. _DbfFile.ReadRecord(cur, _PrevBuffer);
  1879. lIndex.Insert(cur,_PrevBuffer);
  1880. inc(cur);
  1881. end;
  1882. _Indexes.Add(lIndex);
  1883. end;
  1884. //==========================================================
  1885. //============ dbtfile
  1886. //==========================================================
  1887. constructor TDbtFile.Create(const FileName: string; Mode: Word; Ver:xBaseVersion);
  1888. begin
  1889. inherited Create(FileName,Mode);
  1890. _DbtVersion:=Ver;
  1891. if mode = fmCreate then begin
  1892. FillChar(_MemoHdr,sizeof(_MemoHdr),0);
  1893. end else begin
  1894. Stream.Position:=0;
  1895. Stream.read(_MemoHdr,SizeOf(_MemoHdr));
  1896. end;
  1897. HeaderSize:=0;
  1898. RecordSize:=_MemoHdr.BlockLen;
  1899. if (RecordSize=0) or ((RecordSize mod 128)<>0) then begin
  1900. _MemoHdr.BlockLen := $200;
  1901. RecordSize := $200;
  1902. end;
  1903. // Can you tell me why the header of dbase3 memo contains 1024 and it 512 ?
  1904. if _DbtVersion=xBaseIII then RecordSize:=512;
  1905. end;
  1906. procedure TDbtFile.ReadMemo(recno:Integer;Dst:TStream);
  1907. var
  1908. Buff:array[0..511] of char;
  1909. i,lsize:integer;
  1910. finish:boolean;
  1911. lastc:char;
  1912. begin
  1913. if recno=0 then Exit;
  1914. Stream.Position:= RecordSize * recno;
  1915. if _DbtVersion >= xBaseIV then begin // dBase4 memofiles
  1916. Stream.read(Buff[0],8);
  1917. if (Buff[0]=#$ff) and (Buff[1]=#$ff) and
  1918. (Buff[2]=#$08) and (Buff[3]=#$00) then begin
  1919. // dbase IV memo
  1920. lsize:=(PInteger(@Buff[4])^)-8;
  1921. end else begin
  1922. lsize:=0;
  1923. end;
  1924. repeat
  1925. if lsize>SizeOf(Buff) then begin
  1926. Stream.read(Buff,SizeOf(Buff));
  1927. Dst.Write(buff,SizeOf(Buff));
  1928. Dec(lsize,SizeOf(Buff));
  1929. end else if lsize>0 then begin
  1930. Stream.read(Buff,lsize);
  1931. Dst.Write(buff,lsize);
  1932. lsize:=0;
  1933. end;
  1934. until lsize=0;
  1935. end else begin
  1936. finish:=False;
  1937. Stream.read(Buff,SizeOf(Buff));
  1938. lastc:=#0;
  1939. repeat
  1940. for i:=0 to SizeOf(Buff)-2 do begin
  1941. if ((Buff[i]=#$1A) and
  1942. ((Buff[i+1]=#$1A) or ((i=0) and (lastc=#$1A))))
  1943. or (Buff[i]=#$0)
  1944. then begin
  1945. if i>0 then Dst.Write(buff,i);
  1946. finish:=True;
  1947. break;
  1948. end;
  1949. end;
  1950. if finish then Break;
  1951. Dst.Write(buff,512);
  1952. lastc:=Buff[511];
  1953. Stream.read(Buff,SizeOf(Buff));
  1954. until finish;
  1955. end;
  1956. Dst.Seek(0,0);
  1957. end;
  1958. procedure TDbtFile.WriteMemo(var MemoRecno:Integer;ReadSize:Integer;Src:TStream);
  1959. var
  1960. ByteBefore:Integer;
  1961. ByteAfter:Integer;
  1962. Buff:array[0..511] of char;
  1963. i:Integer;
  1964. c:Byte;
  1965. Append:Boolean;
  1966. begin
  1967. if _DbtVersion >= xBaseIV then begin // dBase4 memofiles
  1968. ByteBefore:=8;
  1969. ByteAfter:=0;
  1970. end else begin // stupid files
  1971. ByteBefore:=0;
  1972. ByteAfter:=2;
  1973. end;
  1974. if Src.Size = 0 then begin
  1975. MemoRecno:=0;
  1976. end else begin
  1977. if ((ByteBefore+Src.Size+ByteAfter+_MemoHdr.BlockLen-1) div _MemoHdr.BlockLen)
  1978. <= ((ReadSize+_MemoHdr.BlockLen-1) div _MemoHdr.BlockLen)
  1979. then begin
  1980. Append:=false;
  1981. //MemoRecno:=MemoRecno;
  1982. end else begin
  1983. Append:=True;
  1984. MemoRecno:=_MemoHdr.NextBlock;
  1985. if MemoRecno=0 then begin
  1986. _MemoHdr.NextBlock:=1;
  1987. MemoRecno:=1;
  1988. end;
  1989. end;
  1990. Stream.Seek(_MemoHdr.BlockLen * MemoRecno,0);
  1991. i:=Src.Position;
  1992. Src.Seek(0,0);
  1993. if ByteBefore=8 then begin
  1994. i:=$0008ffff;
  1995. Stream.Write(i,4);
  1996. i:=Src.Size+ByteBefore+ByteAfter;
  1997. Stream.Write(i,4);
  1998. end;
  1999. repeat
  2000. i:=Src.Read(buff,512);
  2001. if i=0 then break;
  2002. Inc(_MemoHdr.NextBlock);
  2003. Stream.Write(Buff,i);
  2004. until i<512;
  2005. if ByteAfter=2 then begin
  2006. c:=$1A;
  2007. Stream.Write(c,1);
  2008. Stream.Write(c,1);
  2009. end;
  2010. if Append then begin
  2011. Stream.Seek(0,0);
  2012. Stream.Write(_MemoHdr,SizeOf(_MemoHdr))
  2013. end;
  2014. end;
  2015. end;
  2016. //==========================================================
  2017. //============ TIndexFile
  2018. //==========================================================
  2019. constructor TIndexFile.Create(const FileName: string; Mode: Word);
  2020. var
  2021. ext:string;
  2022. i:Integer;
  2023. begin
  2024. inherited Create(FileName,Mode);
  2025. HeaderSize:=0;
  2026. RecordSize:=512;
  2027. ext:=ExtractFileExt(FileName);
  2028. if (ext='.mdx') then begin
  2029. _IndexVersion:=xBaseIV;
  2030. if Mode = fmCreate then begin
  2031. FillChar(_MdxHdr,sizeof(_MdxHdr),0);
  2032. end else begin
  2033. Stream.read(_MdxHdr,SizeOf(_MdxHdr));
  2034. end;
  2035. for i:= 0 to _MdxHdr.TagUsed-1 do begin
  2036. // Stream.Position :=544 + i * _MdxHdr.TagSize;
  2037. // Stream.read(lMdxTag,SizeOf(rMdxTag));
  2038. // lIndex:=TIndex.Create(Self,lMdxTag.pageno);
  2039. // _Indexes.Add(lIndex);
  2040. // if i=0 then lIndex.ReadPage(lIndex._NdxHdr.startpage);
  2041. end;
  2042. end else begin
  2043. _IndexVersion:=xBaseIII;
  2044. (*
  2045. _IndexFile._Seek(Pos);
  2046. _IndexFile.Stream.Read(_NdxHdr,SizeOf(_NdxHdr));
  2047. _Root:=TIndexPage.Create(Self);
  2048. _Root.SetPageNo(_NdxHdr.startpage);
  2049. lPos:=_Root;
  2050. _nblevel:=1;
  2051. repeat
  2052. lPos.LocalFirst;
  2053. if lPos.Entry._LowerPage=0 then break;
  2054. inc(_nblevel);
  2055. lChild:=TIndexPage.Create(Self);
  2056. lChild._UpperLevel:=lPos;
  2057. lPos._LowerLevel:=lChild;
  2058. lChild.SetPageNo(lPos.Entry._LowerPage);
  2059. lPos:=lChild;
  2060. until false;
  2061. _Spare:=TIndexPage.Create(Self);
  2062. // _Field:=_IndexFile._Dbf.FindField(_NdxHdr.KeyDesc);
  2063. First;
  2064. *)
  2065. end;
  2066. end;
  2067. destructor TIndexFile.Destroy;
  2068. begin
  2069. inherited;
  2070. end;
  2071. //==========================================================
  2072. //============ TIndexPage
  2073. //==========================================================
  2074. constructor TIndexPage.Create(Parent:TIndex);
  2075. begin
  2076. _LowerLevel:=nil;
  2077. _UpperLevel:=nil;
  2078. _Index:=Parent;
  2079. _PageNo:=-1;
  2080. _EntryNo:=-1;
  2081. end;
  2082. destructor TIndexPage.Destroy;
  2083. begin
  2084. if _LowerLevel<>nil then _LowerLevel.Free;
  2085. end;
  2086. function TIndexPage.GetPEntry(EntryNo:integer):PNdxEntry;
  2087. begin
  2088. Result:=PNdxentry(@_PageBuff.Entries[_Index._NdxHdr.keyreclen*entryno]);
  2089. end;
  2090. function TIndexPage.LocalInsert(Recno:integer; Buffer:Pchar;LowerPage:integer):boolean;
  2091. var
  2092. src,dst:pointer;
  2093. siz:integer;
  2094. begin
  2095. if _PageBuff.NbEntries < _Index._NdxHdr.nbkey then begin
  2096. src:=Entry;
  2097. dst:=GetPEntry(_EntryNo+1);
  2098. siz:=(_PageBuff.NbEntries - _EntryNo)
  2099. * _Index._NdxHdr.keyreclen + 8;
  2100. Move(Src^, Dst^, Siz);
  2101. inc(_PageBuff.NbEntries);
  2102. SetEntry(Recno,Buffer,LowerPage);
  2103. Write;
  2104. Result:=true;
  2105. end else begin
  2106. Result:=false;
  2107. end;
  2108. end;
  2109. function TIndexPage.LocalDelete:boolean;
  2110. var
  2111. src,dst:pointer;
  2112. siz:integer;
  2113. begin
  2114. if _PageBuff.NbEntries >=0 then begin
  2115. if _EntryNo<_PageBuff.NbEntries then begin
  2116. src:=GetPEntry(_EntryNo+1);
  2117. dst:=Entry;
  2118. siz:=(_PageBuff.NbEntries - _EntryNo - 1)
  2119. * _Index._NdxHdr.keyreclen + 8;
  2120. Move(Src^, Dst^, Siz);
  2121. end;
  2122. dec(_PageBuff.NbEntries);
  2123. Write;
  2124. if ((_PageBuff.NbEntries=0) and (_lowerlevel=nil))
  2125. or (_PageBuff.NbEntries<0) then begin
  2126. if _UpperLevel<>nil then begin
  2127. _UpperLevel.LocalDelete;
  2128. end;
  2129. end else if (_EntryNo>LastEntryNo) then begin
  2130. SetEntryNo(LastEntryNo); // We just removed the last on this page.
  2131. if (_UpperLevel<>nil) then begin
  2132. _UpperLevel.SetEntry(0,Entry^.CKey,_PageNo);
  2133. end;
  2134. end;
  2135. Result:=true;
  2136. end else begin
  2137. Result:=false;
  2138. end;
  2139. end;
  2140. function TIndexPage.LastEntryNo:integer;
  2141. begin
  2142. if (_LowerLevel=nil) then begin
  2143. result := _PageBuff.NbEntries - 1;
  2144. end else begin
  2145. result := _PageBuff.NbEntries;
  2146. end;
  2147. end;
  2148. procedure TIndexPage.LocalFirst;
  2149. begin
  2150. SetEntryNo(0);
  2151. end;
  2152. procedure TIndexPage.LocalLast;
  2153. begin
  2154. SetEntryNo(LastEntryNo);
  2155. end;
  2156. function TIndexPage.LocalPrev:boolean;
  2157. begin
  2158. if _EntryNo>0 then begin
  2159. SetEntryNo(_EntryNo-1);
  2160. Result:=true;
  2161. end else begin
  2162. Result:=false;
  2163. end;
  2164. end;
  2165. function TIndexPage.LocalNext:boolean;
  2166. begin
  2167. if (_EntryNo<LastEntryNo) then begin
  2168. SetEntryNo(_EntryNo+1);
  2169. Result:=true;
  2170. end else begin
  2171. Result:=false;
  2172. end;
  2173. end;
  2174. procedure TIndexPage.First;
  2175. begin
  2176. LocalFirst;
  2177. if (_LowerLevel<>nil) then LowerLevel.First;
  2178. end;
  2179. procedure TIndexPage.Last;
  2180. begin
  2181. LocalLast;
  2182. if (_LowerLevel<>nil) then LowerLevel.Last;
  2183. end;
  2184. function TIndexPage.Prev:boolean;
  2185. begin
  2186. if (_LowerLevel<>nil) and LowerLevel.Prev then begin
  2187. result:=true;
  2188. exit;
  2189. end;
  2190. Result:=LocalPrev;
  2191. if Result and (Entry^._LowerPage>0) then LowerLevel.Last;
  2192. end;
  2193. function TIndexPage.Next:boolean;
  2194. begin
  2195. if (_LowerLevel<>nil) and LowerLevel.next then begin
  2196. result:=true;
  2197. exit;
  2198. end;
  2199. Result:=LocalNext;
  2200. if Result and (Entry^._LowerPage>0) then LowerLevel.First;
  2201. end;
  2202. function TIndexPage.FindNearest(Recno:integer; Key:pchar):integer;
  2203. var
  2204. cmpres:integer;
  2205. v1,v2:double;
  2206. p:TIndexPage;
  2207. begin
  2208. Result:=-1;
  2209. if @Key=nil then begin
  2210. Exit;
  2211. end;
  2212. SetEntryNo(0);
  2213. while _EntryNo<=_PageBuff.NbEntries do begin
  2214. if _EntryNo=_PageBuff.NbEntries then break;
  2215. if _Index._NdxHdr.keytype='C' then begin
  2216. cmpres:=StrLIComp(PChar(Key),Entry^.CKey,_Index._FieldLen);
  2217. end else begin
  2218. // Numeric field... to do
  2219. v1:=PDouble(Key)^;
  2220. v2:=Entry^.NKey;
  2221. if v1>v2 then cmpres:=1
  2222. else if v1<v2 then cmpres:=-1
  2223. else cmpres:=0;
  2224. end;
  2225. if cmpres=0 then begin
  2226. if _LowerLevel=nil then begin
  2227. if (Entry^.RecNo=Recno) then begin
  2228. result:=0;
  2229. Exit;
  2230. end else if (Entry^.Recno>Recno) then begin
  2231. result:=-1;
  2232. Exit;
  2233. end;
  2234. end else begin
  2235. p:=self;
  2236. while p._LowerLevel<>nil do begin
  2237. p:=p.LowerLevel;
  2238. p.LocalLast;
  2239. end;
  2240. if (p.Entry^.Recno>=Recno) then begin
  2241. result:=-1;
  2242. Exit;
  2243. end;
  2244. end;
  2245. end else if cmpres<0 then begin
  2246. result:=-1;
  2247. exit;
  2248. end;
  2249. SetEntryNo(_EntryNo+1);
  2250. end;
  2251. result:=1;
  2252. Exit;
  2253. end;
  2254. procedure TIndexPage.SetEntry(Recno:Integer; key:PChar; LowerPage:integer);
  2255. begin
  2256. assert((_EntryNo>=0) and (_EntryNo<=_PageBuff.NbEntries));
  2257. if (_EntryNo=self._PageBuff.NbEntries) then begin
  2258. if (_UpperLevel<>nil) then begin
  2259. _UpperLevel.SetEntry(0,key,Self._PageNo);
  2260. end;
  2261. end else begin
  2262. if _Index._NdxHdr.keytype='C' then begin
  2263. mymove(key,Entry^.CKey,_Index._NdxHdr.keylen);
  2264. end else begin
  2265. Entry^.NKey:=PDouble(key)^;
  2266. end;
  2267. end;
  2268. Entry^.RecNo:=RecNo;
  2269. Entry^._LowerPage:=LowerPage;
  2270. Write;
  2271. end;
  2272. function TIndexPage.LowerLevel : TIndexPage;
  2273. begin
  2274. if (_LowerLevel<>nil) and (_LowerLevel._PageNo<>Entry^._LowerPage) then begin
  2275. _LowerLevel.SetPageNo(Entry^._LowerPage);
  2276. end;
  2277. result:=_LowerLevel;
  2278. end;
  2279. function TIndexPage.Insert(Recno:Integer; Buffer:PChar; LowerPage:integer):boolean;
  2280. var
  2281. src,dst:PNdxEntry;
  2282. siz:integer;
  2283. split,old_entry:integer;
  2284. lSpare:TIndexPage;
  2285. begin
  2286. if not LocalInsert(recno,buffer,lowerpage) then begin
  2287. // The entry is FULL so we will split this page
  2288. // 1 - Check parent exist
  2289. if _UpperLevel=nil then begin
  2290. AddNewLevel;
  2291. end;
  2292. old_entry:=_EntryNo;
  2293. split:=_EntryNo;
  2294. if split < _Index._NdxHdr.nbkey div 2 then begin
  2295. split:=_Index._NdxHdr.nbkey div 2;
  2296. end;
  2297. lSpare:=TIndexPage.Create(_Index);
  2298. try
  2299. // 2 - Create new page with first part
  2300. inc(_Index._NdxHdr.nbPage);
  2301. lSpare._PageNo:=_Index._NdxHdr.nbPage;
  2302. _Index._IndexFile._Seek(_Index._RootPage);
  2303. _Index._IndexFile.Stream.WriteBuffer (_Index._NdxHdr, SizeOf(_Index._NdxHdr));
  2304. if _lowerlevel=nil then begin
  2305. lSpare._PageBuff.NbEntries:=split;
  2306. end else begin
  2307. lSpare._PageBuff.NbEntries:=split-1;
  2308. end;
  2309. siz:=split*_Index._NdxHdr.keyreclen+8;
  2310. src:=@_PageBuff.Entries;
  2311. dst:=@lSpare._PageBuff.Entries;
  2312. Move(src^,dst^,siz);
  2313. lSpare.Write;
  2314. // 3 - Keep only end-part in this page
  2315. siz:=(_PageBuff.NbEntries-Split);
  2316. _PageBuff.NbEntries:=siz;
  2317. siz:=siz*_Index._NdxHdr.keyreclen+8;
  2318. SetEntryNo(split);
  2319. src:=Entry;
  2320. SetEntryNo(0);
  2321. dst:=Entry;
  2322. Move(src^,dst^,siz);
  2323. // 3 - Update upper level
  2324. lSpare.SetEntryNo(split-1);
  2325. _UpperLevel.Insert(0,lSpare.Entry^.CKey,lSpare._PageNo);
  2326. // We just need to go on inserted record now
  2327. if old_entry>=split then begin
  2328. _UpperLevel.LocalNext;
  2329. SetEntryNo(old_entry - split);
  2330. LocalInsert(Recno,Buffer,LowerPage);
  2331. lSpare.Write;
  2332. end else begin
  2333. lSpare.SetEntryNo(old_entry);
  2334. lSpare.LocalInsert(Recno,Buffer,LowerPage);
  2335. Write;
  2336. end;
  2337. finally
  2338. lspare.free;
  2339. end;
  2340. end;
  2341. Result:=true;
  2342. end;
  2343. function TIndexPage.Delete:boolean;
  2344. begin
  2345. Result:=LocalDelete;
  2346. end;
  2347. procedure TIndexPage.SetPageNo(page:Integer);
  2348. begin
  2349. if (_PageNo<>page) and (page>0) then begin
  2350. _Index._IndexFile.ReadRecord(Page,@_PageBuff);
  2351. _PageNo:=page;
  2352. _EntryNo:=-1;
  2353. end;
  2354. end;
  2355. procedure TIndexPage.AddNewLevel;
  2356. var
  2357. lNewPage:TIndexPage;
  2358. begin
  2359. lNewPage:=TIndexPage.Create(_Index);
  2360. inc(_Index._NdxHdr.nbPage);
  2361. lNewPage._PageNo:= _Index._NdxHdr.nbPage;
  2362. _Index._NdxHdr.startpage:= _Index._NdxHdr.nbPage;
  2363. _Index._IndexFile._Seek(_Index._RootPage);
  2364. _Index._IndexFile.Stream.WriteBuffer (_Index._NdxHdr, SizeOf(_Index._NdxHdr));
  2365. lNewPage._PageBuff.NbEntries:=0;
  2366. lNewPage._UpperLevel:=nil;
  2367. lNewPage._LowerLevel:=_Index._Root;
  2368. lNewPage.SetEntryNo(0);
  2369. lNewPage.SetEntry(0,nil,_PageNo);
  2370. _Index._Root._UpperLevel:=lNewPage;
  2371. _Index._Root:=lNewPage;
  2372. lNewPage:=nil;
  2373. end;
  2374. procedure TIndexPage.Write;
  2375. begin
  2376. _Index._IndexFile.WriteRecord(_PageNo,@_PageBuff);
  2377. end;
  2378. procedure TIndexPage.SetEntryNo(entryno:Integer);
  2379. begin
  2380. if (_EntryNo<>entryno) then begin
  2381. _EntryNo:=entryno;
  2382. if _EntryNo>=0 then Entry:=PNdxentry(@_PageBuff.Entries[_Index._NdxHdr.keyreclen*entryno]);
  2383. end;
  2384. end;
  2385. procedure TIndexPage.WritePage(Page:integer);
  2386. begin
  2387. _Index._IndexFile.WriteRecord(Page,@_PageBuff);
  2388. end;
  2389. //==========================================================
  2390. //============ TIndex
  2391. //==========================================================
  2392. constructor TIndex.Create(Parent:TIndexFile; RootPage:integer;CreateIt:boolean);
  2393. var
  2394. lPos:TIndexPage;
  2395. lChild:TIndexPage;
  2396. begin
  2397. _RootPage:=RootPage;
  2398. _IndexFile:=Parent;
  2399. //_IndexOrder:=TList.Create;
  2400. if CreateIt then begin
  2401. FillChar(_NdxHdr,sizeof(_NdxHdr),0);
  2402. _NdxHdr.startpage:=1;
  2403. _NdxHdr.nbPage:=2;
  2404. _NdxHdr.keyformat:=#0;
  2405. _NdxHdr.keytype:='C';
  2406. _IndexFile._Seek(RootPage);
  2407. _IndexFile.Stream.Write(_NdxHdr,SizeOf(_NdxHdr));
  2408. _FieldPos := 0;
  2409. _FieldLen := 0;
  2410. end else begin
  2411. _IndexFile._Seek(RootPage);
  2412. _IndexFile.Stream.Read(_NdxHdr,SizeOf(_NdxHdr));
  2413. end;
  2414. _Root:=TIndexPage.Create(Self);
  2415. _Root.SetPageNo(_NdxHdr.startpage);
  2416. lPos:=_Root;
  2417. _nblevel:=1;
  2418. repeat
  2419. lPos.LocalFirst;
  2420. if lPos.Entry^._LowerPage=0 then break;
  2421. inc(_nblevel);
  2422. lChild:=TIndexPage.Create(Self);
  2423. lChild._UpperLevel:=lPos;
  2424. lPos._LowerLevel:=lChild;
  2425. lChild.SetPageNo(lPos.Entry^._LowerPage);
  2426. lPos:=lChild;
  2427. until false;
  2428. inc(_IndexFile._cntuse);
  2429. First;
  2430. end;
  2431. destructor TIndex.Destroy;
  2432. begin
  2433. _IndexFile.Release;
  2434. _Root.Free;
  2435. end;
  2436. function TIndex.Find(Recno:integer; Buffer:PChar; var pPos:TIndexPage):integer;
  2437. var
  2438. res:integer;
  2439. begin
  2440. pPos:=_Root;
  2441. repeat
  2442. res:=pPos.FindNearest(Recno,Buffer);
  2443. if res<>0 then begin
  2444. if pPos.Entry^._LowerPage<>0 then begin
  2445. pPos:=pPos.LowerLevel;
  2446. res:=2;
  2447. end;
  2448. end;
  2449. until res<>2;
  2450. Result:=res;
  2451. end;
  2452. procedure TIndex.Update(Recno: integer; PrevBuffer,NewBuffer: PChar);
  2453. var
  2454. lPos:TIndexPage;
  2455. begin
  2456. if _FieldLen=0 then exit;
  2457. inc(PrevBuffer,_FieldPos);
  2458. inc(NewBuffer,_FieldPos);
  2459. if StrLIComp(PrevBuffer,NewBuffer,_FieldLen)<>0 then begin
  2460. Delete;
  2461. Find(Recno+1,NewBuffer,lPos);
  2462. lPos.Insert(Recno+1,NewBuffer,0);
  2463. end;
  2464. end;
  2465. procedure TIndex.Insert(Recno:integer; Buffer:PChar);
  2466. var
  2467. lPos:TIndexPage;
  2468. begin
  2469. if _FieldLen=0 then exit;
  2470. inc(Buffer,_FieldPos);
  2471. Find(Recno+1,Buffer,lPos);
  2472. lPos.Insert(Recno+1,Buffer,0);
  2473. end;
  2474. function TIndex.Delete:boolean;
  2475. var
  2476. lPos:TIndexPage;
  2477. begin
  2478. lpos:=_root;
  2479. while lpos._LowerLevel<>nil do begin
  2480. lPos:=lPos.LowerLevel;
  2481. end;
  2482. lPos.Delete;
  2483. Result:=true;
  2484. end;
  2485. function TIndex.Pos:TIndexPage;
  2486. var
  2487. p:TIndexPage;
  2488. begin
  2489. p:=_Root;
  2490. while p.Entry^._LowerPage>0 do begin
  2491. p:=p.LowerLevel;
  2492. end;
  2493. result:=p;
  2494. end;
  2495. procedure TIndex.First;
  2496. begin
  2497. _Root.First;
  2498. dec(Pos._EntryNo);
  2499. end;
  2500. procedure TIndex.Last;
  2501. begin
  2502. _Root.Last;
  2503. inc(Pos._EntryNo);
  2504. end;
  2505. function TIndex.Prev:boolean;
  2506. begin
  2507. result:=_Root.Prev;
  2508. end;
  2509. function TIndex.Next:boolean;
  2510. begin
  2511. result:=_Root.Next;
  2512. end;
  2513. (*
  2514. procedure TIndex.SetRecNo(Value: Integer);
  2515. var
  2516. pos:integer;
  2517. p:TIndexPage;
  2518. i:integer;
  2519. ldiv:integer;
  2520. begin
  2521. p:=_Root;
  2522. ldiv:=1;
  2523. while p.Entry^._LowerPage>0 do begin
  2524. ldiv:=ldiv*(_NdxHdr.nbkey+1);
  2525. p:=p._LowerLevel;
  2526. end;
  2527. pos:=value div ldiv;
  2528. p:=_Root;
  2529. while p.Entry^._LowerPage>0 do begin
  2530. p._EntryNo:=pos;
  2531. value:=value - pos * (_NdxHdr.nbkey+1);
  2532. ldiv:=ldiv div (_NdxHdr.nbkey+1);
  2533. pos:=value div ldiv;
  2534. p:=p._LowerLevel;
  2535. end;
  2536. {
  2537. pos:=1;
  2538. First;
  2539. While pos<value do begin
  2540. if Next = false then break;
  2541. inc(pos);
  2542. end;
  2543. }
  2544. end;
  2545. *)
  2546. function TIndex.GuessRecordCount: Integer;
  2547. var
  2548. lPos:TIndexPage;
  2549. nbrecord:integer;
  2550. begin
  2551. // I just read first level and Guess an approximate record count...
  2552. nbrecord:=_Root._PageBuff.NbEntries;
  2553. lPos:=_Root.LowerLevel;
  2554. while lpos<>nil do begin
  2555. nbrecord:=nbrecord*(_NdxHdr.nbkey+1);
  2556. lPos:=lPos.LowerLevel;
  2557. end;
  2558. result:=nbrecord;
  2559. end;
  2560. function TIndex.GuessRecNo:Integer;
  2561. var
  2562. p:TIndexPage;
  2563. begin
  2564. p:=_Root;
  2565. result:=p._EntryNo;
  2566. while p.Entry^._LowerPage>0 do begin
  2567. p:=p.LowerLevel;
  2568. Result:=Result*(_NdxHdr.nbkey+1) + p._EntryNo;
  2569. end;
  2570. end;
  2571. function TIndex.GetRealRecNo:integer;
  2572. var
  2573. ippos : TIndexPage;
  2574. begin
  2575. ippos:=_Root;
  2576. while ippos._LowerLevel<>nil do begin
  2577. ippos:=pos.LowerLevel;
  2578. end;
  2579. if (ippos._EntryNo<0) or (ippos._EntryNo>=ippos._PageBuff.NbEntries) then Result:=-1
  2580. else Result:=ippos.Entry^.RecNo-1;
  2581. end;
  2582. procedure TIndex.GotoKey(recno:integer; buffer:pchar);
  2583. begin
  2584. // very temporary implementation
  2585. // could definitely be a bit faster.
  2586. _Root.First;
  2587. repeat
  2588. if self.Pos.Entry^.RecNo=(recno+1) then begin
  2589. exit;
  2590. end;
  2591. until Next=false;
  2592. end;
  2593. procedure TIndex.InitFieldDef(dbfFile:TDbfFile;FieldDesc:string);
  2594. var
  2595. FieldInfo:TMyFieldInfo;
  2596. begin
  2597. FieldInfo:=DbfFile.GetFieldInfo(FieldDesc);
  2598. if FieldInfo<>nil then begin
  2599. _FieldPos:=FieldInfo.Offset;
  2600. _FieldLen:=FieldInfo.Size;
  2601. end;
  2602. end;
  2603. //==========================================================
  2604. //============ initialization
  2605. //==========================================================
  2606. {$ifndef fpc}
  2607. type
  2608. TTableNameProperty = class(TStringProperty)
  2609. public
  2610. procedure Edit; override;
  2611. function GetAttributes: TPropertyAttributes; override;
  2612. end;
  2613. procedure TTableNameProperty.Edit; {override;}
  2614. var
  2615. FileOpen: TOpenDialog;
  2616. Dbf: TDbf;
  2617. begin
  2618. FileOpen := TOpenDialog.Create(Application);
  2619. try
  2620. with fileopen do begin
  2621. Dbf:=GetComponent(0) as TDbf;
  2622. Filename := Dbf.DesignTimePath + GetValue;
  2623. Filter := 'Dbf table|*.dbf';
  2624. if Execute then begin
  2625. SetValue(ExtractFilename(Filename));
  2626. Dbf.DesignTimePath:=ExtractFilePath(Filename);
  2627. end;
  2628. end;
  2629. finally
  2630. Fileopen.free;
  2631. end;
  2632. end;
  2633. function TTableNameProperty.GetAttributes: TPropertyAttributes; {override;}
  2634. begin
  2635. Result := [paDialog, paRevertable];
  2636. end;
  2637. type
  2638. TRunTimePathProperty = class(TStringProperty)
  2639. end;
  2640. TDesignTimePathProperty = class(TStringProperty)
  2641. end;
  2642. //==========================================================
  2643. //============ initialization
  2644. //==========================================================
  2645. procedure Register;
  2646. begin
  2647. RegisterComponents('Exemples', [TDbf]);
  2648. RegisterPropertyEditor(TypeInfo(string), TDbf, 'TableName', TTableNameProperty);
  2649. RegisterPropertyEditor(TypeInfo(string), TDbf, 'RunTimePath', TRunTimePathProperty);
  2650. RegisterPropertyEditor(TypeInfo(string), TDbf, 'DesignTimePath', TDesignTimePathProperty);
  2651. // RegisterPropertyEditor(TypeInfo(TStrings), TDbf, 'IndexFiles', TIndexFilesProperty);
  2652. // ShowMessage(ToolServices.GetProjectName);
  2653. end;
  2654. {$endif fpc}
  2655. initialization
  2656. _PagedFiles := TList.Create;
  2657. tDbf_TrimFields := true;
  2658. finalization
  2659. _PagedFiles.free;
  2660. end.