dbf.pas 80 KB

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