dbf.pas 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901
  1. unit dbf;
  2. { design info in dbf_reg.pas }
  3. interface
  4. {$I dbf_common.inc}
  5. uses
  6. Classes,
  7. Db,
  8. dbf_common,
  9. dbf_dbffile,
  10. dbf_parser,
  11. dbf_prsdef,
  12. dbf_cursor,
  13. dbf_fields,
  14. dbf_pgfile,
  15. dbf_idxfile;
  16. // If you got a compilation error here or asking for dsgnintf.pas, then just add
  17. // this file in your project:
  18. // dsgnintf.pas in 'C: \Program Files\Borland\Delphi5\Source\Toolsapi\dsgnintf.pas'
  19. type
  20. //====================================================================
  21. pBookmarkData = ^TBookmarkData;
  22. TBookmarkData = record
  23. PhysicalRecNo: Integer;
  24. end;
  25. pDbfRecord = ^TDbfRecordHeader;
  26. TDbfRecordHeader = record
  27. BookmarkData: TBookmarkData;
  28. BookmarkFlag: TBookmarkFlag;
  29. SequentialRecNo: Integer;
  30. DeletedFlag: Char;
  31. end;
  32. //====================================================================
  33. TDbf = class;
  34. //====================================================================
  35. TDbfStorage = (stoMemory,stoFile);
  36. TDbfOpenMode = (omNormal,omAutoCreate,omTemporary);
  37. TDbfLanguageAction = (laReadOnly, laForceOEM, laForceANSI, laDefault);
  38. TDbfTranslationMode = (tmNoneAvailable, tmNoneNeeded, tmSimple, tmAdvanced);
  39. TDbfFileName = (dfDbf, dfMemo, dfIndex);
  40. //====================================================================
  41. TDbfFileNames = set of TDbfFileName;
  42. //====================================================================
  43. TCompareRecordEvent = procedure(Dbf: TDbf; var Accept: Boolean) of object;
  44. TTranslateEvent = function(Dbf: TDbf; Src, Dest: PChar; ToOem: Boolean): Integer of object;
  45. TLanguageWarningEvent = procedure(Dbf: TDbf; var Action: TDbfLanguageAction) of object;
  46. TConvertFieldEvent = procedure(Dbf: TDbf; DstField, SrcField: TField) of object;
  47. TBeforeAutoCreateEvent = procedure(Dbf: TDbf; var DoCreate: Boolean) of object;
  48. //====================================================================
  49. // TDbfBlobStream keeps a reference count to number of references to
  50. // this instance. Only if FRefCount reaches zero, then the object will be
  51. // destructed. AddReference `clones' a reference.
  52. // This allows the VCL to use Free on the object to `free' that
  53. // particular reference.
  54. TDbfBlobStream = class(TMemoryStream)
  55. private
  56. FBlobField: TBlobField;
  57. FMode: TBlobStreamMode;
  58. FDirty: boolean; { has possibly modified data, needs to be written }
  59. FMemoRecNo: Integer;
  60. { -1 : invalid contents }
  61. { 0 : clear, no contents }
  62. { >0 : data from page x }
  63. FReadSize: Integer;
  64. FRefCount: Integer;
  65. function GetTransliterate: Boolean;
  66. procedure Translate(ToOem: Boolean);
  67. procedure SetMode(NewMode: TBlobStreamMode);
  68. public
  69. constructor Create(FieldVal: TField);
  70. destructor Destroy; override;
  71. function AddReference: TDbfBlobStream;
  72. procedure FreeInstance; override;
  73. procedure Cancel;
  74. procedure Commit;
  75. property Dirty: boolean read FDirty;
  76. property Transliterate: Boolean read GetTransliterate;
  77. property MemoRecNo: Integer read FMemoRecNo write FMemoRecNo;
  78. property ReadSize: Integer read FReadSize write FReadSize;
  79. property Mode: TBlobStreamMode write SetMode;
  80. property BlobField: TBlobField read FBlobField;
  81. end;
  82. //====================================================================
  83. TDbfIndexDefs = class(TCollection)
  84. public
  85. FOwner: TDbf;
  86. private
  87. function GetItem(N: Integer): TDbfIndexDef;
  88. procedure SetItem(N: Integer; Value: TDbfIndexDef);
  89. protected
  90. function GetOwner: TPersistent; override;
  91. public
  92. constructor Create(AOwner: TDbf);
  93. function Add: TDbfIndexDef;
  94. function GetIndexByName(const Name: string): TDbfIndexDef;
  95. function GetIndexByField(const Name: string): TDbfIndexDef;
  96. procedure Update; {$ifdef SUPPORT_REINTRODUCE} reintroduce; {$endif}
  97. property Items[N: Integer]: TDbfIndexDef read GetItem write SetItem; default;
  98. end;
  99. //====================================================================
  100. TDbfMasterLink = class(TDataLink)
  101. private
  102. FDetailDataSet: TDbf;
  103. FParser: TDbfParser;
  104. FFieldNames: string;
  105. FValidExpression: Boolean;
  106. FOnMasterChange: TNotifyEvent;
  107. FOnMasterDisable: TNotifyEvent;
  108. function GetFieldsVal: PChar;
  109. procedure SetFieldNames(const Value: string);
  110. protected
  111. procedure ActiveChanged; override;
  112. procedure CheckBrowseMode; override;
  113. procedure LayoutChanged; override;
  114. procedure RecordChanged(Field: TField); override;
  115. public
  116. constructor Create(ADataSet: TDbf);
  117. destructor Destroy; override;
  118. property FieldNames: string read FFieldNames write SetFieldNames;
  119. property ValidExpression: Boolean read FValidExpression write FValidExpression;
  120. property FieldsVal: PChar read GetFieldsVal;
  121. property Parser: TDbfParser read FParser;
  122. property OnMasterChange: TNotifyEvent read FOnMasterChange write FOnMasterChange;
  123. property OnMasterDisable: TNotifyEvent read FOnMasterDisable write FOnMasterDisable;
  124. end;
  125. //====================================================================
  126. PDbfBlobList = ^TDbfBlobList;
  127. TDbfBlobList = array[0..MaxListSize-1] of TDbfBlobStream;
  128. //====================================================================
  129. TDbf = class(TDataSet)
  130. private
  131. FDbfFile: TDbfFile;
  132. FCursor: TVirtualCursor;
  133. FOpenMode: TDbfOpenMode;
  134. FStorage: TDbfStorage;
  135. FMasterLink: TDbfMasterLink;
  136. FParser: TDbfParser;
  137. FBlobStreams: PDbfBlobList;
  138. FUserStream: TStream; // user stream to open
  139. FTableName: string; // table path and file name
  140. FRelativePath: string;
  141. FAbsolutePath: string;
  142. FIndexName: string;
  143. FReadOnly: Boolean;
  144. FFilterBuffer: PChar;
  145. FTempBuffer: PChar;
  146. FEditingRecNo: Integer;
  147. FLanguageID: Byte;
  148. FTableLevel: Integer;
  149. FExclusive: Boolean;
  150. FShowDeleted: Boolean;
  151. FUseFloatFields: Boolean;
  152. FPosting: Boolean;
  153. FDisableResyncOnPost: Boolean;
  154. FTempExclusive: Boolean;
  155. FInCopyFrom: Boolean;
  156. FStoreDefs: Boolean;
  157. FCopyDateTimeAsString: Boolean;
  158. FFindRecordFilter: Boolean;
  159. FIndexFile: TIndexFile;
  160. FDateTimeHandling: TDateTimeHandling;
  161. FTranslationMode: TDbfTranslationMode;
  162. FIndexDefs: TDbfIndexDefs;
  163. FBeforeAutoCreate: TBeforeAutoCreateEvent;
  164. FOnTranslate: TTranslateEvent;
  165. FOnLanguageWarning: TLanguageWarningEvent;
  166. FOnLocaleError: TDbfLocaleErrorEvent;
  167. FOnIndexMissing: TDbfIndexMissingEvent;
  168. FOnCompareRecord: TNotifyEvent;
  169. FOnCopyDateTimeAsString: TConvertFieldEvent;
  170. function GetIndexName: string;
  171. function GetVersion: string;
  172. function GetPhysicalRecNo: Integer;
  173. function GetLanguageStr: string;
  174. function GetCodePage: Cardinal;
  175. function GetExactRecordCount: Integer;
  176. function GetPhysicalRecordCount: Integer;
  177. function GetKeySize: Integer;
  178. function GetMasterFields: string;
  179. function FieldDefsStored: Boolean;
  180. procedure SetIndexName(AIndexName: string);
  181. procedure SetDbfIndexDefs(const Value: TDbfIndexDefs);
  182. procedure SetFilePath(const Value: string);
  183. procedure SetTableName(const S: string);
  184. procedure SetVersion(const S: string);
  185. procedure SetLanguageID(NewID: Byte);
  186. procedure SetDataSource(Value: TDataSource);
  187. procedure SetMasterFields(const Value: string);
  188. procedure SetTableLevel(const NewLevel: Integer);
  189. procedure SetPhysicalRecNo(const NewRecNo: Integer);
  190. procedure MasterChanged(Sender: TObject);
  191. procedure MasterDisabled(Sender: TObject);
  192. procedure DetermineTranslationMode;
  193. procedure CheckMasterRange;
  194. procedure UpdateRange;
  195. procedure SetShowDeleted(Value: Boolean);
  196. procedure GetFieldDefsFromDbfFieldDefs;
  197. procedure InitDbfFile(FileOpenMode: TPagedFileMode);
  198. function ParseIndexName(const AIndexName: string): string;
  199. procedure ParseFilter(const AFilter: string);
  200. function GetDbfFieldDefs: TDbfFieldDefs;
  201. function SearchKeyBuffer(Buffer: PChar; SearchType: TSearchKeyType): Boolean;
  202. procedure SetRangeBuffer(LowRange: PChar; HighRange: PChar);
  203. protected
  204. { abstract methods }
  205. function AllocRecordBuffer: PChar; override; {virtual abstract}
  206. procedure ClearCalcFields(Buffer: PChar); override;
  207. procedure FreeRecordBuffer(var Buffer: PChar); override; {virtual abstract}
  208. procedure GetBookmarkData(Buffer: PChar; Data: Pointer); override; {virtual abstract}
  209. function GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; override; {virtual abstract}
  210. function GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; override; {virtual abstract}
  211. function GetRecordSize: Word; override; {virtual abstract}
  212. procedure InternalAddRecord(Buffer: Pointer; AAppend: Boolean); override; {virtual abstract}
  213. procedure InternalClose; override; {virtual abstract}
  214. procedure InternalDelete; override; {virtual abstract}
  215. procedure InternalFirst; override; {virtual abstract}
  216. procedure InternalGotoBookmark(ABookmark: Pointer); override; {virtual abstract}
  217. procedure InternalHandleException; override; {virtual abstract}
  218. procedure InternalInitFieldDefs; override; {virtual abstract}
  219. procedure InternalInitRecord(Buffer: PChar); override; {virtual abstract}
  220. procedure InternalLast; override; {virtual abstract}
  221. procedure InternalOpen; override; {virtual abstract}
  222. procedure InternalEdit; override; {virtual}
  223. procedure InternalCancel; override; {virtual}
  224. {$ifndef FPC}
  225. {$ifndef DELPHI_3}
  226. procedure InternalInsert; override; {virtual}
  227. {$endif}
  228. {$endif}
  229. procedure InternalPost; override; {virtual abstract}
  230. procedure InternalSetToRecord(Buffer: PChar); override; {virtual abstract}
  231. procedure InitFieldDefs; override;
  232. function IsCursorOpen: Boolean; override; {virtual abstract}
  233. procedure SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); override; {virtual abstract}
  234. procedure SetBookmarkData(Buffer: PChar; Data: Pointer); override; {virtual abstract}
  235. procedure SetFieldData(Field: TField; Buffer: Pointer); override; {virtual abstract}
  236. { virtual methods (mostly optionnal) }
  237. function GetDataSource: TDataSource; {$ifndef VER1_0}override;{$endif}
  238. function GetRecordCount: Integer; override; {virtual}
  239. function GetRecNo: Integer; override; {virtual}
  240. function GetCanModify: Boolean; override; {virtual}
  241. procedure SetRecNo(Value: Integer); override; {virual}
  242. procedure SetFiltered(Value: Boolean); override; {virtual;}
  243. procedure SetFilterText(const Value: String); override; {virtual;}
  244. {$ifdef SUPPORT_DEFCHANGED}
  245. procedure DefChanged(Sender: TObject); override;
  246. {$endif}
  247. function FindRecord(Restart, GoForward: Boolean): Boolean; override;
  248. function GetIndexFieldNames: string; {virtual;}
  249. procedure SetIndexFieldNames(const Value: string); {virtual;}
  250. {$ifdef SUPPORT_VARIANTS}
  251. function LocateRecord(const KeyFields: String; const KeyValues: Variant; Options: TLocateOptions): Boolean;
  252. {$endif}
  253. procedure DoFilterRecord(var Acceptable: Boolean);
  254. public
  255. constructor Create(AOwner: TComponent); override;
  256. destructor Destroy; override;
  257. { abstract methods }
  258. function GetFieldData(Field: TField; Buffer: Pointer): Boolean; override; {virtual abstract}
  259. { virtual methods (mostly optionnal) }
  260. procedure Resync(Mode: TResyncMode); override;
  261. function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override; {virtual}
  262. {$ifdef SUPPORT_NEW_TRANSLATE}
  263. function Translate(Src, Dest: PChar; ToOem: Boolean): Integer; override; {virtual}
  264. {$else}
  265. procedure Translate(Src, Dest: PChar; ToOem: Boolean); override; {virtual}
  266. {$endif}
  267. {$ifdef SUPPORT_BACKWARD_FIELDDATA}
  268. function GetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean): Boolean; overload; override;
  269. procedure SetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean); overload; override;
  270. {$endif}
  271. function CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer; override;
  272. procedure CheckDbfFieldDefs(DbfFieldDefs: TDbfFieldDefs);
  273. {$ifdef VER1_0}
  274. procedure DataEvent(Event: TDataEvent; Info: Longint); override;
  275. {$endif}
  276. // my own methods and properties
  277. // most look like ttable functions but they are not tdataset related
  278. // I (try to) use the same syntax to facilitate the conversion between bde and TDbf
  279. // index support (use same syntax as ttable but is not related)
  280. {$ifdef SUPPORT_DEFAULT_PARAMS}
  281. procedure AddIndex(const AIndexName, AFields: String; Options: TIndexOptions; const DescFields: String='');
  282. {$else}
  283. procedure AddIndex(const AIndexName, AFields: String; Options: TIndexOptions);
  284. {$endif}
  285. procedure RegenerateIndexes;
  286. procedure CancelRange;
  287. {$ifdef SUPPORT_VARIANTS}
  288. function SearchKey(Key: Variant; SearchType: TSearchKeyType): Boolean;
  289. procedure SetRange(LowRange: Variant; HighRange: Variant);
  290. {$endif}
  291. function PrepareKey(Buffer: Pointer; BufferType: TExpressionType): PChar;
  292. function SearchKeyPChar(Key: PChar; SearchType: TSearchKeyType): Boolean;
  293. procedure SetRangePChar(LowRange: PChar; HighRange: PChar);
  294. function GetCurrentBuffer: PChar;
  295. procedure ExtractKey(KeyBuffer: PChar);
  296. procedure UpdateIndexDefs; override;
  297. procedure GetFileNames(Strings: TStrings; Files: TDbfFileNames); {$ifdef SUPPORT_DEFAULT_PARAMS} overload; {$endif}
  298. {$ifdef SUPPORT_DEFAULT_PARAMS}
  299. function GetFileNames(Files: TDbfFileNames = [dfDbf] ): string; overload;
  300. {$else}
  301. function GetFileNamesString(Files: TDbfFileNames (* = [dfDbf] *) ): string;
  302. {$endif}
  303. procedure GetIndexNames(Strings: TStrings);
  304. procedure GetAllIndexFiles(Strings: TStrings);
  305. procedure TryExclusive;
  306. procedure EndExclusive;
  307. function LockTable(const Wait: Boolean): Boolean;
  308. procedure UnlockTable;
  309. procedure OpenIndexFile(IndexFile: string);
  310. procedure DeleteIndex(const AIndexName: string);
  311. procedure CloseIndexFile(const AIndexName: string);
  312. procedure RepageIndexFile(const AIndexFile: string);
  313. procedure CompactIndexFile(const AIndexFile: string);
  314. {$ifdef SUPPORT_VARIANTS}
  315. {$ifdef USE_BUGGY_LOOKUP}
  316. function Lookup(const KeyFields: string; const KeyValues: Variant; const ResultFields: string): Variant; override;
  317. {$endif}
  318. function Locate(const KeyFields: string; const KeyValues: Variant; Options: TLocateOptions): Boolean; {$ifndef FPC_VERSION}override;{$endif}
  319. {$endif}
  320. function IsDeleted: Boolean;
  321. procedure Undelete;
  322. procedure CreateTable;
  323. procedure CreateTableEx(DbfFieldDefs: TDbfFieldDefs);
  324. procedure CopyFrom(DataSet: TDataSet; FileName: string; DateTimeAsString: Boolean; Level: Integer);
  325. procedure RestructureTable(DbfFieldDefs: TDbfFieldDefs; Pack: Boolean);
  326. procedure PackTable;
  327. procedure EmptyTable;
  328. procedure Zap;
  329. {$ifndef SUPPORT_INITDEFSFROMFIELDS}
  330. procedure InitFieldDefsFromFields;
  331. {$endif}
  332. property AbsolutePath: string read FAbsolutePath;
  333. property DbfFieldDefs: TDbfFieldDefs read GetDbfFieldDefs;
  334. property PhysicalRecNo: Integer read GetPhysicalRecNo write SetPhysicalRecNo;
  335. property LanguageID: Byte read FLanguageID write SetLanguageID;
  336. property LanguageStr: String read GetLanguageStr;
  337. property CodePage: Cardinal read GetCodePage;
  338. property ExactRecordCount: Integer read GetExactRecordCount;
  339. property PhysicalRecordCount: Integer read GetPhysicalRecordCount;
  340. property KeySize: Integer read GetKeySize;
  341. property DbfFile: TDbfFile read FDbfFile;
  342. property UserStream: TStream read FUserStream write FUserStream;
  343. property DisableResyncOnPost: Boolean read FDisableResyncOnPost write FDisableResyncOnPost;
  344. published
  345. property DateTimeHandling: TDateTimeHandling
  346. read FDateTimeHandling write FDateTimeHandling default dtBDETimeStamp;
  347. property Exclusive: Boolean read FExclusive write FExclusive default false;
  348. property FilePath: string read FRelativePath write SetFilePath;
  349. property FilePathFull: string read FAbsolutePath write SetFilePath stored false;
  350. property Indexes: TDbfIndexDefs read FIndexDefs write SetDbfIndexDefs stored false;
  351. property IndexDefs: TDbfIndexDefs read FIndexDefs write SetDbfIndexDefs;
  352. property IndexFieldNames: string read GetIndexFieldNames write SetIndexFieldNames;
  353. property IndexName: string read GetIndexName write SetIndexName;
  354. property MasterFields: string read GetMasterFields write SetMasterFields;
  355. property MasterSource: TDataSource read GetDataSource write SetDataSource;
  356. property OpenMode: TDbfOpenMode read FOpenMode write FOpenMode default omNormal;
  357. property ReadOnly: Boolean read FReadOnly write FReadonly default false;
  358. property ShowDeleted: Boolean read FShowDeleted write SetShowDeleted default false;
  359. property Storage: TDbfStorage read FStorage write FStorage default stoFile;
  360. property StoreDefs: Boolean read FStoreDefs write FStoreDefs default False;
  361. property TableName: string read FTableName write SetTableName;
  362. property TableLevel: Integer read FTableLevel write SetTableLevel;
  363. property UseFloatFields: Boolean read FUseFloatFields write FUseFloatFields;
  364. (* default {$ifdef SUPPORT_INT64} false {$else} true {$endif}; *)
  365. property Version: string read GetVersion write SetVersion stored false;
  366. property BeforeAutoCreate: TBeforeAutoCreateEvent read FBeforeAutoCreate write FBeforeAutoCreate;
  367. property OnCompareRecord: TNotifyEvent read FOnCompareRecord write FOnCompareRecord;
  368. property OnLanguageWarning: TLanguageWarningEvent read FOnLanguageWarning write FOnLanguageWarning;
  369. property OnLocaleError: TDbfLocaleErrorEvent read FOnLocaleError write FOnLocaleError;
  370. property OnIndexMissing: TDbfIndexMissingEvent read FOnIndexMissing write FOnIndexMissing;
  371. property OnCopyDateTimeAsString: TConvertFieldEvent read FOnCopyDateTimeAsString write FOnCopyDateTimeAsString;
  372. property OnTranslate: TTranslateEvent read FOnTranslate write FOnTranslate;
  373. // redeclared data set properties
  374. property Active;
  375. property FieldDefs stored FieldDefsStored;
  376. property Filter;
  377. property Filtered;
  378. property FilterOptions;
  379. property BeforeOpen;
  380. property AfterOpen;
  381. property BeforeClose;
  382. property AfterClose;
  383. property BeforeInsert;
  384. property AfterInsert;
  385. property BeforeEdit;
  386. property AfterEdit;
  387. property BeforePost;
  388. property AfterPost;
  389. property BeforeCancel;
  390. property AfterCancel;
  391. property BeforeDelete;
  392. property AfterDelete;
  393. property BeforeScroll;
  394. property AfterScroll;
  395. property OnCalcFields;
  396. property OnDeleteError;
  397. property OnEditError;
  398. property OnFilterRecord;
  399. property OnNewRecord;
  400. property OnPostError;
  401. end;
  402. TDbf_GetBasePathFunction = function: string;
  403. var
  404. DbfBasePath: TDbf_GetBasePathFunction;
  405. implementation
  406. uses
  407. SysUtils,
  408. {$ifndef FPC}
  409. DBConsts,
  410. {$endif}
  411. {$ifdef WIN32}
  412. Windows,
  413. {$else}
  414. {$ifdef KYLIX}
  415. Libc,
  416. {$endif}
  417. Types,
  418. dbf_wtil,
  419. {$endif}
  420. {$ifdef DELPHI_6}
  421. Variants,
  422. {$endif}
  423. dbf_idxcur,
  424. dbf_memo,
  425. dbf_str;
  426. {$ifdef FPC}
  427. const
  428. // TODO: move these to DBConsts
  429. SNotEditing = 'Dataset not in edit or insert mode';
  430. SCircularDataLink = 'Circular datalinks are not allowed';
  431. {$endif}
  432. function TableLevelToDbfVersion(TableLevel: integer): TXBaseVersion;
  433. begin
  434. case TableLevel of
  435. 3: Result := xBaseIII;
  436. 7: Result := xBaseVII;
  437. TDBF_TABLELEVEL_FOXPRO: Result := xFoxPro;
  438. else
  439. {4:} Result := xBaseIV;
  440. end;
  441. end;
  442. //==========================================================
  443. //============ TDbfBlobStream
  444. //==========================================================
  445. constructor TDbfBlobStream.Create(FieldVal: TField);
  446. begin
  447. FBlobField := FieldVal as TBlobField;
  448. FReadSize := 0;
  449. FMemoRecNo := 0;
  450. FRefCount := 1;
  451. FDirty := false;
  452. end;
  453. destructor TDbfBlobStream.Destroy;
  454. begin
  455. // only continue destroy if all references released
  456. if FRefCount = 1 then
  457. begin
  458. // this is the last reference
  459. inherited
  460. end else begin
  461. // fire event when dirty, and the last "user" is freeing it's reference
  462. // tdbf always has the last reference
  463. if FDirty and (FRefCount = 2) then
  464. begin
  465. // a second referer to instance has changed the data, remember modified
  466. // TDbf(FBlobField.DataSet).SetModified(true);
  467. // is following better? seems to provide notification for user (from VCL)
  468. if not (FBlobField.DataSet.State in [dsCalcFields, dsFilter, dsNewValue]) then
  469. TDbf(FBlobField.DataSet).DataEvent(deFieldChange, Longint(FBlobField));
  470. end;
  471. end;
  472. Dec(FRefCount);
  473. end;
  474. procedure TDbfBlobStream.FreeInstance;
  475. begin
  476. // only continue freeing if all references released
  477. if FRefCount = 0 then
  478. inherited;
  479. end;
  480. procedure TDbfBlobStream.SetMode(NewMode: TBlobStreamMode);
  481. begin
  482. FMode := NewMode;
  483. FDirty := FDirty or (NewMode = bmWrite) or (NewMode = bmReadWrite);
  484. end;
  485. procedure TDbfBlobStream.Cancel;
  486. begin
  487. FDirty := false;
  488. FMemoRecNo := -1;
  489. end;
  490. procedure TDbfBlobStream.Commit;
  491. var
  492. Dbf: TDbf;
  493. begin
  494. if FDirty then
  495. begin
  496. Size := Position; // Strange but it leave tailing trash bytes if I do not write that.
  497. Dbf := TDbf(FBlobField.DataSet);
  498. Translate(true);
  499. Dbf.FDbfFile.MemoFile.WriteMemo(FMemoRecNo, FReadSize, Self);
  500. Dbf.FDbfFile.SetFieldData(FBlobField.FieldNo-1, ftInteger, @FMemoRecNo,
  501. @pDbfRecord(TDbf(FBlobField.DataSet).ActiveBuffer)^.DeletedFlag);
  502. FDirty := false;
  503. end;
  504. end;
  505. function TDbfBlobStream.AddReference: TDbfBlobStream;
  506. begin
  507. Inc(FRefCount);
  508. Result := Self;
  509. end;
  510. function TDbfBlobStream.GetTransliterate: Boolean;
  511. begin
  512. Result := FBlobField.Transliterate;
  513. end;
  514. procedure TDbfBlobStream.Translate(ToOem: Boolean);
  515. var
  516. bytesToDo, numBytes: Integer;
  517. bufPos: PChar;
  518. saveChar: Char;
  519. begin
  520. if (Transliterate) and (Size > 0) then
  521. begin
  522. // get number of bytes to be translated
  523. bytesToDo := Size;
  524. // make space for final null-terminator
  525. Size := Size + 1;
  526. bufPos := Memory;
  527. repeat
  528. // process blocks of 512 bytes
  529. numBytes := bytesToDo;
  530. if numBytes > 512 then
  531. numBytes := 512;
  532. // null-terminate memory
  533. saveChar := bufPos[numBytes];
  534. bufPos[numBytes] := #0;
  535. // translate memory
  536. TDbf(FBlobField.DataSet).Translate(bufPos, bufPos, ToOem);
  537. // restore char
  538. bufPos[numBytes] := saveChar;
  539. // numBytes bytes translated
  540. Dec(bytesToDo, numBytes);
  541. Inc(bufPos, numBytes);
  542. until bytesToDo = 0;
  543. // cut ending null-terminator
  544. Size := Size - 1;
  545. end;
  546. end;
  547. //====================================================================
  548. // TDbf = TDataset Descendant.
  549. //====================================================================
  550. constructor TDbf.Create(AOwner: TComponent); {override;}
  551. begin
  552. inherited;
  553. if DbfGlobals = nil then
  554. DbfGlobals := TDbfGlobals.Create;
  555. BookmarkSize := sizeof(TBookmarkData);
  556. FIndexDefs := TDbfIndexDefs.Create(Self);
  557. FMasterLink := TDbfMasterLink.Create(Self);
  558. FMasterLink.OnMasterChange := MasterChanged;
  559. FMasterLink.OnMasterDisable := MasterDisabled;
  560. FDateTimeHandling := dtBDETimeStamp;
  561. FStorage := stoFile;
  562. FOpenMode := omNormal;
  563. FParser := nil;
  564. FPosting := false;
  565. FReadOnly := false;
  566. FExclusive := false;
  567. FUseFloatFields := true;
  568. //FUseFloatFields := {$ifdef SUPPORT_INT64} false {$else} true {$endif};
  569. FDisableResyncOnPost := false;
  570. FTempExclusive := false;
  571. FCopyDateTimeAsString := false;
  572. FInCopyFrom := false;
  573. FFindRecordFilter := false;
  574. FEditingRecNo := -1;
  575. FTableLevel := 4;
  576. FIndexName := EmptyStr;
  577. FilePath := EmptyStr;
  578. FTempBuffer := nil;
  579. FFilterBuffer := nil;
  580. FIndexFile := nil;
  581. FOnTranslate := nil;
  582. FOnCopyDateTimeAsString := nil;
  583. end;
  584. destructor TDbf.Destroy; {override;}
  585. var
  586. I: Integer;
  587. begin
  588. inherited Destroy;
  589. if FIndexDefs <> nil then
  590. begin
  591. for I := FIndexDefs.Count - 1 downto 0 do
  592. TDbfIndexDef(FIndexDefs.Items[I]).Free;
  593. FIndexDefs.Free;
  594. end;
  595. FMasterLink.Free;
  596. end;
  597. function TDbf.AllocRecordBuffer: PChar; {override virtual abstract from TDataset}
  598. begin
  599. GetMem(Result, SizeOf(TDbfRecordHeader)+FDbfFile.RecordSize+CalcFieldsSize+1);
  600. end;
  601. procedure TDbf.FreeRecordBuffer(var Buffer: PChar); {override virtual abstract from TDataset}
  602. begin
  603. FreeMemAndNil(Pointer(Buffer));
  604. end;
  605. procedure TDbf.GetBookmarkData(Buffer: PChar; Data: Pointer); {override virtual abstract from TDataset}
  606. begin
  607. pBookmarkData(Data)^ := pDbfRecord(Buffer)^.BookmarkData;
  608. end;
  609. function TDbf.GetBookmarkFlag(Buffer: PChar): TBookmarkFlag; {override virtual abstract from TDataset}
  610. begin
  611. Result := pDbfRecord(Buffer)^.BookmarkFlag;
  612. end;
  613. function TDbf.GetCurrentBuffer: PChar;
  614. begin
  615. case State of
  616. dsFilter: Result := FFilterBuffer;
  617. dsCalcFields: Result := @(pDbfRecord(CalcBuffer)^.DeletedFlag);
  618. // dsSetKey: Result := FKeyBuffer; // TO BE Implemented
  619. else
  620. if IsEmpty then
  621. begin
  622. Result := nil;
  623. end else begin
  624. Result := @(pDbfRecord(ActiveBuffer)^.DeletedFlag);
  625. end;
  626. end;
  627. end;
  628. function TDbf.GetFieldData(Field: TField; Buffer: Pointer): Boolean; {override virtual abstract from TDataset}
  629. var
  630. Src: PChar;
  631. begin
  632. Src := GetCurrentBuffer;
  633. if Src = nil then
  634. begin
  635. Result := false;
  636. exit;
  637. end;
  638. if Field.FieldNo>0 then
  639. begin
  640. Result := FDbfFile.GetFieldData(Field.FieldNo-1, Field.DataType, Src, Buffer);
  641. end else begin { calculated fields.... }
  642. Inc(PChar(Src), Field.Offset + GetRecordSize);
  643. // Result := Boolean(PChar(Buffer)[0]);
  644. Result := true;
  645. if {Result and (Src <> nil) and } (Buffer <> nil) then
  646. begin
  647. // A ftBoolean was 1 byte in Delphi 3
  648. // it is now 2 byte in Delphi 5
  649. // not sure about delphi 4.
  650. {$ifdef DELPHI_5}
  651. Move(Src^, Buffer^, Field.DataSize);
  652. {$else}
  653. if Field.DataType = ftBoolean then
  654. Move(Src^, Buffer^, 1)
  655. else
  656. Move(Src^, Buffer^, Field.DataSize);
  657. {$endif}
  658. end;
  659. end;
  660. end;
  661. {$ifdef SUPPORT_BACKWARD_FIELDDATA}
  662. // we don't want converted data formats, we want native :-)
  663. // it makes coding easier in TDbfFile.GetFieldData
  664. // ftCurrency:
  665. // Delphi 3,4: BCD array
  666. // ftBCD:
  667. // ftDateTime is more difficult though
  668. function TDbf.GetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean): Boolean; {overload; override;}
  669. begin
  670. // pretend nativeformat is true
  671. Result := inherited GetFieldData(Field, Buffer, True);
  672. end;
  673. procedure TDbf.SetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean); {overload; override;}
  674. begin
  675. // pretend nativeformat is true
  676. inherited SetFieldData(Field, Buffer, True);
  677. end;
  678. {$endif}
  679. procedure TDbf.DoFilterRecord(var Acceptable: Boolean);
  680. begin
  681. // check filtertext
  682. if Length(Filter) > 0 then
  683. begin
  684. {$ifndef VER1_0}
  685. Acceptable := Boolean((FParser.ExtractFromBuffer(GetCurrentBuffer))^);
  686. {$else}
  687. // strange problem
  688. // dbf.pas(716,19) Error: Incompatible types: got "CHAR" expected "BOOLEAN"
  689. Acceptable := not ((FParser.ExtractFromBuffer(GetCurrentBuffer))^ = #0);
  690. {$endif}
  691. end;
  692. // check user filter
  693. if Acceptable and Assigned(OnFilterRecord) then
  694. OnFilterRecord(Self, Acceptable);
  695. end;
  696. function TDbf.GetRecord(Buffer: PChar; GetMode: TGetMode; DoCheck: Boolean): TGetResult; {override virtual abstract from TDataset}
  697. var
  698. pRecord: pDBFRecord;
  699. acceptable: Boolean;
  700. SaveState: TDataSetState;
  701. lPhysicalRecNo: Integer;
  702. // s: string;
  703. begin
  704. if FCursor = nil then
  705. begin
  706. Result := grEOF;
  707. exit;
  708. end;
  709. pRecord := pDBFRecord(Buffer);
  710. acceptable := false;
  711. repeat
  712. Result := grOK;
  713. case GetMode of
  714. gmNext :
  715. begin
  716. Acceptable := FCursor.Next;
  717. if Acceptable then begin
  718. Result := grOK;
  719. end else begin
  720. Result := grEOF
  721. end;
  722. end;
  723. gmPrior :
  724. begin
  725. Acceptable := FCursor.Prev;
  726. if Acceptable then begin
  727. Result := grOK;
  728. end else begin
  729. Result := grBOF
  730. end;
  731. end;
  732. end;
  733. if (Result = grOK) then
  734. begin
  735. lPhysicalRecNo := FCursor.PhysicalRecNo;
  736. if (lPhysicalRecNo = 0) or not FDbfFile.IsRecordPresent(lPhysicalRecNo) then
  737. begin
  738. Result := grError;
  739. end else begin
  740. FDbfFile.ReadRecord(lPhysicalRecNo, @pRecord^.DeletedFlag);
  741. acceptable := (FShowDeleted or (pRecord^.DeletedFlag <> '*'))
  742. end;
  743. end;
  744. if (Result = grOK) and acceptable then
  745. begin
  746. if Filtered or FFindRecordFilter then
  747. begin
  748. FFilterBuffer := @pRecord^.DeletedFlag;
  749. SaveState := SetTempState(dsFilter);
  750. DoFilterRecord(acceptable);
  751. RestoreState(SaveState);
  752. end;
  753. end;
  754. if (GetMode = gmCurrent) and not acceptable then
  755. Result := grError;
  756. until (Result <> grOK) or acceptable;
  757. if (Result = grOK) and not FFindRecordFilter then
  758. begin
  759. pRecord^.BookmarkData.PhysicalRecNo := FCursor.PhysicalRecNo;
  760. pRecord^.BookmarkFlag := bfCurrent;
  761. pRecord^.SequentialRecNo := FCursor.SequentialRecNo;
  762. GetCalcFields(Buffer);
  763. end else begin
  764. pRecord^.BookmarkData.PhysicalRecNo := -1;
  765. end;
  766. end;
  767. function TDbf.GetRecordSize: Word; {override virtual abstract from TDataset}
  768. begin
  769. Result := FDbfFile.RecordSize;
  770. end;
  771. procedure TDbf.InternalAddRecord(Buffer: Pointer; AAppend: Boolean); {override virtual abstract from TDataset}
  772. // this function is called from TDataSet.InsertRecord and TDataSet.AppendRecord
  773. // goal: add record with Edit...Set Fields...Post all in one step
  774. var
  775. pRecord: pDbfRecord;
  776. newRecord: integer;
  777. begin
  778. // if InternalAddRecord is called, we know we are active
  779. pRecord := Buffer;
  780. // we can not insert records in DBF files, only append
  781. // ignore Append parameter
  782. newRecord := FDbfFile.Insert(@pRecord^.DeletedFlag);
  783. if newRecord > 0 then
  784. FCursor.PhysicalRecNo := newRecord;
  785. // set flag that TDataSet is about to post...so we can disable resync
  786. FPosting := true;
  787. end;
  788. procedure TDbf.InternalClose; {override virtual abstract from TDataset}
  789. var
  790. lIndex: TDbfIndexDef;
  791. I: Integer;
  792. begin
  793. // clear automatically added MDX index entries
  794. I := 0;
  795. while I < FIndexDefs.Count do
  796. begin
  797. // is this an MDX index?
  798. lIndex := FIndexDefs.Items[I];
  799. if (Length(ExtractFileExt(lIndex.IndexFile)) = 0) and
  800. TDbfIndexDef(FIndexDefs.Items[I]).Temporary then
  801. begin
  802. {$ifdef SUPPORT_DEF_DELETE}
  803. // delete this entry
  804. FIndexDefs.Delete(I);
  805. {$else}
  806. // does this work? I hope so :-)
  807. FIndexDefs.Items[I].Free;
  808. {$endif}
  809. end else begin
  810. // NDX entry -> goto next
  811. Inc(I);
  812. end;
  813. end;
  814. // free blobs
  815. if FBlobStreams <> nil then
  816. begin
  817. for I := 0 to Pred(FieldCount) do
  818. if FBlobStreams^[I] <> nil then
  819. FBlobStreams^[I].Free;
  820. FreeMemAndNil(Pointer(FBlobStreams));
  821. end;
  822. FreeRecordBuffer(FTempBuffer);
  823. // disconnect field objects
  824. BindFields(false);
  825. // Destroy field object (if not persistent)
  826. if DefaultFields then
  827. DestroyFields;
  828. if FParser <> nil then
  829. FreeAndNil(FParser);
  830. if (FDbfFile <> nil) and not FReadOnly then
  831. FDbfFile.WriteHeader;
  832. FreeAndNil(FCursor);
  833. if FDbfFile <> nil then
  834. FreeAndNil(FDbfFile);
  835. end;
  836. procedure TDbf.InternalCancel;
  837. var
  838. I: Integer;
  839. begin
  840. // cancel blobs
  841. for I := 0 to Pred(FieldCount) do
  842. if Assigned(FBlobStreams^[I]) then
  843. FBlobStreams^[I].Cancel;
  844. // if we have locked a record, unlock it
  845. if FEditingRecNo >= 0 then
  846. begin
  847. FDbfFile.UnlockPage(FEditingRecNo);
  848. FEditingRecNo := -1;
  849. end;
  850. end;
  851. procedure TDbf.InternalDelete; {override virtual abstract from TDataset}
  852. var
  853. lRecord: pDbfRecord;
  854. begin
  855. // start editing
  856. InternalEdit;
  857. SetState(dsEdit);
  858. // get record pointer
  859. lRecord := pDbfRecord(ActiveBuffer);
  860. // flag we deleted this record
  861. lRecord^.DeletedFlag := '*';
  862. // notify indexes this record is deleted
  863. FDbfFile.RecordDeleted(FEditingRecNo, @lRecord^.DeletedFlag);
  864. // done!
  865. InternalPost;
  866. end;
  867. procedure TDbf.InternalFirst; {override virtual abstract from TDataset}
  868. begin
  869. FCursor.First;
  870. end;
  871. procedure TDbf.InternalGotoBookmark(ABookmark: Pointer); {override virtual abstract from TDataset}
  872. begin
  873. with PBookmarkData(ABookmark)^ do
  874. begin
  875. if (PhysicalRecNo = 0) then begin
  876. First;
  877. end else
  878. if (PhysicalRecNo = MaxInt) then begin
  879. Last;
  880. end else begin
  881. if FCursor.PhysicalRecNo <> PhysicalRecNo then
  882. FCursor.PhysicalRecNo := PhysicalRecNo;
  883. end;
  884. end;
  885. end;
  886. procedure TDbf.InternalHandleException; {override virtual abstract from TDataset}
  887. begin
  888. SysUtils.ShowException(ExceptObject, ExceptAddr);
  889. end;
  890. procedure TDbf.GetFieldDefsFromDbfFieldDefs;
  891. var
  892. I, N: Integer;
  893. TempFieldDef: TDbfFieldDef;
  894. TempMdxFile: TIndexFile;
  895. BaseName, lIndexName: string;
  896. begin
  897. FieldDefs.Clear;
  898. // get all fields
  899. for I := 0 to FDbfFile.FieldDefs.Count - 1 do
  900. begin
  901. TempFieldDef := FDbfFile.FieldDefs.Items[I];
  902. // handle duplicate field names
  903. N := 1;
  904. BaseName := TempFieldDef.FieldName;
  905. while FieldDefs.IndexOf(TempFieldDef.FieldName)>=0 do
  906. begin
  907. Inc(N);
  908. TempFieldDef.FieldName:=BaseName+IntToStr(N);
  909. end;
  910. // add field
  911. if TempFieldDef.FieldType in [ftString, ftBCD, ftBytes] then
  912. FieldDefs.Add(TempFieldDef.FieldName, TempFieldDef.FieldType, TempFieldDef.Size, false)
  913. else
  914. FieldDefs.Add(TempFieldDef.FieldName, TempFieldDef.FieldType, 0, false);
  915. if TempFieldDef.FieldType = ftFloat then
  916. FieldDefs[I].Precision := TempFieldDef.Precision;
  917. {$ifdef SUPPORT_FIELDDEF_ATTRIBUTES}
  918. // AutoInc fields are readonly
  919. if TempFieldDef.FieldType = ftAutoInc then
  920. FieldDefs[I].Attributes := [Db.faReadOnly];
  921. // if table has dbase lock field, then hide it
  922. if TempFieldDef.IsLockField then
  923. FieldDefs[I].Attributes := [Db.faHiddenCol];
  924. {$endif}
  925. end;
  926. // get all (new) MDX index defs
  927. TempMdxFile := FDbfFile.MdxFile;
  928. for I := 0 to FDbfFile.IndexNames.Count - 1 do
  929. begin
  930. // is this an MDX index?
  931. lIndexName := FDbfFile.IndexNames.Strings[I];
  932. if FDbfFile.IndexNames.Objects[I] = TempMdxFile then
  933. if FIndexDefs.GetIndexByName(lIndexName) = nil then
  934. TempMdxFile.GetIndexInfo(lIndexName, FIndexDefs.Add);
  935. end;
  936. end;
  937. procedure TDbf.InitFieldDefs;
  938. begin
  939. InternalInitFieldDefs;
  940. end;
  941. procedure TDbf.InitDbfFile(FileOpenMode: TPagedFileMode);
  942. const
  943. FileModeToMemMode: array[TPagedFileMode] of TPagedFileMode =
  944. (pfNone, pfMemoryCreate, pfMemoryOpen, pfMemoryCreate, pfMemoryOpen,
  945. pfMemoryCreate, pfMemoryOpen, pfMemoryOpen);
  946. begin
  947. FDbfFile := TDbfFile.Create;
  948. if FStorage = stoMemory then
  949. begin
  950. FDbfFile.Stream := FUserStream;
  951. FDbfFile.Mode := FileModeToMemMode[FileOpenMode];
  952. end else begin
  953. FDbfFile.FileName := FAbsolutePath + FTableName;
  954. FDbfFile.Mode := FileOpenMode;
  955. end;
  956. FDbfFile.AutoCreate := false;
  957. FDbfFile.UseFloatFields := FUseFloatFields;
  958. FDbfFile.DateTimeHandling := FDateTimeHandling;
  959. FDbfFile.OnLocaleError := FOnLocaleError;
  960. FDbfFile.OnIndexMissing := FOnIndexMissing;
  961. end;
  962. procedure TDbf.InternalInitFieldDefs; {override virtual abstract from TDataset}
  963. var
  964. MustReleaseDbfFile: Boolean;
  965. begin
  966. MustReleaseDbfFile := false;
  967. with FieldDefs do
  968. begin
  969. if FDbfFile = nil then
  970. begin
  971. // do not AutoCreate file
  972. InitDbfFile(pfReadOnly);
  973. FDbfFile.Open;
  974. MustReleaseDbfFile := true;
  975. end;
  976. GetFieldDefsFromDbfFieldDefs;
  977. if MustReleaseDbfFile then
  978. FreeAndNil(FDbfFile);
  979. end;
  980. end;
  981. procedure TDbf.InternalInitRecord(Buffer: PChar); {override virtual abstract from TDataset}
  982. var
  983. pRecord: pDbfRecord;
  984. begin
  985. pRecord := pDbfRecord(Buffer);
  986. pRecord^.BookmarkData.PhysicalRecNo := 0;
  987. pRecord^.BookmarkFlag := bfCurrent;
  988. pRecord^.SequentialRecNo := 0;
  989. // Init Record with zero and set autoinc field with next value
  990. FDbfFile.InitRecord(@pRecord^.DeletedFlag);
  991. end;
  992. procedure TDbf.InternalLast; {override virtual abstract from TDataset}
  993. begin
  994. FCursor.Last;
  995. end;
  996. procedure TDbf.DetermineTranslationMode;
  997. var
  998. lCodePage: Cardinal;
  999. begin
  1000. lCodePage := FDbfFile.UseCodePage;
  1001. if lCodePage = GetACP then
  1002. FTranslationMode := tmNoneNeeded
  1003. else
  1004. if lCodePage = GetOEMCP then
  1005. FTranslationMode := tmSimple
  1006. // check if this code page, although non default, is installed
  1007. else
  1008. if DbfGlobals.CodePageInstalled(lCodePage) then
  1009. FTranslationMode := tmAdvanced
  1010. else
  1011. FTranslationMode := tmNoneAvailable;
  1012. end;
  1013. procedure TDbf.InternalOpen; {override virtual abstract from TDataset}
  1014. const
  1015. DbfOpenMode: array[Boolean, Boolean] of TPagedFileMode =
  1016. ((pfReadWriteOpen, pfExclusiveOpen), (pfReadOnly, pfReadOnly));
  1017. var
  1018. lIndex: TDbfIndexDef;
  1019. lIndexName: string;
  1020. LanguageAction: TDbfLanguageAction;
  1021. doCreate: Boolean;
  1022. I: Integer;
  1023. begin
  1024. // close current file
  1025. FreeAndNil(FDbfFile);
  1026. // does file not exist? -> create
  1027. if ((FStorage = stoFile) and
  1028. not FileExists(FAbsolutePath + FTableName) and
  1029. (FOpenMode in [omAutoCreate, omTemporary])) or
  1030. ((FStorage = stoMemory) and (FUserStream = nil)) then
  1031. begin
  1032. doCreate := true;
  1033. if Assigned(FBeforeAutoCreate) then
  1034. FBeforeAutoCreate(Self, doCreate);
  1035. if doCreate then
  1036. CreateTable
  1037. else
  1038. exit;
  1039. end;
  1040. // now we know for sure the file exists
  1041. InitDbfFile(DbfOpenMode[FReadOnly, FExclusive]);
  1042. FDbfFile.Open;
  1043. // fail open?
  1044. {$ifndef FPC}
  1045. if FDbfFile.ForceClose then
  1046. Abort;
  1047. {$endif}
  1048. // determine dbf version
  1049. case FDbfFile.DbfVersion of
  1050. xBaseIII: FTableLevel := 3;
  1051. xBaseIV: FTableLevel := 4;
  1052. xBaseVII: FTableLevel := 7;
  1053. xFoxPro: FTableLevel := TDBF_TABLELEVEL_FOXPRO;
  1054. end;
  1055. FLanguageID := FDbfFile.LanguageID;
  1056. // build VCL fielddef list from native DBF FieldDefs
  1057. (*
  1058. if (FDbfFile.HeaderSize = 0) or (FDbfFile.FieldDefs.Count = 0) then
  1059. begin
  1060. if FieldDefs.Count > 0 then
  1061. begin
  1062. CreateTableFromFieldDefs;
  1063. end else begin
  1064. CreateTableFromFields;
  1065. end;
  1066. end else begin
  1067. *)
  1068. // GetFieldDefsFromDbfFieldDefs;
  1069. // end;
  1070. {$ifdef SUPPORT_FIELDDEFS_UPDATED}
  1071. FieldDefs.Updated := False;
  1072. FieldDefs.Update;
  1073. {$else}
  1074. InternalInitFieldDefs;
  1075. {$endif}
  1076. // create the fields dynamically
  1077. if DefaultFields then
  1078. CreateFields; // Create fields from fielddefs.
  1079. BindFields(true);
  1080. // create array of blobstreams to store memo's in. each field is a possible blob
  1081. GetMem(FBlobStreams, FieldCount * SizeOf(TDbfBlobStream));
  1082. for I := 0 to Pred(FieldCount) do
  1083. FBlobStreams^[I] := nil;
  1084. // check codepage settings
  1085. DetermineTranslationMode;
  1086. if FTranslationMode = tmNoneAvailable then
  1087. begin
  1088. // no codepage available? ask user
  1089. LanguageAction := laReadOnly;
  1090. if Assigned(FOnLanguageWarning) then
  1091. FOnLanguageWarning(Self, LanguageAction);
  1092. case LanguageAction of
  1093. laReadOnly: FTranslationMode := tmNoneAvailable;
  1094. laForceOEM:
  1095. begin
  1096. FDbfFile.UseCodePage := GetOEMCP;
  1097. FTranslationMode := tmSimple;
  1098. end;
  1099. laForceANSI:
  1100. begin
  1101. FDbfFile.UseCodePage := GetACP;
  1102. FTranslationMode := tmNoneNeeded;
  1103. end;
  1104. laDefault:
  1105. begin
  1106. FDbfFile.UseCodePage := DbfGlobals.DefaultOpenCodePage;
  1107. DetermineTranslationMode;
  1108. end;
  1109. end;
  1110. end;
  1111. // allocate a record buffer for temporary data
  1112. FTempBuffer := AllocRecordBuffer;
  1113. // open indexes
  1114. for I := 0 to FIndexDefs.Count - 1 do
  1115. begin
  1116. lIndex := FIndexDefs.Items[I];
  1117. lIndexName := ParseIndexName(lIndex.IndexFile);
  1118. // if index does not exist -> create, if it does exist -> open only
  1119. FDbfFile.OpenIndex(lIndexName, lIndex.SortField, false, lIndex.Options);
  1120. end;
  1121. // parse filter expression
  1122. try
  1123. ParseFilter(Filter);
  1124. except
  1125. // oops, a problem with parsing, clear filter for now
  1126. on E: EDbfError do Filter := EmptyStr;
  1127. end;
  1128. SetIndexName(FIndexName);
  1129. // SetIndexName will have made the cursor for us if no index selected :-)
  1130. // if FCursor = nil then FCursor := TDbfCursor.Create(FDbfFile);
  1131. InternalFirst;
  1132. // FDbfFile.SetIndex(FIndexName);
  1133. // FDbfFile.FIsCursorOpen := true;
  1134. end;
  1135. function TDbf.GetCodePage: Cardinal;
  1136. begin
  1137. if FDbfFile <> nil then
  1138. Result := FDbfFile.UseCodePage
  1139. else
  1140. Result := 0;
  1141. end;
  1142. function TDbf.GetLanguageStr: String;
  1143. begin
  1144. if FDbfFile <> nil then
  1145. Result := FDbfFile.LanguageStr;
  1146. end;
  1147. function TDbf.LockTable(const Wait: Boolean): Boolean;
  1148. begin
  1149. CheckActive;
  1150. Result := FDbfFile.LockAllPages(Wait);
  1151. end;
  1152. procedure TDbf.UnlockTable;
  1153. begin
  1154. CheckActive;
  1155. FDbfFile.UnlockAllPages;
  1156. end;
  1157. procedure TDbf.InternalEdit;
  1158. var
  1159. I: Integer;
  1160. begin
  1161. // store recno we are editing
  1162. FEditingRecNo := FCursor.PhysicalRecNo;
  1163. // reread blobs, execute cancel -> clears remembered memo pageno,
  1164. // causing it to reread the memo contents
  1165. for I := 0 to Pred(FieldCount) do
  1166. if Assigned(FBlobStreams^[I]) then
  1167. FBlobStreams^[I].Cancel;
  1168. // try to lock this record
  1169. FDbfFile.LockRecord(FEditingRecNo, @pDbfRecord(ActiveBuffer)^.DeletedFlag);
  1170. // succeeded!
  1171. end;
  1172. {$ifndef FPC}
  1173. {$ifndef DELPHI_3}
  1174. procedure TDbf.InternalInsert; {override virtual from TDataset}
  1175. begin
  1176. CursorPosChanged;
  1177. end;
  1178. {$endif}
  1179. {$endif}
  1180. procedure TDbf.InternalPost; {override virtual abstract from TDataset}
  1181. var
  1182. pRecord: pDbfRecord;
  1183. I, newRecord: Integer;
  1184. begin
  1185. // if internalpost is called, we know we are active
  1186. pRecord := pDbfRecord(ActiveBuffer);
  1187. // commit blobs
  1188. for I := 0 to Pred(FieldCount) do
  1189. if Assigned(FBlobStreams^[I]) then
  1190. FBlobStreams^[I].Commit;
  1191. if State = dsEdit then
  1192. begin
  1193. // write changes
  1194. FDbfFile.UnlockRecord(FEditingRecNo, @pRecord^.DeletedFlag);
  1195. // not editing anymore
  1196. FEditingRecNo := -1;
  1197. end else begin
  1198. // insert
  1199. newRecord := FDbfFile.Insert(@pRecord^.DeletedFlag);
  1200. if newRecord > 0 then
  1201. FCursor.PhysicalRecNo := newRecord;
  1202. end;
  1203. // set flag that TDataSet is about to post...so we can disable resync
  1204. FPosting := true;
  1205. end;
  1206. procedure TDbf.Resync(Mode: TResyncMode);
  1207. begin
  1208. // try to increase speed
  1209. if not FDisableResyncOnPost or not FPosting then
  1210. inherited;
  1211. // clear post flag
  1212. FPosting := false;
  1213. end;
  1214. {$ifndef SUPPORT_INITDEFSFROMFIELDS}
  1215. procedure TDbf.InitFieldDefsFromFields;
  1216. var
  1217. I: Integer;
  1218. F: TField;
  1219. begin
  1220. { create fielddefs from persistent fields if needed }
  1221. for I := 0 to FieldCount - 1 do
  1222. begin
  1223. F := Fields[I];
  1224. with F do
  1225. if FieldKind = fkData then begin
  1226. FieldDefs.Add(FieldName,DataType,Size,Required);
  1227. end;
  1228. end;
  1229. end;
  1230. {$endif}
  1231. procedure TDbf.CreateTable;
  1232. begin
  1233. CreateTableEx(nil);
  1234. end;
  1235. procedure TDbf.CheckDbfFieldDefs(DbfFieldDefs: TDbfFieldDefs);
  1236. var
  1237. I: Integer;
  1238. TempDef: TDbfFieldDef;
  1239. function FieldTypeStr(const FieldType: char): string;
  1240. begin
  1241. if FieldType = #0 then
  1242. Result := 'NULL'
  1243. else if FieldType > #127 then
  1244. Result := 'ASCII '+IntToStr(Byte(FieldType))
  1245. else
  1246. Result := ' "'+fieldType+'" ';
  1247. Result := ' ' + Result + '(#'+IntToHex(Byte(FieldType),SizeOf(FieldType))+') '
  1248. end;
  1249. begin
  1250. if DbfFieldDefs = nil then exit;
  1251. for I := 0 to DbfFieldDefs.Count - 1 do
  1252. begin
  1253. // check dbffielddefs for errors
  1254. TempDef := DbfFieldDefs.Items[I];
  1255. if FTableLevel < 7 then
  1256. if not (TempDef.NativeFieldType in ['C', 'F', 'N', 'D', 'L', 'M']) then
  1257. raise EDbfError.CreateFmt(STRING_INVALID_FIELD_TYPE,
  1258. [FieldTypeStr(TempDef.NativeFieldType), TempDef.FieldName]);
  1259. end;
  1260. end;
  1261. procedure TDbf.CreateTableEx(DbfFieldDefs: TDbfFieldDefs);
  1262. var
  1263. I: Integer;
  1264. lIndex: TDbfIndexDef;
  1265. lIndexName: string;
  1266. tempFieldDefs: Boolean;
  1267. begin
  1268. CheckInactive;
  1269. tempFieldDefs := DbfFieldDefs = nil;
  1270. try
  1271. try
  1272. if tempFieldDefs then
  1273. begin
  1274. DbfFieldDefs := TDbfFieldDefs.Create(Self);
  1275. DbfFieldDefs.DbfVersion := TableLevelToDbfVersion(FTableLevel);
  1276. DbfFieldDefs.UseFloatFields := FUseFloatFields;
  1277. // get fields -> fielddefs if no fielddefs
  1278. {$ifndef FPC_VERSION}
  1279. if FieldDefs.Count = 0 then
  1280. InitFieldDefsFromFields;
  1281. {$endif}
  1282. // fielddefs -> dbffielddefs
  1283. for I := 0 to FieldDefs.Count - 1 do
  1284. begin
  1285. with DbfFieldDefs.AddFieldDef do
  1286. begin
  1287. FieldName := FieldDefs.Items[I].Name;
  1288. FieldType := FieldDefs.Items[I].DataType;
  1289. if FieldDefs.Items[I].Size > 0 then
  1290. begin
  1291. Size := FieldDefs.Items[I].Size;
  1292. Precision := FieldDefs.Items[I].Precision;
  1293. end else begin
  1294. SetDefaultSize;
  1295. end;
  1296. end;
  1297. end;
  1298. end;
  1299. InitDbfFile(pfExclusiveCreate);
  1300. FDbfFile.CopyDateTimeAsString := FInCopyFrom and FCopyDateTimeAsString;
  1301. FDbfFile.DbfVersion := TableLevelToDbfVersion(FTableLevel);
  1302. FDbfFile.FileLangID := FLanguageID;
  1303. FDbfFile.Open;
  1304. FDbfFile.FinishCreate(DbfFieldDefs, 512);
  1305. // if creating memory table, copy stream pointer
  1306. if FStorage = stoMemory then
  1307. FUserStream := FDbfFile.Stream;
  1308. // create all indexes
  1309. for I := 0 to FIndexDefs.Count-1 do
  1310. begin
  1311. lIndex := FIndexDefs.Items[I];
  1312. lIndexName := ParseIndexName(lIndex.IndexFile);
  1313. FDbfFile.OpenIndex(lIndexName, lIndex.SortField, true, lIndex.Options);
  1314. end;
  1315. except
  1316. // dbf file created?
  1317. if (FDbfFile <> nil) and (FStorage = stoFile) then
  1318. begin
  1319. FreeAndNil(FDbfFile);
  1320. SysUtils.DeleteFile(FAbsolutePath+FTableName);
  1321. end;
  1322. raise;
  1323. end;
  1324. finally
  1325. // free temporary fielddefs
  1326. if tempFieldDefs and Assigned(DbfFieldDefs) then
  1327. DbfFieldDefs.Free;
  1328. FreeAndNil(FDbfFile);
  1329. end;
  1330. end;
  1331. procedure TDbf.EmptyTable;
  1332. begin
  1333. Zap;
  1334. end;
  1335. procedure TDbf.Zap;
  1336. begin
  1337. // are we active?
  1338. CheckActive;
  1339. FDbfFile.Zap;
  1340. end;
  1341. procedure TDbf.RestructureTable(DbfFieldDefs: TDbfFieldDefs; Pack: Boolean);
  1342. begin
  1343. CheckInactive;
  1344. // check field defs for errors
  1345. CheckDbfFieldDefs(DbfFieldDefs);
  1346. // open dbf file
  1347. InitDbfFile(pfExclusiveOpen);
  1348. FDbfFile.Open;
  1349. // do restructure
  1350. try
  1351. FDbfFile.RestructureTable(DbfFieldDefs, Pack);
  1352. finally
  1353. // close file
  1354. FreeAndNil(FDbfFile);
  1355. end;
  1356. end;
  1357. procedure TDbf.PackTable;
  1358. var
  1359. oldIndexName: string;
  1360. begin
  1361. CheckBrowseMode;
  1362. // deselect any index while packing
  1363. oldIndexName := IndexName;
  1364. IndexName := EmptyStr;
  1365. // pack
  1366. FDbfFile.RestructureTable(nil, true);
  1367. // reselect index
  1368. IndexName := oldIndexName;
  1369. end;
  1370. procedure TDbf.CopyFrom(DataSet: TDataSet; FileName: string; DateTimeAsString: Boolean; Level: Integer);
  1371. var
  1372. I: integer;
  1373. begin
  1374. FInCopyFrom := true;
  1375. try
  1376. if Active then
  1377. Close;
  1378. FilePath := ExtractFilePath(FileName);
  1379. TableName := ExtractFileName(FileName);
  1380. FCopyDateTimeAsString := DateTimeAsString;
  1381. TableLevel := Level;
  1382. if not DataSet.Active then
  1383. DataSet.Open;
  1384. DataSet.FieldDefs.Update;
  1385. FieldDefs.Assign(DataSet.FieldDefs);
  1386. IndexDefs.Clear;
  1387. CreateTable;
  1388. Open;
  1389. DataSet.First;
  1390. while not DataSet.EOF do
  1391. begin
  1392. Append;
  1393. for I := 0 to Pred(FieldCount) do
  1394. begin
  1395. if not DataSet.Fields[I].IsNull then
  1396. begin
  1397. if DataSet.Fields[I].DataType = ftDateTime then
  1398. begin
  1399. if FCopyDateTimeAsString then
  1400. begin
  1401. Fields[I].AsString := DataSet.Fields[I].AsString;
  1402. if Assigned(FOnCopyDateTimeAsString) then
  1403. FOnCopyDateTimeAsString(Self, Fields[I], DataSet.Fields[I])
  1404. end else
  1405. Fields[I].AsDateTime := DataSet.Fields[I].AsDateTime;
  1406. end else
  1407. Fields[I].Assign(DataSet.Fields[I]);
  1408. end;
  1409. end;
  1410. Post;
  1411. DataSet.Next;
  1412. end;
  1413. Close;
  1414. finally
  1415. FInCopyFrom := false;
  1416. end;
  1417. end;
  1418. function TDbf.FindRecord(Restart, GoForward: Boolean): Boolean;
  1419. var
  1420. oldRecNo: Integer;
  1421. begin
  1422. CheckBrowseMode;
  1423. DoBeforeScroll;
  1424. Result := false;
  1425. UpdateCursorPos;
  1426. oldRecNo := RecNo;
  1427. try
  1428. FFindRecordFilter := true;
  1429. if GoForward then
  1430. begin
  1431. if Restart then FCursor.First;
  1432. Result := GetRecord(FTempBuffer, gmNext, false) = grOK;
  1433. end else begin
  1434. if Restart then FCursor.Last;
  1435. Result := GetRecord(FTempBuffer, gmPrior, false) = grOK;
  1436. end;
  1437. finally
  1438. FFindRecordFilter := false;
  1439. if not Result then
  1440. begin
  1441. RecNo := oldRecNo;
  1442. end else begin
  1443. CursorPosChanged;
  1444. Resync([]);
  1445. DoAfterScroll;
  1446. end;
  1447. end;
  1448. end;
  1449. {$ifdef SUPPORT_VARIANTS}
  1450. {$ifdef USE_BUGGY_LOOKUP}
  1451. function TDbf.Lookup(const KeyFields: string; const KeyValues: Variant;
  1452. const ResultFields: string): Variant;
  1453. var
  1454. // OldState: TDataSetState;
  1455. retBookmark: TBookmarkStr;
  1456. begin
  1457. Result := Null;
  1458. if VarIsNull(KeyValues) then exit;
  1459. retBookmark := Bookmark;
  1460. DisableControls;
  1461. try
  1462. if LocateRecord(KeyFields, KeyValues, []) then
  1463. begin
  1464. {
  1465. OldState := SetTempState(dsCalcFields);
  1466. // OldState := SetTempState(dsInternalCalc);
  1467. // disable Calculated fields - otherwise were heavy AVs
  1468. // and buffer troubles below
  1469. try
  1470. // CalculateFields(PChar(@FDbfCalcBuffer));
  1471. CalculateFields(TempBuffer);
  1472. // CalculateFields(GetCurrentBuffer);
  1473. if KeyValues = FieldValues[KeyFields] then // there was bug in TDbf.SearchKey
  1474. }
  1475. Result := FieldValues[ResultFields]; // also there may be buffer troubles from above
  1476. {
  1477. finally
  1478. (* else *) RestoreState(OldState);
  1479. end;
  1480. }
  1481. end;
  1482. finally
  1483. Bookmark := retBookmark;
  1484. EnableControls;
  1485. end;
  1486. end;
  1487. {$endif}
  1488. function TDbf.Locate(const KeyFields: string; const KeyValues: Variant; Options: TLocateOptions): Boolean;
  1489. var
  1490. retBookmark: TBookmarkStr;
  1491. begin
  1492. DoBeforeScroll;
  1493. try
  1494. DisableControls;
  1495. retBookmark := Bookmark;
  1496. Result := LocateRecord(KeyFields, KeyValues, Options);
  1497. if Result then
  1498. DoAfterScroll
  1499. else
  1500. Bookmark := retBookmark;
  1501. finally
  1502. EnableControls;
  1503. end;
  1504. end;
  1505. function TDbf.LocateRecord(const KeyFields: String; const KeyValues: Variant;
  1506. Options: TLocateOptions): Boolean;
  1507. var
  1508. lstKeys : TList;
  1509. iIndex : Integer;
  1510. Field : TField;
  1511. bMatchedData : Boolean;
  1512. bVarIsArray : Boolean;
  1513. varCompare : Variant;
  1514. doLinSearch : Boolean;
  1515. pIndexValue : PChar;
  1516. function CompareValues: Boolean;
  1517. var
  1518. sCompare: String;
  1519. begin
  1520. if (Field.DataType = ftString) then
  1521. begin
  1522. sCompare := VarToStr(varCompare);
  1523. if loCaseInsensitive in Options then
  1524. begin
  1525. Result := AnsiCompareText(Field.AsString,sCompare) = 0;
  1526. if not Result and (iIndex = lstKeys.Count - 1) and (loPartialKey in Options) and
  1527. (Length(sCompare) < Length(Field.AsString)) then
  1528. begin
  1529. if Length(sCompare) = 0 then
  1530. Result := true
  1531. else
  1532. Result := AnsiCompareText (Copy (Field.AsString,1,Length (sCompare)),sCompare) = 0;
  1533. end;
  1534. end else begin
  1535. Result := Field.AsString = sCompare;
  1536. if not Result and (iIndex = lstKeys.Count - 1) and (loPartialKey in Options) and
  1537. (Length (sCompare) < Length (Field.AsString)) then
  1538. begin
  1539. if Length (sCompare) = 0 then
  1540. Result := true
  1541. else
  1542. Result := Copy(Field.AsString, 1, Length(sCompare)) = sCompare;
  1543. end;
  1544. end;
  1545. end
  1546. else
  1547. Result := Field.Value = varCompare;
  1548. end;
  1549. var
  1550. searchFlag: TSearchKeyType;
  1551. searchString: string;
  1552. strLength: Integer;
  1553. begin
  1554. Result := false;
  1555. CheckBrowseMode;
  1556. doLinSearch := true;
  1557. // index active?
  1558. if FCursor is TIndexCursor then
  1559. begin
  1560. // matches field to search on?
  1561. if TIndexCursor(FCursor).IndexFile.Expression = KeyFields then
  1562. begin
  1563. // can do index search
  1564. doLinSearch := false;
  1565. if loPartialKey in Options then
  1566. searchFlag := stGreaterEqual
  1567. else
  1568. searchFlag := stEqual;
  1569. Result := SearchKey(KeyValues, searchFlag);
  1570. if Result and (loPartialKey in Options) then
  1571. begin
  1572. searchString := VarToStr(KeyValues);
  1573. strLength := Length(searchString);
  1574. pIndexValue := TIndexCursor(FCursor).IndexFile.ExtractKeyFromBuffer(GetCurrentBuffer);
  1575. if loCaseInsensitive in Options then
  1576. begin
  1577. Result := AnsiStrLIComp(pIndexValue, PChar(searchString), strLength) = 0;
  1578. end else begin
  1579. Result := StrLComp(pIndexValue, PChar(searchString), strLength) = 0;
  1580. end;
  1581. end;
  1582. end;
  1583. end;
  1584. if doLinSearch then
  1585. begin
  1586. bVarIsArray := false;
  1587. CursorPosChanged;
  1588. lstKeys := TList.Create;
  1589. try
  1590. GetFieldList(lstKeys, KeyFields);
  1591. if VarArrayDimCount(KeyValues) = 0 then
  1592. bMatchedData := lstKeys.Count = 1
  1593. else if VarArrayDimCount (KeyValues) = 1 then
  1594. begin
  1595. bMatchedData := VarArrayHighBound (KeyValues,1) + 1 = lstKeys.Count;
  1596. bVarIsArray := true;
  1597. end else
  1598. bMatchedData := false;
  1599. if bMatchedData then
  1600. begin
  1601. First;
  1602. while not Eof and not Result Do
  1603. begin
  1604. Result := true;
  1605. iIndex := 0;
  1606. while Result and (iIndex < lstKeys.Count) Do
  1607. begin
  1608. Field := TField (lstKeys [iIndex]);
  1609. if bVarIsArray then
  1610. varCompare := KeyValues [iIndex]
  1611. else
  1612. varCompare := KeyValues;
  1613. Result := CompareValues;
  1614. iIndex := iIndex + 1;
  1615. end;
  1616. if not Result then
  1617. Next;
  1618. end;
  1619. end;
  1620. finally
  1621. lstKeys.Free;
  1622. end;
  1623. end;
  1624. end;
  1625. {$endif}
  1626. procedure TDbf.TryExclusive;
  1627. begin
  1628. // are we active?
  1629. if Active then
  1630. begin
  1631. // already in exclusive mode?
  1632. FDbfFile.TryExclusive;
  1633. // update file mode
  1634. FExclusive := not FDbfFile.IsSharedAccess;
  1635. FReadOnly := FDbfFile.Mode = pfReadOnly;
  1636. end else begin
  1637. // just set exclusive to true
  1638. FExclusive := true;
  1639. FReadOnly := false;
  1640. end;
  1641. end;
  1642. procedure TDbf.EndExclusive;
  1643. begin
  1644. if Active then
  1645. begin
  1646. // call file handler
  1647. FDbfFile.EndExclusive;
  1648. // update file mode
  1649. FExclusive := not FDbfFile.IsSharedAccess;
  1650. FReadOnly := FDbfFile.Mode = pfReadOnly;
  1651. end else begin
  1652. // just set exclusive to false
  1653. FExclusive := false;
  1654. end;
  1655. end;
  1656. function TDbf.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; {override virtual}
  1657. var
  1658. MemoPageNo: Integer;
  1659. MemoFieldNo: Integer;
  1660. lBlob: TDbfBlobStream;
  1661. begin
  1662. // check if in editing mode if user wants to write
  1663. if (Mode = bmWrite) or (Mode = bmReadWrite) then
  1664. if not (State in [dsEdit, dsInsert]) then
  1665. {$ifdef DELPHI_3}
  1666. DatabaseError(SNotEditing);
  1667. {$else}
  1668. DatabaseError(SNotEditing, Self);
  1669. {$endif}
  1670. // already created a `placeholder' blob for this field?
  1671. MemoFieldNo := Field.FieldNo - 1;
  1672. if FBlobStreams^[MemoFieldNo] = nil then
  1673. FBlobStreams^[MemoFieldNo] := TDbfBlobStream.Create(Field);
  1674. lBlob := FBlobStreams^[MemoFieldNo].AddReference;
  1675. // update pageno of blob <-> location where to read/write in memofile
  1676. if FDbfFile.GetFieldData(Field.FieldNo-1, ftInteger, GetCurrentBuffer, @MemoPageNo) then
  1677. begin
  1678. // read blob? different blob?
  1679. if (Mode = bmRead) or (Mode = bmReadWrite) then
  1680. begin
  1681. if MemoPageNo <> lBlob.MemoRecNo then
  1682. begin
  1683. FDbfFile.MemoFile.ReadMemo(MemoPageNo, lBlob);
  1684. lBlob.ReadSize := lBlob.Size;
  1685. lBlob.Translate(false);
  1686. end;
  1687. end else begin
  1688. lBlob.Size := 0;
  1689. lBlob.ReadSize := 0;
  1690. end;
  1691. lBlob.MemoRecNo := MemoPageNo;
  1692. end else
  1693. if not lBlob.Dirty or (Mode = bmWrite) then
  1694. begin
  1695. // reading and memo is empty and not written yet, or rewriting
  1696. lBlob.Size := 0;
  1697. lBlob.ReadSize := 0;
  1698. lBlob.MemoRecNo := 0;
  1699. end;
  1700. { this is a hack, we actually need to know per user who's modifying, and who is not }
  1701. { Mode is more like: the mode of the last "creation" }
  1702. { if create/free is nested, then everything will be alright, i think ;-) }
  1703. lBlob.Mode := Mode;
  1704. { this is a hack: we actually need to know per user what it's position is }
  1705. lBlob.Position := 0;
  1706. Result := lBlob;
  1707. end;
  1708. {$ifdef SUPPORT_NEW_TRANSLATE}
  1709. function TDbf.Translate(Src, Dest: PChar; ToOem: Boolean): Integer; {override virtual}
  1710. var
  1711. FromCP, ToCP: Cardinal;
  1712. begin
  1713. if (Src <> nil) and (Dest <> nil) then
  1714. begin
  1715. if Assigned(FOnTranslate) then
  1716. begin
  1717. Result := FOnTranslate(Self, Src, Dest, ToOem);
  1718. if Result = -1 then
  1719. Result := StrLen(Dest);
  1720. end else begin
  1721. if FTranslationMode <> tmNoneNeeded then
  1722. begin
  1723. if ToOem then
  1724. begin
  1725. FromCP := GetACP;
  1726. ToCP := FDbfFile.UseCodePage;
  1727. end else begin
  1728. FromCP := FDbfFile.UseCodePage;
  1729. ToCP := GetACP;
  1730. end;
  1731. end else begin
  1732. FromCP := GetACP;
  1733. ToCP := FromCP;
  1734. end;
  1735. Result := TranslateString(FromCP, ToCP, Src, Dest, -1);
  1736. end;
  1737. end else
  1738. Result := 0;
  1739. end;
  1740. {$else}
  1741. procedure TDbf.Translate(Src, Dest: PChar; ToOem: Boolean); {override virtual}
  1742. var
  1743. FromCP, ToCP: Cardinal;
  1744. begin
  1745. if (Src <> nil) and (Dest <> nil) then
  1746. begin
  1747. if Assigned(FOnTranslate) then
  1748. begin
  1749. FOnTranslate(Self, Src, Dest, ToOem);
  1750. end else begin
  1751. if FTranslationMode <> tmNoneNeeded then
  1752. begin
  1753. if ToOem then
  1754. begin
  1755. FromCP := GetACP;
  1756. ToCP := FDbfFile.UseCodePage;
  1757. end else begin
  1758. FromCP := FDbfFile.UseCodePage;
  1759. ToCP := GetACP;
  1760. end;
  1761. TranslateString(FromCP, ToCP, Src, Dest, -1);
  1762. end;
  1763. end;
  1764. end;
  1765. end;
  1766. {$endif}
  1767. procedure TDbf.ClearCalcFields(Buffer: PChar);
  1768. var
  1769. lRealBuffer, lCalcBuffer: PChar;
  1770. begin
  1771. lRealBuffer := @pDbfRecord(Buffer)^.DeletedFlag;
  1772. lCalcBuffer := lRealBuffer + FDbfFile.RecordSize;
  1773. FillChar(lCalcBuffer^, CalcFieldsSize, 0);
  1774. end;
  1775. procedure TDbf.InternalSetToRecord(Buffer: PChar); {override virtual abstract from TDataset}
  1776. var
  1777. pRecord: pDbfRecord;
  1778. begin
  1779. if Buffer <> nil then
  1780. begin
  1781. pRecord := pDbfRecord(Buffer);
  1782. if pRecord^.BookmarkFlag = bfInserted then
  1783. begin
  1784. // do what ???
  1785. end else begin
  1786. FCursor.SequentialRecNo := pRecord^.SequentialRecNo;
  1787. end;
  1788. end;
  1789. end;
  1790. function TDbf.IsCursorOpen: Boolean; {override virtual abstract from TDataset}
  1791. begin
  1792. Result := FCursor <> nil;
  1793. end;
  1794. function TDbf.FieldDefsStored: Boolean;
  1795. begin
  1796. Result := StoreDefs and (FieldDefs.Count > 0);
  1797. end;
  1798. procedure TDbf.SetBookmarkFlag(Buffer: PChar; Value: TBookmarkFlag); {override virtual abstract from TDataset}
  1799. begin
  1800. pDbfRecord(Buffer)^.BookmarkFlag := Value;
  1801. end;
  1802. procedure TDbf.SetBookmarkData(Buffer: PChar; Data: Pointer); {override virtual abstract from TDataset}
  1803. begin
  1804. pDbfRecord(Buffer)^.BookmarkData := pBookmarkData(Data)^;
  1805. end;
  1806. procedure TDbf.SetFieldData(Field: TField; Buffer: Pointer); {override virtual abstract from TDataset}
  1807. var
  1808. pRecord: pDbfRecord;
  1809. Dst: Pointer;
  1810. begin
  1811. if (Field.FieldNo >= 0) then
  1812. begin
  1813. pRecord := pDbfRecord(ActiveBuffer);
  1814. dst := @pRecord^.DeletedFlag;
  1815. FDbfFile.SetFieldData(Field.FieldNo - 1,Field.DataType,Buffer,Dst);
  1816. end else begin { ***** fkCalculated, fkLookup ***** }
  1817. pRecord := pDbfRecord(CalcBuffer);
  1818. Dst := @pRecord^.DeletedFlag;
  1819. Inc(PChar(Dst), RecordSize + Field.Offset);
  1820. // Boolean(dst^) := LongBool(Buffer);
  1821. // if Boolean(dst^) then begin
  1822. // Inc(Integer(dst), 1);
  1823. if Buffer <> nil then
  1824. Move(Buffer^, Dst^, Field.DataSize)
  1825. else
  1826. FillChar(Dst^, Field.DataSize, #0);
  1827. // end;
  1828. end; { end of ***** fkCalculated, fkLookup ***** }
  1829. if not (State in [dsCalcFields, dsFilter, dsNewValue]) then begin
  1830. DataEvent(deFieldChange, Longint(Field));
  1831. end;
  1832. end;
  1833. // this function counts real number of records: skip deleted records, filter, etc.
  1834. // warning: is very slow, compared to GetRecordCount
  1835. function TDbf.GetExactRecordCount: Integer;
  1836. var
  1837. prevRecNo: Integer;
  1838. getRes: TGetResult;
  1839. begin
  1840. // init vars
  1841. Result := 0;
  1842. // check if FCursor open
  1843. if FCursor = nil then
  1844. exit;
  1845. // store current position
  1846. prevRecNo := FCursor.SequentialRecNo;
  1847. FCursor.First;
  1848. repeat
  1849. // repeatedly retrieve next record until eof encountered
  1850. getRes := GetRecord(FTempBuffer, gmNext, true);
  1851. if getRes = grOk then
  1852. inc(Result);
  1853. until getRes <> grOk;
  1854. // restore current position
  1855. FCursor.SequentialRecNo := prevRecNo;
  1856. end;
  1857. // this functions returns the physical number of records present in file
  1858. function TDbf.GetPhysicalRecordCount: Integer;
  1859. begin
  1860. if FDbfFile <> nil then
  1861. Result := FDbfFile.RecordCount
  1862. else
  1863. Result := 0
  1864. end;
  1865. // this function is just for the grid scrollbars
  1866. // it doesn't have to be perfectly accurate, but fast.
  1867. function TDbf.GetRecordCount: Integer; {override virtual}
  1868. begin
  1869. if FCursor <> nil then
  1870. Result := FCursor.SequentialRecordCount
  1871. else
  1872. Result := 0
  1873. end;
  1874. // this function is just for the grid scrollbars
  1875. // it doesn't have to be perfectly accurate, but fast.
  1876. function TDbf.GetRecNo: Integer; {override virtual}
  1877. var
  1878. pBuffer: pointer;
  1879. begin
  1880. if State = dsCalcFields then
  1881. pBuffer := CalcBuffer
  1882. else
  1883. pBuffer := ActiveBuffer;
  1884. Result := pDbfRecord(pBuffer)^.SequentialRecNo;
  1885. end;
  1886. procedure TDbf.SetRecNo(Value: Integer); {override virtual}
  1887. begin
  1888. CheckBrowseMode;
  1889. if Value = RecNo then
  1890. exit;
  1891. DoBeforeScroll;
  1892. FCursor.SequentialRecNo := Value;
  1893. CursorPosChanged;
  1894. Resync([]);
  1895. DoAfterScroll;
  1896. end;
  1897. function TDbf.GetCanModify: Boolean; {override;}
  1898. begin
  1899. if FReadOnly or (csDesigning in ComponentState) then
  1900. Result := false
  1901. else
  1902. Result := FTranslationMode > tmNoneAvailable;
  1903. end;
  1904. {$ifdef SUPPORT_DEFCHANGED}
  1905. procedure TDbf.DefChanged(Sender: TObject);
  1906. begin
  1907. StoreDefs := true;
  1908. end;
  1909. {$endif}
  1910. procedure TDbf.ParseFilter(const AFilter: string);
  1911. begin
  1912. // parser created?
  1913. if Length(AFilter) > 0 then
  1914. begin
  1915. if (FParser = nil) and (FDbfFile <> nil) then
  1916. begin
  1917. FParser := TDbfParser.Create(FDbfFile);
  1918. // we need translated (to ANSI) strings
  1919. FParser.RawStringFields := false;
  1920. end;
  1921. // have a parser now?
  1922. if FParser <> nil then
  1923. begin
  1924. // set options
  1925. FParser.PartialMatch := not (foNoPartialCompare in FilterOptions);
  1926. FParser.CaseInsensitive := foCaseInsensitive in FilterOptions;
  1927. // parse expression
  1928. FParser.ParseExpression(AFilter);
  1929. end;
  1930. end;
  1931. end;
  1932. procedure TDbf.SetFilterText(const Value: String);
  1933. begin
  1934. if Value = Filter then
  1935. exit;
  1936. // parse
  1937. ParseFilter(Value);
  1938. // call dataset method
  1939. inherited;
  1940. // refilter dataset if filtered
  1941. if (FDbfFile <> nil) and Filtered then Refresh;
  1942. end;
  1943. procedure TDbf.SetFiltered(Value: Boolean); {override;}
  1944. begin
  1945. if Value = Filtered then
  1946. exit;
  1947. // pass on to ancestor
  1948. inherited;
  1949. // only refresh if active
  1950. if FCursor <> nil then
  1951. Refresh;
  1952. end;
  1953. procedure TDbf.SetFilePath(const Value: string);
  1954. begin
  1955. CheckInactive;
  1956. FRelativePath := Value;
  1957. if Length(FRelativePath) > 0 then
  1958. FRelativePath := IncludeTrailingPathDelimiter(FRelativePath);
  1959. if IsFullFilePath(Value) then
  1960. begin
  1961. FAbsolutePath := IncludeTrailingPathDelimiter(Value);
  1962. end else begin
  1963. FAbsolutePath := GetCompletePath(DbfBasePath(), FRelativePath);
  1964. end;
  1965. end;
  1966. procedure TDbf.SetTableName(const s: string);
  1967. var
  1968. lPath: string;
  1969. begin
  1970. FTableName := ExtractFileName(s);
  1971. lPath := ExtractFilePath(s);
  1972. if (Length(lPath) > 0) then
  1973. FilePath := lPath;
  1974. // force IDE to reread fielddefs when a different file is opened
  1975. {$ifdef SUPPORT_FIELDDEFS_UPDATED}
  1976. FieldDefs.Updated := false;
  1977. {$else}
  1978. // TODO ... ??
  1979. {$endif}
  1980. end;
  1981. procedure TDbf.SetDbfIndexDefs(const Value: TDbfIndexDefs);
  1982. begin
  1983. FIndexDefs.Assign(Value);
  1984. end;
  1985. procedure TDbf.SetLanguageID(NewID: Byte);
  1986. begin
  1987. CheckInactive;
  1988. FLanguageID := NewID;
  1989. end;
  1990. procedure TDbf.SetTableLevel(const NewLevel: Integer);
  1991. begin
  1992. if NewLevel <> FTableLevel then
  1993. begin
  1994. // check validity
  1995. if not ((NewLevel = 3) or (NewLevel = 4) or (NewLevel = 7) or (NewLevel = 25)) then
  1996. exit;
  1997. // can only assign tablelevel if table is closed
  1998. CheckInactive;
  1999. FTableLevel := NewLevel;
  2000. end;
  2001. end;
  2002. function TDbf.GetIndexName: string;
  2003. begin
  2004. Result := FIndexName;
  2005. end;
  2006. function TDbf.CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer;
  2007. const
  2008. RetCodes: array[Boolean, Boolean] of ShortInt = ((2,-1),(1,0));
  2009. var
  2010. b1,b2: Integer;
  2011. begin
  2012. // Check for uninitialized bookmarks
  2013. Result := RetCodes[Bookmark1 = nil, Bookmark2 = nil];
  2014. if (Result = 2) then
  2015. begin
  2016. b1 := PInteger(Bookmark1)^;
  2017. b2 := PInteger(Bookmark2)^;
  2018. if b1 < b2 then Result := -1
  2019. else if b1 > b2 then Result := 1
  2020. else Result := 0;
  2021. end;
  2022. end;
  2023. function TDbf.GetVersion: string;
  2024. begin
  2025. Result := Format('%d.%02d', [TDBF_MAJOR_VERSION, TDBF_MINOR_VERSION]);
  2026. end;
  2027. procedure TDbf.SetVersion(const S: string);
  2028. begin
  2029. // What an idea...
  2030. end;
  2031. function TDbf.ParseIndexName(const AIndexName: string): string;
  2032. begin
  2033. // if no ext, then it is a MDX tag, get complete only if it is a filename
  2034. // MDX: get first 10 characters only
  2035. if Length(ExtractFileExt(AIndexName)) > 0 then
  2036. Result := GetCompleteFileName(FAbsolutePath, AIndexName)
  2037. else
  2038. Result := AIndexName;
  2039. end;
  2040. procedure TDbf.RegenerateIndexes;
  2041. begin
  2042. CheckBrowseMode;
  2043. FDbfFile.RegenerateIndexes;
  2044. end;
  2045. {$ifdef SUPPORT_DEFAULT_PARAMS}
  2046. procedure TDbf.AddIndex(const AIndexName, AFields: String; Options: TIndexOptions; const DescFields: String='');
  2047. {$else}
  2048. procedure TDbf.AddIndex(const AIndexName, AFields: String; Options: TIndexOptions);
  2049. {$endif}
  2050. var
  2051. lIndexFileName: string;
  2052. begin
  2053. CheckActive;
  2054. lIndexFileName := ParseIndexName(AIndexName);
  2055. FDbfFile.OpenIndex(lIndexFileName, AFields, true, Options);
  2056. // refresh our indexdefs
  2057. InternalInitFieldDefs;
  2058. end;
  2059. procedure TDbf.SetIndexName(AIndexName: string);
  2060. var
  2061. lRecNo: Integer;
  2062. begin
  2063. FIndexName := AIndexName;
  2064. if FDbfFile = nil then
  2065. exit;
  2066. // get accompanying index file
  2067. AIndexName := ParseIndexName(Trim(AIndexName));
  2068. FIndexFile := FDbfFile.GetIndexByName(AIndexName);
  2069. // store current lRecNo
  2070. if FCursor = nil then
  2071. begin
  2072. lRecNo := 1;
  2073. end else begin
  2074. UpdateCursorPos;
  2075. lRecNo := FCursor.PhysicalRecNo;
  2076. end;
  2077. // select new cursor
  2078. FreeAndNil(FCursor);
  2079. if FIndexFile <> nil then
  2080. begin
  2081. FCursor := TIndexCursor.Create(FIndexFile);
  2082. // select index
  2083. FIndexFile.IndexName := AIndexName;
  2084. // check if can activate master link
  2085. CheckMasterRange;
  2086. end else begin
  2087. FCursor := TDbfCursor.Create(FDbfFile);
  2088. FIndexName := EmptyStr;
  2089. end;
  2090. // reset previous lRecNo
  2091. FCursor.PhysicalRecNo := lRecNo;
  2092. // refresh records
  2093. if State = dsBrowse then
  2094. Resync([]);
  2095. // warn user if selecting non-existing index
  2096. if (FCursor = nil) and (AIndexName <> EmptyStr) then
  2097. raise EDbfError.CreateFmt(STRING_INDEX_NOT_EXIST, [AIndexName]);
  2098. end;
  2099. function TDbf.GetIndexFieldNames: string;
  2100. var
  2101. lIndexDef: TDbfIndexDef;
  2102. begin
  2103. lIndexDef := FIndexDefs.GetIndexByName(IndexName);
  2104. if lIndexDef = nil then
  2105. Result := EmptyStr
  2106. else
  2107. Result := lIndexDef.SortField;
  2108. end;
  2109. procedure tdbf.SetIndexFieldNames(const Value: string);
  2110. var
  2111. lIndexDef: TDbfIndexDef;
  2112. begin
  2113. // Exception if index not found?
  2114. lIndexDef := FIndexDefs.GetIndexByField(Value);
  2115. if lIndexDef = nil then
  2116. IndexName := EmptyStr
  2117. else
  2118. IndexName := lIndexDef.IndexFile;
  2119. end;
  2120. procedure TDbf.DeleteIndex(const AIndexName: string);
  2121. var
  2122. lIndexFileName: string;
  2123. begin
  2124. // extract absolute path if NDX file
  2125. lIndexFileName := ParseIndexName(AIndexName);
  2126. // try to delete index
  2127. FDbfFile.DeleteIndex(lIndexFileName);
  2128. // refresh index defs
  2129. InternalInitFieldDefs;
  2130. end;
  2131. procedure TDbf.OpenIndexFile(IndexFile: string);
  2132. var
  2133. lIndexFileName: string;
  2134. begin
  2135. CheckActive;
  2136. // make absolute path
  2137. lIndexFileName := GetCompleteFileName(FAbsolutePath, IndexFile);
  2138. // open index
  2139. FDbfFile.OpenIndex(lIndexFileName, '', false, []);
  2140. end;
  2141. procedure TDbf.CloseIndexFile(const AIndexName: string);
  2142. var
  2143. lIndexFileName: string;
  2144. begin
  2145. CheckActive;
  2146. // make absolute path
  2147. lIndexFileName := GetCompleteFileName(FAbsolutePath, AIndexName);
  2148. // close this index
  2149. FDbfFile.CloseIndex(lIndexFileName);
  2150. end;
  2151. procedure TDbf.RepageIndexFile(const AIndexFile: string);
  2152. begin
  2153. if FDbfFile <> nil then
  2154. FDbfFile.RepageIndex(ParseIndexName(AIndexFile));
  2155. end;
  2156. procedure TDbf.CompactIndexFile(const AIndexFile: string);
  2157. begin
  2158. if FDbfFile <> nil then
  2159. FDbfFile.CompactIndex(ParseIndexName(AIndexFile));
  2160. end;
  2161. procedure TDbf.GetFileNames(Strings: TStrings; Files: TDbfFileNames);
  2162. var
  2163. I: Integer;
  2164. begin
  2165. Strings.Clear;
  2166. if FDbfFile <> nil then
  2167. begin
  2168. if dfDbf in Files then
  2169. Strings.Add(FDbfFile.FileName);
  2170. if (dfMemo in Files) and (FDbfFile.MemoFile <> nil) then
  2171. Strings.Add(FDbfFile.MemoFile.FileName);
  2172. if dfIndex in Files then
  2173. for I := 0 to Pred(FDbfFile.IndexFiles.Count) do
  2174. Strings.Add(TPagedFile(FDbfFile.IndexFiles.Items[I]).FileName);
  2175. end else
  2176. Strings.Add(IncludeTrailingPathDelimiter(FilePathFull) + TableName);
  2177. end;
  2178. {$ifdef SUPPORT_DEFAULT_PARAMS}
  2179. function TDbf.GetFileNames(Files: TDbfFileNames (* = [dfDbf] *) ): string;
  2180. {$else}
  2181. function TDbf.GetFileNamesString(Files: TDbfFileNames ): string;
  2182. {$endif}
  2183. var
  2184. sl: TStrings;
  2185. begin
  2186. sl := TStringList.Create;
  2187. try
  2188. GetFileNames(sl, Files);
  2189. Result := sl.Text;
  2190. finally
  2191. sl.Free;
  2192. end;
  2193. end;
  2194. procedure TDbf.GetIndexNames(Strings: TStrings);
  2195. begin
  2196. CheckActive;
  2197. Strings.Assign(DbfFile.IndexNames)
  2198. end;
  2199. procedure TDbf.GetAllIndexFiles(Strings: TStrings);
  2200. var
  2201. SR: TSearchRec;
  2202. begin
  2203. CheckActive;
  2204. Strings.Clear;
  2205. if SysUtils.FindFirst(IncludeTrailingPathDelimiter(ExtractFilePath(FDbfFile.FileName))
  2206. + '*.NDX', faAnyFile, SR) = 0 then
  2207. begin
  2208. repeat
  2209. Strings.Add(SR.Name);
  2210. until SysUtils.FindNext(SR)<>0;
  2211. SysUtils.FindClose(SR);
  2212. end;
  2213. end;
  2214. function TDbf.GetPhysicalRecNo: Integer;
  2215. var
  2216. pBuffer: pointer;
  2217. begin
  2218. // check if active, test state: if inserting, then -1
  2219. if (FCursor <> nil) and (State <> dsInsert) then
  2220. begin
  2221. if State = dsCalcFields then
  2222. pBuffer := CalcBuffer
  2223. else
  2224. pBuffer := ActiveBuffer;
  2225. Result := pDbfRecord(pBuffer)^.BookmarkData.PhysicalRecNo;
  2226. end else
  2227. Result := -1;
  2228. end;
  2229. procedure TDbf.SetPhysicalRecNo(const NewRecNo: Integer);
  2230. begin
  2231. // editing?
  2232. CheckBrowseMode;
  2233. DoBeforeScroll;
  2234. FCursor.PhysicalRecNo := NewRecNo;
  2235. CursorPosChanged;
  2236. Resync([]);
  2237. DoAfterScroll;
  2238. end;
  2239. function TDbf.GetDbfFieldDefs: TDbfFieldDefs;
  2240. begin
  2241. if FDbfFile <> nil then
  2242. Result := FDbfFile.FieldDefs
  2243. else
  2244. Result := nil;
  2245. end;
  2246. procedure TDbf.SetShowDeleted(Value: Boolean);
  2247. begin
  2248. // test if changed
  2249. if Value <> FShowDeleted then
  2250. begin
  2251. // store new value
  2252. FShowDeleted := Value;
  2253. // refresh view only if active
  2254. if FCursor <> nil then
  2255. Refresh;
  2256. end;
  2257. end;
  2258. function TDbf.IsDeleted: Boolean;
  2259. var
  2260. src: PChar;
  2261. begin
  2262. src := GetCurrentBuffer;
  2263. IsDeleted := (src=nil) or (src^ = '*')
  2264. end;
  2265. procedure TDbf.Undelete;
  2266. var
  2267. src: PChar;
  2268. begin
  2269. if State <> dsEdit then
  2270. inherited Edit;
  2271. // get active buffer
  2272. src := GetCurrentBuffer;
  2273. if (src <> nil) and (src^ = '*') then
  2274. begin
  2275. // notify indexes record is about to be recalled
  2276. FDbfFile.RecordRecalled(FCursor.PhysicalRecNo, src);
  2277. // recall record
  2278. src^ := ' ';
  2279. FDbfFile.WriteRecord(FCursor.PhysicalRecNo, src);
  2280. end;
  2281. end;
  2282. procedure TDbf.CancelRange;
  2283. begin
  2284. if FIndexFile = nil then
  2285. exit;
  2286. // disable current range if any
  2287. FIndexFile.CancelRange;
  2288. // reretrieve previous and next records
  2289. Refresh;
  2290. end;
  2291. procedure TDbf.SetRangeBuffer(LowRange: PChar; HighRange: PChar);
  2292. begin
  2293. if FIndexFile = nil then
  2294. exit;
  2295. FIndexFile.SetRange(LowRange, HighRange);
  2296. // go to first in this range
  2297. if Active then
  2298. inherited First;
  2299. end;
  2300. {$ifdef SUPPORT_VARIANTS}
  2301. procedure TDbf.SetRange(LowRange: Variant; HighRange: Variant);
  2302. var
  2303. LowBuf, HighBuf: array[0..100] of Char;
  2304. begin
  2305. if (FIndexFile = nil) or VarIsNull(LowRange) or VarIsNull(HighRange) then
  2306. exit;
  2307. // convert variants to index key type
  2308. TIndexCursor(FCursor).VariantToBuffer(LowRange, @LowBuf[0]);
  2309. TIndexCursor(FCursor).VariantToBuffer(HighRange, @HighBuf[0]);
  2310. SetRangeBuffer(@LowBuf[0], @HighBuf[0]);
  2311. end;
  2312. {$endif}
  2313. procedure TDbf.SetRangePChar(LowRange: PChar; HighRange: PChar);
  2314. var
  2315. LowBuf, HighBuf: array [0..100] of Char;
  2316. LowPtr, HighPtr: PChar;
  2317. begin
  2318. if FIndexFile = nil then
  2319. exit;
  2320. // convert to pchars
  2321. LowPtr := TIndexCursor(FCursor).CheckUserKey(LowRange, @LowBuf[0]);
  2322. HighPtr := TIndexCursor(FCursor).CheckUserKey(HighRange, @HighBuf[0]);
  2323. SetRangeBuffer(LowPtr, HighPtr);
  2324. end;
  2325. procedure TDbf.ExtractKey(KeyBuffer: PChar);
  2326. begin
  2327. if FIndexFile <> nil then
  2328. StrCopy(FIndexFile.ExtractKeyFromBuffer(GetCurrentBuffer), KeyBuffer)
  2329. else
  2330. KeyBuffer[0] := #0;
  2331. end;
  2332. function TDbf.GetKeySize: Integer;
  2333. begin
  2334. if FCursor is TIndexCursor then
  2335. Result := TIndexCursor(FCursor).IndexFile.KeyLen
  2336. else
  2337. Result := 0;
  2338. end;
  2339. {$ifdef SUPPORT_VARIANTS}
  2340. function TDbf.SearchKey(Key: Variant; SearchType: TSearchKeyType): Boolean;
  2341. var
  2342. TempBuffer: array [0..100] of Char;
  2343. begin
  2344. if (FIndexFile = nil) or VarIsNull(Key) then
  2345. begin
  2346. Result := false;
  2347. exit;
  2348. end;
  2349. // FIndexFile <> nil -> FCursor as TIndexCursor <> nil
  2350. TIndexCursor(FCursor).VariantToBuffer(Key, @TempBuffer[0]);
  2351. Result := SearchKeyBuffer(@TempBuffer[0], SearchType);
  2352. end;
  2353. {$endif}
  2354. function TDbf.PrepareKey(Buffer: Pointer; BufferType: TExpressionType): PChar;
  2355. begin
  2356. if FIndexFile = nil then
  2357. begin
  2358. Result := nil;
  2359. exit;
  2360. end;
  2361. Result := TIndexCursor(FCursor).IndexFile.PrepareKey(Buffer, BufferType);
  2362. end;
  2363. function TDbf.SearchKeyPChar(Key: PChar; SearchType: TSearchKeyType): Boolean;
  2364. var
  2365. StringBuf: array [0..100] of Char;
  2366. begin
  2367. if FIndexFile = nil then
  2368. begin
  2369. Result := false;
  2370. exit;
  2371. end;
  2372. Result := SearchKeyBuffer(TIndexCursor(FCursor).CheckUserKey(Key, @StringBuf[0]), SearchType);
  2373. end;
  2374. function TDbf.SearchKeyBuffer(Buffer: PChar; SearchType: TSearchKeyType): Boolean;
  2375. var
  2376. matchRes: Integer;
  2377. begin
  2378. if FIndexFile = nil then
  2379. begin
  2380. Result := false;
  2381. exit;
  2382. end;
  2383. CheckBrowseMode;
  2384. Result := FIndexFile.SearchKey(Buffer, SearchType);
  2385. { if found, then retrieve new current record }
  2386. if Result then
  2387. begin
  2388. CursorPosChanged;
  2389. Resync([]);
  2390. UpdateCursorPos;
  2391. { recno could have been changed due to deleted record, check if still matches }
  2392. matchRes := TIndexCursor(FCursor).IndexFile.MatchKey(Buffer);
  2393. case SearchType of
  2394. stEqual: Result := matchRes = 0;
  2395. stGreater: Result := (not Eof) and (matchRes < 0);
  2396. stGreaterEqual: Result := (not Eof) and (matchRes <= 0);
  2397. end;
  2398. end;
  2399. end;
  2400. procedure TDbf.UpdateIndexDefs;
  2401. begin
  2402. FieldDefs.Update;
  2403. end;
  2404. // A hack to upgrade method visibility, only necessary for FPC 1.0.x
  2405. {$ifdef VER1_0}
  2406. procedure TDbf.DataEvent(Event: TDataEvent; Info: Longint);
  2407. begin
  2408. inherited;
  2409. end;
  2410. {$endif}
  2411. { Master / Detail }
  2412. procedure TDbf.CheckMasterRange;
  2413. begin
  2414. if FMasterLink.Active and FMasterLink.ValidExpression and (FIndexFile <> nil) then
  2415. UpdateRange;
  2416. end;
  2417. procedure TDbf.UpdateRange;
  2418. var
  2419. fieldsVal: PChar;
  2420. begin
  2421. fieldsVal := FMasterLink.FieldsVal;
  2422. fieldsVal := TIndexCursor(FCursor).IndexFile.PrepareKey(fieldsVal, FMasterLink.Parser.ResultType);
  2423. SetRangeBuffer(fieldsVal, fieldsVal);
  2424. end;
  2425. procedure TDbf.MasterChanged(Sender: TObject);
  2426. begin
  2427. CheckBrowseMode;
  2428. CheckMasterRange;
  2429. end;
  2430. procedure TDbf.MasterDisabled(Sender: TObject);
  2431. begin
  2432. CancelRange;
  2433. end;
  2434. function TDbf.GetDataSource: TDataSource;
  2435. begin
  2436. Result := FMasterLink.DataSource;
  2437. end;
  2438. procedure TDbf.SetDataSource(Value: TDataSource);
  2439. begin
  2440. {$ifndef FPC}
  2441. if IsLinkedTo(Value) then
  2442. begin
  2443. {$ifdef DELPHI_4}
  2444. DatabaseError(SCircularDataLink, Self);
  2445. {$else}
  2446. DatabaseError(SCircularDataLink);
  2447. {$endif}
  2448. end;
  2449. {$endif}
  2450. FMasterLink.DataSource := Value;
  2451. end;
  2452. function TDbf.GetMasterFields: string;
  2453. begin
  2454. Result := FMasterLink.FieldNames;
  2455. end;
  2456. procedure TDbf.SetMasterFields(const Value: string);
  2457. begin
  2458. FMasterLink.FieldNames := Value;
  2459. end;
  2460. //==========================================================
  2461. //============ TDbfIndexDefs
  2462. //==========================================================
  2463. constructor TDbfIndexDefs.Create(AOwner: TDbf);
  2464. begin
  2465. inherited Create(TDbfIndexDef);
  2466. FOwner := AOwner;
  2467. end;
  2468. function TDbfIndexDefs.Add: TDbfIndexDef;
  2469. begin
  2470. Result := TDbfIndexDef(inherited Add);
  2471. end;
  2472. procedure TDbfIndexDefs.SetItem(N: Integer; Value: TDbfIndexDef);
  2473. begin
  2474. inherited SetItem(N, Value);
  2475. end;
  2476. function TDbfIndexDefs.GetItem(N: Integer): TDbfIndexDef;
  2477. begin
  2478. Result := TDbfIndexDef(inherited GetItem(N));
  2479. end;
  2480. function TDbfIndexDefs.GetOwner: tpersistent;
  2481. begin
  2482. Result := FOwner;
  2483. end;
  2484. function TDbfIndexDefs.GetIndexByName(const Name: string): TDbfIndexDef;
  2485. var
  2486. I: Integer;
  2487. lIndex: TDbfIndexDef;
  2488. begin
  2489. for I := 0 to Count-1 do
  2490. begin
  2491. lIndex := Items[I];
  2492. if lIndex.IndexFile = Name then
  2493. begin
  2494. Result := lIndex;
  2495. exit;
  2496. end
  2497. end;
  2498. Result := nil;
  2499. end;
  2500. function TDbfIndexDefs.GetIndexByField(const Name: string): TDbfIndexDef;
  2501. var
  2502. lIndex: TDbfIndexDef;
  2503. searchStr: string;
  2504. i: integer;
  2505. begin
  2506. searchStr := AnsiUpperCase(Trim(Name));
  2507. Result := nil;
  2508. if searchStr = EmptyStr then
  2509. exit;
  2510. for I := 0 to Count-1 do
  2511. begin
  2512. lIndex := Items[I];
  2513. if AnsiUpperCase(Trim(lIndex.SortField)) = searchStr then
  2514. begin
  2515. Result := lIndex;
  2516. exit;
  2517. end
  2518. end;
  2519. end;
  2520. procedure TDbfIndexDefs.Update;
  2521. begin
  2522. if Assigned(FOwner) then
  2523. FOwner.UpdateIndexDefs;
  2524. end;
  2525. //==========================================================
  2526. //============ TDbfMasterLink
  2527. //==========================================================
  2528. constructor TDbfMasterLink.Create(ADataSet: TDbf);
  2529. begin
  2530. inherited Create;
  2531. FDetailDataSet := ADataSet;
  2532. FParser := TDbfParser.Create(nil);
  2533. FValidExpression := false;
  2534. end;
  2535. destructor TDbfMasterLink.Destroy;
  2536. begin
  2537. FParser.Free;
  2538. inherited;
  2539. end;
  2540. procedure TDbfMasterLink.ActiveChanged;
  2541. begin
  2542. if Active and (FFieldNames <> EmptyStr) then
  2543. begin
  2544. FValidExpression := false;
  2545. FParser.DbfFile := TDbf(DataSet).DbfFile;
  2546. FParser.ParseExpression(FFieldNames);
  2547. FValidExpression := true;
  2548. end else begin
  2549. FParser.ClearExpressions;
  2550. FValidExpression := false;
  2551. end;
  2552. if FDetailDataSet.Active and not (csDestroying in FDetailDataSet.ComponentState) then
  2553. if Active then
  2554. begin
  2555. if Assigned(FOnMasterChange) then FOnMasterChange(Self);
  2556. end else
  2557. if Assigned(FOnMasterDisable) then FOnMasterDisable(Self);
  2558. end;
  2559. procedure TDbfMasterLink.CheckBrowseMode;
  2560. begin
  2561. if FDetailDataSet.Active then
  2562. FDetailDataSet.CheckBrowseMode;
  2563. end;
  2564. procedure TDbfMasterLink.LayoutChanged;
  2565. begin
  2566. ActiveChanged;
  2567. end;
  2568. procedure TDbfMasterLink.RecordChanged(Field: TField);
  2569. begin
  2570. if (DataSource.State <> dsSetKey) and FDetailDataSet.Active and Assigned(FOnMasterChange) then
  2571. FOnMasterChange(Self);
  2572. end;
  2573. procedure TDbfMasterLink.SetFieldNames(const Value: string);
  2574. begin
  2575. if FFieldNames <> Value then
  2576. begin
  2577. FFieldNames := Value;
  2578. ActiveChanged;
  2579. end;
  2580. end;
  2581. function TDbfMasterLink.GetFieldsVal: PChar;
  2582. begin
  2583. Result := FParser.ExtractFromBuffer(@pDbfRecord(TDbf(DataSet).ActiveBuffer)^.DeletedFlag);
  2584. end;
  2585. ////////////////////////////////////////////////////////////////////////////
  2586. function ApplicationPath: string;
  2587. begin
  2588. Result := ExtractFilePath(ParamStr(0));
  2589. end;
  2590. ////////////////////////////////////////////////////////////////////////////
  2591. initialization
  2592. DbfBasePath := ApplicationPath;
  2593. end.