dbf.pas 78 KB

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