dbf.pas 87 KB

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