sqldb.pp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. {
  2. Copyright (c) 2004 by Joost van der Sluis
  3. SQL database & dataset
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. unit sqldb;
  11. {$mode objfpc}
  12. {$H+}
  13. {$M+} // ### remove this!!!
  14. interface
  15. uses SysUtils, Classes, DB, bufdataset;
  16. type TSchemaType = (stNoSchema, stTables, stSysTables, stProcedures, stColumns, stProcedureParams, stIndexes, stPackages);
  17. TConnOption = (sqSupportParams);
  18. TConnOptions= set of TConnOption;
  19. type
  20. TSQLConnection = class;
  21. TSQLTransaction = class;
  22. TSQLQuery = class;
  23. TSQLScript = class;
  24. TStatementType = (stNone, stSelect, stInsert, stUpdate, stDelete,
  25. stDDL, stGetSegment, stPutSegment, stExecProcedure,
  26. stStartTrans, stCommit, stRollback, stSelectForUpd);
  27. TSQLHandle = Class(TObject)
  28. end;
  29. { TSQLCursor }
  30. TSQLCursor = Class(TSQLHandle)
  31. public
  32. FPrepared : Boolean;
  33. FInitFieldDef : Boolean;
  34. FStatementType : TStatementType;
  35. FBlobStrings : TStringList; // list of strings in which the blob-fields are stored
  36. public
  37. constructor Create;
  38. destructor Destroy; override;
  39. end;
  40. const
  41. StatementTokens : Array[TStatementType] of string = ('(none)', 'select',
  42. 'insert', 'update', 'delete',
  43. 'create', 'get', 'put', 'execute',
  44. 'start','commit','rollback', '?'
  45. );
  46. { TSQLConnection }
  47. type
  48. { TSQLConnection }
  49. TSQLConnection = class (TDatabase)
  50. private
  51. FPassword : string;
  52. FTransaction : TSQLTransaction;
  53. FUserName : string;
  54. FHostName : string;
  55. FCharSet : string;
  56. FRole : String;
  57. procedure SetTransaction(Value : TSQLTransaction);
  58. procedure GetDBInfo(const SchemaType : TSchemaType; const SchemaObjectName, ReturnField : string; List: TStrings);
  59. protected
  60. FConnOptions : TConnOptions;
  61. function StrToStatementType(s : string) : TStatementType; virtual;
  62. procedure DoInternalConnect; override;
  63. procedure DoInternalDisconnect; override;
  64. function GetAsSQLText(Field : TField) : string; overload; virtual;
  65. function GetAsSQLText(Param : TParam) : string; overload; virtual;
  66. function GetHandle : pointer; virtual; virtual;
  67. Function AllocateCursorHandle : TSQLCursor; virtual; abstract;
  68. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); virtual; abstract;
  69. Function AllocateTransactionHandle : TSQLHandle; virtual; abstract;
  70. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); virtual; abstract;
  71. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); virtual; abstract;
  72. function Fetch(cursor : TSQLCursor) : boolean; virtual; abstract;
  73. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); virtual; abstract;
  74. procedure UnPrepareStatement(cursor : TSQLCursor); virtual; abstract;
  75. procedure FreeFldBuffers(cursor : TSQLCursor); virtual;
  76. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer) : boolean; virtual; abstract;
  77. function GetTransactionHandle(trans : TSQLHandle): pointer; virtual; abstract;
  78. function Commit(trans : TSQLHandle) : boolean; virtual; abstract;
  79. function RollBack(trans : TSQLHandle) : boolean; virtual; abstract;
  80. function StartdbTransaction(trans : TSQLHandle; aParams : string) : boolean; virtual; abstract;
  81. procedure CommitRetaining(trans : TSQLHandle); virtual; abstract;
  82. procedure RollBackRetaining(trans : TSQLHandle); virtual; abstract;
  83. procedure UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string); virtual;
  84. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; virtual;
  85. procedure LoadBlobIntoStream(Field: TField;AStream: TStream;cursor: TSQLCursor;ATransaction : TSQLTransaction); virtual;
  86. public
  87. property Handle: Pointer read GetHandle;
  88. destructor Destroy; override;
  89. procedure StartTransaction; override;
  90. procedure EndTransaction; override;
  91. property ConnOptions: TConnOptions read FConnOptions;
  92. procedure ExecuteDirect(SQL : String); overload; virtual;
  93. procedure ExecuteDirect(SQL : String; ATransaction : TSQLTransaction); overload; virtual;
  94. procedure GetTableNames(List : TStrings; SystemTables : Boolean = false); virtual;
  95. procedure GetProcedureNames(List : TStrings); virtual;
  96. procedure GetFieldNames(const TableName : string; List : TStrings); virtual;
  97. procedure CreateDB; virtual;
  98. procedure DropDB; virtual;
  99. published
  100. property Password : string read FPassword write FPassword;
  101. property Transaction : TSQLTransaction read FTransaction write SetTransaction;
  102. property UserName : string read FUserName write FUserName;
  103. property CharSet : string read FCharSet write FCharSet;
  104. property HostName : string Read FHostName Write FHostName;
  105. property Connected;
  106. Property Role : String read FRole write FRole;
  107. property DatabaseName;
  108. property KeepConnection;
  109. property LoginPrompt;
  110. property Params;
  111. property OnLogin;
  112. end;
  113. { TSQLTransaction }
  114. TCommitRollbackAction = (caNone, caCommit, caCommitRetaining, caRollback,
  115. caRollbackRetaining);
  116. TSQLTransaction = class (TDBTransaction)
  117. private
  118. FTrans : TSQLHandle;
  119. FAction : TCommitRollbackAction;
  120. FParams : TStringList;
  121. protected
  122. function GetHandle : Pointer; virtual;
  123. Procedure SetDatabase (Value : TDatabase); override;
  124. public
  125. procedure Commit; virtual;
  126. procedure CommitRetaining; virtual;
  127. procedure Rollback; virtual;
  128. procedure RollbackRetaining; virtual;
  129. procedure StartTransaction; override;
  130. constructor Create(AOwner : TComponent); override;
  131. destructor Destroy; override;
  132. property Handle: Pointer read GetHandle;
  133. procedure EndTransaction; override;
  134. published
  135. property Action : TCommitRollbackAction read FAction write FAction;
  136. property Database;
  137. property Params : TStringList read FParams write FParams;
  138. end;
  139. { TSQLQuery }
  140. TSQLQuery = class (Tbufdataset)
  141. private
  142. FCursor : TSQLCursor;
  143. FUpdateable : boolean;
  144. FTableName : string;
  145. FSQL : TStringList;
  146. FUpdateSQL,
  147. FInsertSQL,
  148. FDeleteSQL : TStringList;
  149. FIsEOF : boolean;
  150. FLoadingFieldDefs : boolean;
  151. FIndexDefs : TIndexDefs;
  152. FReadOnly : boolean;
  153. FUpdateMode : TUpdateMode;
  154. FParams : TParams;
  155. FusePrimaryKeyAsKey : Boolean;
  156. FSQLBuf : String;
  157. FFromPart : String;
  158. FWhereStartPos : integer;
  159. FWhereStopPos : integer;
  160. FParseSQL : boolean;
  161. FMasterLink : TMasterParamsDatalink;
  162. // FSchemaInfo : TSchemaInfo;
  163. FServerFilterText : string;
  164. FServerFiltered : Boolean;
  165. FUpdateQry,
  166. FDeleteQry,
  167. FInsertQry : TSQLQuery;
  168. procedure FreeFldBuffers;
  169. procedure InitUpdates(ASQL : string);
  170. function GetIndexDefs : TIndexDefs;
  171. function GetStatementType : TStatementType;
  172. procedure SetIndexDefs(AValue : TIndexDefs);
  173. procedure SetReadOnly(AValue : Boolean);
  174. procedure SetParseSQL(AValue : Boolean);
  175. procedure SetUsePrimaryKeyAsKey(AValue : Boolean);
  176. procedure SetUpdateMode(AValue : TUpdateMode);
  177. procedure OnChangeSQL(Sender : TObject);
  178. procedure OnChangeModifySQL(Sender : TObject);
  179. procedure Execute;
  180. Procedure SQLParser(var ASQL : string);
  181. procedure ApplyFilter;
  182. Function AddFilter(SQLstr : string) : string;
  183. protected
  184. // abstract & virtual methods of TBufDataset
  185. function Fetch : boolean; override;
  186. function LoadField(FieldDef : TFieldDef;buffer : pointer) : boolean; override;
  187. // abstract & virtual methods of TDataset
  188. procedure UpdateIndexDefs; override;
  189. procedure SetDatabase(Value : TDatabase); override;
  190. Procedure SetTransaction(Value : TDBTransaction); override;
  191. procedure InternalAddRecord(Buffer: Pointer; AAppend: Boolean); override;
  192. procedure InternalClose; override;
  193. procedure InternalInitFieldDefs; override;
  194. procedure InternalOpen; override;
  195. function GetCanModify: Boolean; override;
  196. procedure ApplyRecUpdate(UpdateKind : TUpdateKind); override;
  197. Function IsPrepared : Boolean; virtual;
  198. Procedure SetActive (Value : Boolean); override;
  199. procedure SetServerFiltered(Value: Boolean); virtual;
  200. procedure SetServerFilterText(const Value: string); virtual;
  201. Function GetDataSource : TDatasource; override;
  202. Procedure SetDataSource(AValue : TDatasource);
  203. procedure LoadBlobIntoStream(Field: TField;AStream: TStream); override;
  204. public
  205. procedure Prepare; virtual;
  206. procedure UnPrepare; virtual;
  207. procedure ExecSQL; virtual;
  208. constructor Create(AOwner : TComponent); override;
  209. destructor Destroy; override;
  210. procedure SetSchemaInfo( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string); virtual;
  211. property Prepared : boolean read IsPrepared;
  212. procedure Notification(AComponent: TComponent; Operation: TOperation); override;
  213. published
  214. // redeclared data set properties
  215. property Active;
  216. property Filter;
  217. property Filtered;
  218. property ServerFilter: string read FServerFilterText write SetServerFilterText;
  219. property ServerFiltered: Boolean read FServerFiltered write SetServerFiltered default False;
  220. // property FilterOptions;
  221. property BeforeOpen;
  222. property AfterOpen;
  223. property BeforeClose;
  224. property AfterClose;
  225. property BeforeInsert;
  226. property AfterInsert;
  227. property BeforeEdit;
  228. property AfterEdit;
  229. property BeforePost;
  230. property AfterPost;
  231. property BeforeCancel;
  232. property AfterCancel;
  233. property BeforeDelete;
  234. property AfterDelete;
  235. property BeforeScroll;
  236. property AfterScroll;
  237. property OnCalcFields;
  238. property OnDeleteError;
  239. property OnEditError;
  240. property OnFilterRecord;
  241. property OnNewRecord;
  242. property OnPostError;
  243. property AutoCalcFields;
  244. property Database;
  245. property Transaction;
  246. property ReadOnly : Boolean read FReadOnly write SetReadOnly;
  247. property SQL : TStringlist read FSQL write FSQL;
  248. property UpdateSQL : TStringlist read FUpdateSQL write FUpdateSQL;
  249. property InsertSQL : TStringlist read FInsertSQL write FInsertSQL;
  250. property DeleteSQL : TStringlist read FDeleteSQL write FDeleteSQL;
  251. property IndexDefs : TIndexDefs read GetIndexDefs;
  252. property Params : TParams read FParams write FParams;
  253. property UpdateMode : TUpdateMode read FUpdateMode write SetUpdateMode;
  254. property UsePrimaryKeyAsKey : boolean read FUsePrimaryKeyAsKey write SetUsePrimaryKeyAsKey;
  255. property StatementType : TStatementType read GetStatementType;
  256. property ParseSQL : Boolean read FParseSQL write SetParseSQL;
  257. Property DataSource : TDatasource Read GetDataSource Write SetDatasource;
  258. // property SchemaInfo : TSchemaInfo read FSchemaInfo default stNoSchema;
  259. end;
  260. { TSQLScript }
  261. TSQLScript = class (Tcomponent)
  262. private
  263. FScript : TStrings;
  264. FQuery : TSQLQuery;
  265. FDatabase : TDatabase;
  266. FTransaction : TDBTransaction;
  267. protected
  268. procedure SetScript(const AValue: TStrings);
  269. Procedure SetDatabase (Value : TDatabase); virtual;
  270. Procedure SetTransaction(Value : TDBTransaction); virtual;
  271. Procedure CheckDatabase;
  272. public
  273. constructor Create(AOwner : TComponent); override;
  274. destructor Destroy; override;
  275. procedure ExecuteScript;
  276. Property Script : TStrings Read FScript Write SetScript;
  277. Property DataBase : TDatabase Read FDatabase Write SetDatabase;
  278. Property Transaction : TDBTransaction Read FTransaction Write SetTransaction;
  279. end;
  280. implementation
  281. uses dbconst, strutils;
  282. { TSQLConnection }
  283. function TSQLConnection.StrToStatementType(s : string) : TStatementType;
  284. var T : TStatementType;
  285. begin
  286. S:=Lowercase(s);
  287. For t:=stselect to strollback do
  288. if (S=StatementTokens[t]) then
  289. Exit(t);
  290. end;
  291. procedure TSQLConnection.SetTransaction(Value : TSQLTransaction);
  292. begin
  293. if FTransaction<>value then
  294. begin
  295. if Assigned(FTransaction) and FTransaction.Active then
  296. DatabaseError(SErrAssTransaction);
  297. if Assigned(Value) then
  298. Value.Database := Self;
  299. FTransaction := Value;
  300. end;
  301. end;
  302. procedure TSQLConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  303. begin
  304. // Empty abstract
  305. end;
  306. procedure TSQLConnection.DoInternalConnect;
  307. begin
  308. if (DatabaseName = '') then
  309. DatabaseError(SErrNoDatabaseName,self);
  310. end;
  311. procedure TSQLConnection.DoInternalDisconnect;
  312. begin
  313. end;
  314. destructor TSQLConnection.Destroy;
  315. begin
  316. inherited Destroy;
  317. end;
  318. procedure TSQLConnection.StartTransaction;
  319. begin
  320. if not assigned(Transaction) then
  321. DatabaseError(SErrConnTransactionnSet)
  322. else
  323. Transaction.StartTransaction;
  324. end;
  325. procedure TSQLConnection.EndTransaction;
  326. begin
  327. if not assigned(Transaction) then
  328. DatabaseError(SErrConnTransactionnSet)
  329. else
  330. Transaction.EndTransaction;
  331. end;
  332. Procedure TSQLConnection.ExecuteDirect(SQL: String);
  333. begin
  334. ExecuteDirect(SQL,FTransaction);
  335. end;
  336. Procedure TSQLConnection.ExecuteDirect(SQL: String; ATransaction : TSQLTransaction);
  337. var Cursor : TSQLCursor;
  338. begin
  339. if not assigned(ATransaction) then
  340. DatabaseError(SErrTransactionnSet);
  341. if not Connected then Open;
  342. if not ATransaction.Active then ATransaction.StartTransaction;
  343. try
  344. Cursor := AllocateCursorHandle;
  345. SQL := TrimRight(SQL);
  346. if SQL = '' then
  347. DatabaseError(SErrNoStatement);
  348. Cursor.FStatementType := stNone;
  349. PrepareStatement(cursor,ATransaction,SQL,Nil);
  350. execute(cursor,ATransaction, Nil);
  351. UnPrepareStatement(Cursor);
  352. finally;
  353. DeAllocateCursorHandle(Cursor);
  354. end;
  355. end;
  356. procedure TSQLConnection.GetDBInfo(const SchemaType : TSchemaType; const SchemaObjectName, ReturnField : string; List: TStrings);
  357. var qry : TSQLQuery;
  358. begin
  359. if not assigned(Transaction) then
  360. DatabaseError(SErrConnTransactionnSet);
  361. qry := tsqlquery.Create(nil);
  362. qry.transaction := Transaction;
  363. qry.database := Self;
  364. with qry do
  365. begin
  366. ParseSQL := False;
  367. SetSchemaInfo(SchemaType,SchemaObjectName,'');
  368. open;
  369. List.Clear;
  370. while not eof do
  371. begin
  372. List.Append(fieldbyname(ReturnField).asstring);
  373. Next;
  374. end;
  375. end;
  376. qry.free;
  377. end;
  378. procedure TSQLConnection.GetTableNames(List: TStrings; SystemTables: Boolean);
  379. begin
  380. if not systemtables then GetDBInfo(stTables,'','table_name',List)
  381. else GetDBInfo(stSysTables,'','table_name',List);
  382. end;
  383. procedure TSQLConnection.GetProcedureNames(List: TStrings);
  384. begin
  385. GetDBInfo(stProcedures,'','proc_name',List);
  386. end;
  387. procedure TSQLConnection.GetFieldNames(const TableName: string; List: TStrings);
  388. begin
  389. GetDBInfo(stColumns,TableName,'column_name',List);
  390. end;
  391. function TSQLConnection.GetAsSQLText(Field : TField) : string;
  392. begin
  393. if (not assigned(field)) or field.IsNull then Result := 'Null'
  394. else case field.DataType of
  395. ftString : Result := '''' + field.asstring + '''';
  396. ftDate : Result := '''' + FormatDateTime('yyyy-mm-dd',Field.AsDateTime) + '''';
  397. ftDateTime : Result := '''' + FormatDateTime('yyyy-mm-dd hh:mm:ss',Field.AsDateTime) + ''''
  398. else
  399. Result := field.asstring;
  400. end; {case}
  401. end;
  402. function TSQLConnection.GetAsSQLText(Param: TParam) : string;
  403. begin
  404. if (not assigned(param)) or param.IsNull then Result := 'Null'
  405. else case param.DataType of
  406. ftString : Result := '''' + param.asstring + '''';
  407. ftDate : Result := '''' + FormatDateTime('yyyy-mm-dd',Param.AsDateTime) + '''';
  408. ftDateTime : Result := '''' + FormatDateTime('yyyy-mm-dd hh:mm:ss',Param.AsDateTime) + ''''
  409. else
  410. Result := Param.asstring;
  411. end; {case}
  412. end;
  413. function TSQLConnection.GetHandle: pointer;
  414. begin
  415. Result := nil;
  416. end;
  417. procedure TSQLConnection.FreeFldBuffers(cursor: TSQLCursor);
  418. begin
  419. cursor.FBlobStrings.Clear;
  420. end;
  421. function TSQLConnection.GetSchemaInfoSQL( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string;
  422. begin
  423. DatabaseError(SMetadataUnavailable);
  424. end;
  425. procedure TSQLConnection.LoadBlobIntoStream(Field: TField;AStream: TStream; cursor: TSQLCursor;ATransaction : TSQLTransaction);
  426. var blobId : pinteger;
  427. BlobBuf : TBufBlobField;
  428. s : string;
  429. begin
  430. { if not field.getData(@BlobBuf) then
  431. exit;
  432. blobId := @BlobBuf.BufBlobId;
  433. s := cursor.FBlobStrings.Strings[blobid^];
  434. AStream.WriteBuffer(s[1],length(s));
  435. AStream.seek(0,soFromBeginning);}
  436. end;
  437. procedure TSQLConnection.CreateDB;
  438. begin
  439. DatabaseError(SNotSupported);
  440. end;
  441. procedure TSQLConnection.DropDB;
  442. begin
  443. DatabaseError(SNotSupported);
  444. end;
  445. { TSQLTransaction }
  446. procedure TSQLTransaction.EndTransaction;
  447. begin
  448. rollback;
  449. end;
  450. function TSQLTransaction.GetHandle: pointer;
  451. begin
  452. Result := (Database as tsqlconnection).GetTransactionHandle(FTrans);
  453. end;
  454. procedure TSQLTransaction.Commit;
  455. begin
  456. if active then
  457. begin
  458. closedatasets;
  459. if (Database as tsqlconnection).commit(FTrans) then
  460. begin
  461. closeTrans;
  462. FreeAndNil(FTrans);
  463. end;
  464. end;
  465. end;
  466. procedure TSQLTransaction.CommitRetaining;
  467. begin
  468. if active then
  469. (Database as tsqlconnection).commitRetaining(FTrans);
  470. end;
  471. procedure TSQLTransaction.Rollback;
  472. begin
  473. if active then
  474. begin
  475. closedatasets;
  476. if (Database as tsqlconnection).RollBack(FTrans) then
  477. begin
  478. CloseTrans;
  479. FreeAndNil(FTrans);
  480. end;
  481. end;
  482. end;
  483. procedure TSQLTransaction.RollbackRetaining;
  484. begin
  485. if active then
  486. (Database as tsqlconnection).RollBackRetaining(FTrans);
  487. end;
  488. procedure TSQLTransaction.StartTransaction;
  489. var db : TSQLConnection;
  490. begin
  491. if Active then
  492. DatabaseError(SErrTransAlreadyActive);
  493. db := (Database as tsqlconnection);
  494. if Db = nil then
  495. DatabaseError(SErrDatabasenAssigned);
  496. if not Db.Connected then
  497. Db.Open;
  498. if not assigned(FTrans) then FTrans := Db.AllocateTransactionHandle;
  499. if Db.StartdbTransaction(FTrans,FParams.CommaText) then OpenTrans;
  500. end;
  501. constructor TSQLTransaction.Create(AOwner : TComponent);
  502. begin
  503. inherited Create(AOwner);
  504. FParams := TStringList.Create;
  505. end;
  506. destructor TSQLTransaction.Destroy;
  507. begin
  508. Rollback;
  509. FreeAndNil(FParams);
  510. inherited Destroy;
  511. end;
  512. Procedure TSQLTransaction.SetDatabase(Value : TDatabase);
  513. begin
  514. If Value<>Database then
  515. begin
  516. CheckInactive;
  517. If Assigned(Database) then
  518. with Database as TSqlConnection do
  519. if Transaction = self then Transaction := nil;
  520. inherited SetDatabase(Value);
  521. end;
  522. end;
  523. { TSQLQuery }
  524. procedure TSQLQuery.OnChangeSQL(Sender : TObject);
  525. begin
  526. UnPrepare;
  527. if (FSQL <> nil) then
  528. begin
  529. FParams.ParseSQL(FSQL.Text,True);
  530. If Assigned(FMasterLink) then
  531. FMasterLink.RefreshParamNames;
  532. end;
  533. end;
  534. procedure TSQLQuery.OnChangeModifySQL(Sender : TObject);
  535. begin
  536. CheckInactive;
  537. end;
  538. Procedure TSQLQuery.SetTransaction(Value : TDBTransaction);
  539. begin
  540. UnPrepare;
  541. inherited;
  542. end;
  543. procedure TSQLQuery.SetDatabase(Value : TDatabase);
  544. var db : tsqlconnection;
  545. begin
  546. if (Database <> Value) then
  547. begin
  548. UnPrepare;
  549. if assigned(FCursor) then (Database as TSQLConnection).DeAllocateCursorHandle(FCursor);
  550. db := value as tsqlconnection;
  551. inherited setdatabase(value);
  552. if assigned(value) and (Transaction = nil) and (Assigned(db.Transaction)) then
  553. transaction := Db.Transaction;
  554. end;
  555. end;
  556. Function TSQLQuery.IsPrepared : Boolean;
  557. begin
  558. Result := Assigned(FCursor) and FCursor.FPrepared;
  559. end;
  560. Function TSQLQuery.AddFilter(SQLstr : string) : string;
  561. begin
  562. if FWhereStartPos = 0 then
  563. SQLstr := SQLstr + ' where (' + Filter + ')'
  564. else if FWhereStopPos > 0 then
  565. system.insert(' and ('+Filter+') ',SQLstr,FWhereStopPos+1)
  566. else
  567. system.insert(' where ('+Filter+') ',SQLstr,FWhereStartPos);
  568. Result := SQLstr;
  569. end;
  570. procedure TSQLQuery.ApplyFilter;
  571. var S : String;
  572. begin
  573. FreeFldBuffers;
  574. (Database as tsqlconnection).UnPrepareStatement(FCursor);
  575. FIsEOF := False;
  576. inherited internalclose;
  577. s := FSQLBuf;
  578. if ServerFiltered then s := AddFilter(s);
  579. (Database as tsqlconnection).PrepareStatement(Fcursor,(transaction as tsqltransaction),S,FParams);
  580. Execute;
  581. inherited InternalOpen;
  582. First;
  583. end;
  584. Procedure TSQLQuery.SetActive (Value : Boolean);
  585. begin
  586. inherited SetActive(Value);
  587. // The query is UnPrepared, so that if a transaction closes all datasets
  588. // they also get unprepared
  589. if not Value and IsPrepared then UnPrepare;
  590. end;
  591. procedure TSQLQuery.SetServerFiltered(Value: Boolean);
  592. begin
  593. if Value and not FParseSQL then DatabaseErrorFmt(SNoParseSQL,['Filtering ']);
  594. if (ServerFiltered <> Value) then
  595. begin
  596. FServerFiltered := Value;
  597. if active then ApplyFilter;
  598. end;
  599. end;
  600. procedure TSQLQuery.SetServerFilterText(const Value: string);
  601. begin
  602. if Value <> ServerFilter then
  603. begin
  604. FServerFilterText := Value;
  605. if active then ApplyFilter;
  606. end;
  607. end;
  608. procedure TSQLQuery.Prepare;
  609. var
  610. db : tsqlconnection;
  611. sqltr : tsqltransaction;
  612. begin
  613. if not IsPrepared then
  614. begin
  615. db := (Database as tsqlconnection);
  616. sqltr := (transaction as tsqltransaction);
  617. if not assigned(Db) then
  618. DatabaseError(SErrDatabasenAssigned);
  619. if not assigned(sqltr) then
  620. DatabaseError(SErrTransactionnSet);
  621. if not Db.Connected then db.Open;
  622. if not sqltr.Active then sqltr.StartTransaction;
  623. // if assigned(fcursor) then FreeAndNil(fcursor);
  624. if not assigned(fcursor) then
  625. FCursor := Db.AllocateCursorHandle;
  626. FSQLBuf := TrimRight(FSQL.Text);
  627. if FSQLBuf = '' then
  628. DatabaseError(SErrNoStatement);
  629. SQLParser(FSQLBuf);
  630. if ServerFiltered then
  631. Db.PrepareStatement(Fcursor,sqltr,AddFilter(FSQLBuf),FParams)
  632. else
  633. Db.PrepareStatement(Fcursor,sqltr,FSQLBuf,FParams);
  634. if (FCursor.FStatementType = stSelect) then
  635. begin
  636. FCursor.FInitFieldDef := True;
  637. if not ReadOnly then InitUpdates(FSQLBuf);
  638. end;
  639. end;
  640. end;
  641. procedure TSQLQuery.UnPrepare;
  642. begin
  643. CheckInactive;
  644. if IsPrepared then with Database as TSQLConnection do
  645. UnPrepareStatement(FCursor);
  646. end;
  647. procedure TSQLQuery.FreeFldBuffers;
  648. begin
  649. if assigned(FCursor) then (Database as tsqlconnection).FreeFldBuffers(FCursor);
  650. end;
  651. function TSQLQuery.Fetch : boolean;
  652. begin
  653. if not (Fcursor.FStatementType in [stSelect]) then
  654. Exit;
  655. if not FIsEof then FIsEOF := not (Database as tsqlconnection).Fetch(Fcursor);
  656. Result := not FIsEOF;
  657. end;
  658. procedure TSQLQuery.Execute;
  659. begin
  660. If (FParams.Count>0) and Assigned(FMasterLink) then
  661. FMasterLink.CopyParamsFromMaster(False);
  662. (Database as tsqlconnection).execute(Fcursor,Transaction as tsqltransaction, FParams);
  663. end;
  664. function TSQLQuery.LoadField(FieldDef : TFieldDef;buffer : pointer) : boolean;
  665. begin
  666. result := (Database as tSQLConnection).LoadField(FCursor,FieldDef,buffer)
  667. end;
  668. procedure TSQLQuery.InternalAddRecord(Buffer: Pointer; AAppend: Boolean);
  669. begin
  670. // not implemented - sql dataset
  671. end;
  672. procedure TSQLQuery.InternalClose;
  673. begin
  674. if StatementType = stSelect then FreeFldBuffers;
  675. // Database and FCursor could be nil, for example if the database is not assigned, and .open is called
  676. if (not IsPrepared) and (assigned(database)) and (assigned(FCursor)) then (database as TSQLconnection).UnPrepareStatement(FCursor);
  677. if DefaultFields then
  678. DestroyFields;
  679. FIsEOF := False;
  680. if assigned(FUpdateQry) then FreeAndNil(FUpdateQry);
  681. if assigned(FInsertQry) then FreeAndNil(FInsertQry);
  682. if assigned(FDeleteQry) then FreeAndNil(FDeleteQry);
  683. // FRecordSize := 0;
  684. inherited internalclose;
  685. end;
  686. procedure TSQLQuery.InternalInitFieldDefs;
  687. begin
  688. if FLoadingFieldDefs then
  689. Exit;
  690. FLoadingFieldDefs := True;
  691. try
  692. FieldDefs.Clear;
  693. (Database as tsqlconnection).AddFieldDefs(fcursor,FieldDefs);
  694. finally
  695. FLoadingFieldDefs := False;
  696. end;
  697. end;
  698. procedure TSQLQuery.SQLParser(var ASQL : string);
  699. type TParsePart = (ppStart,ppSelect,ppWhere,ppFrom,ppOrder,ppComment,ppGroup,ppBogus);
  700. Var
  701. PSQL,CurrentP,
  702. PhraseP, PStatementPart : pchar;
  703. S : string;
  704. ParsePart : TParsePart;
  705. StrLength : Integer;
  706. EndOfComment : Boolean;
  707. BracketCount : Integer;
  708. begin
  709. PSQL:=Pchar(ASQL);
  710. ParsePart := ppStart;
  711. CurrentP := PSQL-1;
  712. PhraseP := PSQL;
  713. FWhereStartPos := 0;
  714. FWhereStopPos := 0;
  715. repeat
  716. begin
  717. inc(CurrentP);
  718. EndOfComment := SkipComments(CurrentP);
  719. if EndOfcomment then dec(currentp);
  720. if EndOfComment and (ParsePart = ppStart) then PhraseP := CurrentP;
  721. // skip everything between bracket, since it could be a sub-select, and
  722. // further nothing between brackets could be interesting for the parser.
  723. if currentp^='(' then
  724. begin
  725. inc(currentp);
  726. BracketCount := 0;
  727. while (currentp^ <> #0) and ((currentp^ <> ')') or (BracketCount > 0 )) do
  728. begin
  729. if currentp^ = '(' then inc(bracketcount)
  730. else if currentp^ = ')' then dec(bracketcount);
  731. inc(currentp);
  732. end;
  733. EndOfComment := True;
  734. end;
  735. if EndOfComment or (CurrentP^ in [' ',#13,#10,#9,#0,';']) then
  736. begin
  737. if (CurrentP-PhraseP > 0) or (CurrentP^ in [';',#0]) then
  738. begin
  739. strLength := CurrentP-PhraseP;
  740. Setlength(S,strLength);
  741. if strLength > 0 then Move(PhraseP^,S[1],(strLength));
  742. s := uppercase(s);
  743. case ParsePart of
  744. ppStart : begin
  745. FCursor.FStatementType := (Database as tsqlconnection).StrToStatementType(s);
  746. if FCursor.FStatementType = stSelect then ParsePart := ppSelect
  747. else break;
  748. if not FParseSQL then break;
  749. PStatementPart := CurrentP;
  750. end;
  751. ppSelect : begin
  752. if s = 'FROM' then
  753. begin
  754. ParsePart := ppFrom;
  755. PhraseP := CurrentP;
  756. PStatementPart := CurrentP;
  757. end;
  758. end;
  759. ppFrom : begin
  760. if (s = 'WHERE') or (s = 'ORDER') or (s = 'GROUP') or (CurrentP^=#0) or (CurrentP^=';') then
  761. begin
  762. if (s = 'WHERE') then
  763. begin
  764. ParsePart := ppWhere;
  765. StrLength := PhraseP-PStatementPart;
  766. end
  767. else if (s = 'GROUP') then
  768. begin
  769. ParsePart := ppGroup;
  770. StrLength := PhraseP-PStatementPart;
  771. end
  772. else if (s = 'ORDER') then
  773. begin
  774. ParsePart := ppOrder;
  775. StrLength := PhraseP-PStatementPart
  776. end
  777. else
  778. begin
  779. ParsePart := ppBogus;
  780. StrLength := CurrentP-PStatementPart;
  781. end;
  782. Setlength(FFromPart,StrLength);
  783. Move(PStatementPart^,FFromPart[1],(StrLength));
  784. FFrompart := trim(FFrompart);
  785. FWhereStartPos := PStatementPart-PSQL+StrLength+1;
  786. PStatementPart := CurrentP;
  787. end;
  788. end;
  789. ppWhere : begin
  790. if (s = 'ORDER') or (s = 'GROUP') or (CurrentP^=#0) or (CurrentP^=';') then
  791. begin
  792. ParsePart := ppBogus;
  793. FWhereStartPos := PStatementPart-PSQL;
  794. if (s = 'ORDER') or (s = 'GROUP') then
  795. FWhereStopPos := PhraseP-PSQL+1
  796. else
  797. FWhereStopPos := CurrentP-PSQL+1;
  798. end;
  799. end;
  800. end; {case}
  801. end;
  802. PhraseP := CurrentP+1;
  803. end
  804. end;
  805. until CurrentP^=#0;
  806. if (FWhereStartPos > 0) and (FWhereStopPos > 0) then
  807. begin
  808. system.insert('(',ASQL,FWhereStartPos+1);
  809. inc(FWhereStopPos);
  810. system.insert(')',ASQL,FWhereStopPos);
  811. end
  812. end;
  813. procedure TSQLQuery.InitUpdates(ASQL : string);
  814. begin
  815. if pos(',',FFromPart) > 0 then
  816. FUpdateable := False // select-statements from more then one table are not updateable
  817. else
  818. begin
  819. FUpdateable := True;
  820. FTableName := FFromPart;
  821. end;
  822. end;
  823. procedure TSQLQuery.InternalOpen;
  824. procedure InitialiseModifyQuery(var qry : TSQLQuery; aSQL: TSTringList);
  825. begin
  826. qry := TSQLQuery.Create(nil);
  827. with qry do
  828. begin
  829. ParseSQL := False;
  830. DataBase := Self.DataBase;
  831. Transaction := Self.Transaction;
  832. SQL.Assign(aSQL);
  833. end;
  834. end;
  835. var tel : integer;
  836. f : TField;
  837. s : string;
  838. begin
  839. try
  840. Prepare;
  841. if FCursor.FStatementType in [stSelect] then
  842. begin
  843. Execute;
  844. if FCursor.FInitFieldDef then InternalInitFieldDefs;
  845. if DefaultFields then
  846. begin
  847. CreateFields;
  848. if FUpdateable then
  849. begin
  850. if FusePrimaryKeyAsKey then
  851. begin
  852. UpdateIndexDefs;
  853. for tel := 0 to indexdefs.count-1 do {with indexdefs[tel] do}
  854. begin
  855. if ixPrimary in indexdefs[tel].options then
  856. begin
  857. // Todo: If there is more then one field in the key, that must be parsed
  858. s := indexdefs[tel].fields;
  859. F := Findfield(s);
  860. if F <> nil then
  861. F.ProviderFlags := F.ProviderFlags + [pfInKey];
  862. end;
  863. end;
  864. end;
  865. end;
  866. end;
  867. if FUpdateable then
  868. begin
  869. InitialiseModifyQuery(FDeleteQry,FDeleteSQL);
  870. InitialiseModifyQuery(FUpdateQry,FUpdateSQL);
  871. InitialiseModifyQuery(FInsertQry,FInsertSQL);
  872. end;
  873. end
  874. else
  875. DatabaseError(SErrNoSelectStatement,Self);
  876. except
  877. on E:Exception do
  878. raise;
  879. end;
  880. inherited InternalOpen;
  881. end;
  882. // public part
  883. procedure TSQLQuery.ExecSQL;
  884. begin
  885. try
  886. Prepare;
  887. Execute;
  888. finally
  889. // FCursor has to be assigned, or else the prepare went wrong before PrepareStatment was
  890. // called, so UnPrepareStatement shoudn't be called either
  891. if (not IsPrepared) and (assigned(database)) and (assigned(FCursor)) then (database as TSQLConnection).UnPrepareStatement(Fcursor);
  892. end;
  893. end;
  894. constructor TSQLQuery.Create(AOwner : TComponent);
  895. begin
  896. inherited Create(AOwner);
  897. FParams := TParams.create(self);
  898. FSQL := TStringList.Create;
  899. FSQL.OnChange := @OnChangeSQL;
  900. FUpdateSQL := TStringList.Create;
  901. FUpdateSQL.OnChange := @OnChangeModifySQL;
  902. FInsertSQL := TStringList.Create;
  903. FInsertSQL.OnChange := @OnChangeModifySQL;
  904. FDeleteSQL := TStringList.Create;
  905. FDeleteSQL.OnChange := @OnChangeModifySQL;
  906. FIndexDefs := TIndexDefs.Create(Self);
  907. FReadOnly := false;
  908. FParseSQL := True;
  909. FServerFiltered := False;
  910. FServerFilterText := '';
  911. // Delphi has upWhereAll as default, but since strings and oldvalue's don't work yet
  912. // (variants) set it to upWhereKeyOnly
  913. FUpdateMode := upWhereKeyOnly;
  914. FUsePrimaryKeyAsKey := True;
  915. end;
  916. destructor TSQLQuery.Destroy;
  917. begin
  918. if Active then Close;
  919. UnPrepare;
  920. if assigned(FCursor) then (Database as TSQLConnection).DeAllocateCursorHandle(FCursor);
  921. FreeAndNil(FMasterLink);
  922. FreeAndNil(FParams);
  923. FreeAndNil(FSQL);
  924. FreeAndNil(FInsertSQL);
  925. FreeAndNil(FDeleteSQL);
  926. FreeAndNil(FUpdateSQL);
  927. FreeAndNil(FIndexDefs);
  928. inherited Destroy;
  929. end;
  930. procedure TSQLQuery.SetReadOnly(AValue : Boolean);
  931. begin
  932. CheckInactive;
  933. if not AValue then
  934. begin
  935. if FParseSQL then FReadOnly := False
  936. else DatabaseErrorFmt(SNoParseSQL,['Updating ']);
  937. end
  938. else FReadOnly := True;
  939. end;
  940. procedure TSQLQuery.SetParseSQL(AValue : Boolean);
  941. begin
  942. CheckInactive;
  943. if not AValue then
  944. begin
  945. FReadOnly := True;
  946. FServerFiltered := False;
  947. FParseSQL := False;
  948. end
  949. else
  950. FParseSQL := True;
  951. end;
  952. procedure TSQLQuery.SetUsePrimaryKeyAsKey(AValue : Boolean);
  953. begin
  954. if not Active then FusePrimaryKeyAsKey := AValue
  955. else
  956. begin
  957. // Just temporary, this should be possible in the future
  958. DatabaseError(SActiveDataset);
  959. end;
  960. end;
  961. Procedure TSQLQuery.UpdateIndexDefs;
  962. begin
  963. if assigned(DataBase) then
  964. (DataBase as TSQLConnection).UpdateIndexDefs(FIndexDefs,FTableName);
  965. end;
  966. Procedure TSQLQuery.ApplyRecUpdate(UpdateKind : TUpdateKind);
  967. procedure UpdateWherePart(var sql_where : string;x : integer);
  968. begin
  969. if (pfInKey in Fields[x].ProviderFlags) or
  970. ((FUpdateMode = upWhereAll) and (pfInWhere in Fields[x].ProviderFlags)) or
  971. ((FUpdateMode = UpWhereChanged) and (pfInWhere in Fields[x].ProviderFlags) and (fields[x].value <> fields[x].oldvalue)) then
  972. sql_where := sql_where + '(' + fields[x].FieldName + '= :OLD_' + fields[x].FieldName + ') and ';
  973. end;
  974. function ModifyRecQuery : string;
  975. var x : integer;
  976. sql_set : string;
  977. sql_where : string;
  978. begin
  979. sql_set := '';
  980. sql_where := '';
  981. for x := 0 to Fields.Count -1 do
  982. begin
  983. UpdateWherePart(sql_where,x);
  984. if (pfInUpdate in Fields[x].ProviderFlags) then
  985. sql_set := sql_set + fields[x].FieldName + '=:' + fields[x].FieldName + ',';
  986. end;
  987. setlength(sql_set,length(sql_set)-1);
  988. if length(sql_where) = 0 then DatabaseError(sNoWhereFields,self);
  989. setlength(sql_where,length(sql_where)-5);
  990. result := 'update ' + FTableName + ' set ' + sql_set + ' where ' + sql_where;
  991. end;
  992. function InsertRecQuery : string;
  993. var x : integer;
  994. sql_fields : string;
  995. sql_values : string;
  996. begin
  997. sql_fields := '';
  998. sql_values := '';
  999. for x := 0 to Fields.Count -1 do
  1000. begin
  1001. if not fields[x].IsNull then
  1002. begin
  1003. sql_fields := sql_fields + fields[x].FieldName + ',';
  1004. sql_values := sql_values + ':' + fields[x].FieldName + ',';
  1005. end;
  1006. end;
  1007. setlength(sql_fields,length(sql_fields)-1);
  1008. setlength(sql_values,length(sql_values)-1);
  1009. result := 'insert into ' + FTableName + ' (' + sql_fields + ') values (' + sql_values + ')';
  1010. end;
  1011. function DeleteRecQuery : string;
  1012. var x : integer;
  1013. sql_where : string;
  1014. begin
  1015. sql_where := '';
  1016. for x := 0 to Fields.Count -1 do
  1017. UpdateWherePart(sql_where,x);
  1018. if length(sql_where) = 0 then DatabaseError(sNoWhereFields,self);
  1019. setlength(sql_where,length(sql_where)-5);
  1020. result := 'delete from ' + FTableName + ' where ' + sql_where;
  1021. end;
  1022. var qry : tsqlquery;
  1023. x : integer;
  1024. Fld : TField;
  1025. begin
  1026. case UpdateKind of
  1027. ukModify : begin
  1028. qry := FUpdateQry;
  1029. if trim(qry.sql.Text) = '' then qry.SQL.Add(ModifyRecQuery);
  1030. end;
  1031. ukInsert : begin
  1032. qry := FInsertQry;
  1033. if trim(qry.sql.Text) = '' then qry.SQL.Add(InsertRecQuery);
  1034. end;
  1035. ukDelete : begin
  1036. qry := FDeleteQry;
  1037. if trim(qry.sql.Text) = '' then qry.SQL.Add(DeleteRecQuery);
  1038. end;
  1039. end;
  1040. with qry do
  1041. begin
  1042. for x := 0 to Params.Count-1 do with params[x] do if leftstr(name,4)='OLD_' then
  1043. begin
  1044. Fld := self.FieldByName(copy(name,5,length(name)-4));
  1045. AssignFieldValue(Fld,Fld.OldValue);
  1046. end
  1047. else
  1048. begin
  1049. Fld := self.FieldByName(name);
  1050. AssignFieldValue(Fld,Fld.Value);
  1051. end;
  1052. execsql;
  1053. end;
  1054. end;
  1055. Function TSQLQuery.GetCanModify: Boolean;
  1056. begin
  1057. // the test for assigned(FCursor) is needed for the case that the dataset isn't opened
  1058. if assigned(FCursor) and (FCursor.FStatementType = stSelect) then
  1059. Result:= FUpdateable and (not FReadOnly)
  1060. else
  1061. Result := False;
  1062. end;
  1063. function TSQLQuery.GetIndexDefs : TIndexDefs;
  1064. begin
  1065. Result := FIndexDefs;
  1066. end;
  1067. procedure TSQLQuery.SetIndexDefs(AValue : TIndexDefs);
  1068. begin
  1069. FIndexDefs := AValue;
  1070. end;
  1071. procedure TSQLQuery.SetUpdateMode(AValue : TUpdateMode);
  1072. begin
  1073. FUpdateMode := AValue;
  1074. end;
  1075. procedure TSQLQuery.SetSchemaInfo( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string);
  1076. begin
  1077. ReadOnly := True;
  1078. SQL.Clear;
  1079. SQL.Add((DataBase as tsqlconnection).GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaPattern));
  1080. end;
  1081. procedure TSQLQuery.LoadBlobIntoStream(Field: TField;AStream: TStream);
  1082. begin
  1083. (DataBase as tsqlconnection).LoadBlobIntoStream(Field, AStream, FCursor,(Transaction as tsqltransaction));
  1084. end;
  1085. function TSQLQuery.GetStatementType : TStatementType;
  1086. begin
  1087. if assigned(FCursor) then Result := FCursor.FStatementType
  1088. else Result := stNone;
  1089. end;
  1090. Procedure TSQLQuery.SetDataSource(AVAlue : TDatasource);
  1091. Var
  1092. DS : TDatasource;
  1093. begin
  1094. DS:=DataSource;
  1095. If (AValue<>DS) then
  1096. begin
  1097. If Assigned(DS) then
  1098. DS.RemoveFreeNotification(Self);
  1099. If Assigned(AValue) then
  1100. begin
  1101. AValue.FreeNotification(Self);
  1102. FMasterLink:=TMasterParamsDataLink.Create(Self);
  1103. FMasterLink.Datasource:=AValue;
  1104. end
  1105. else
  1106. FreeAndNil(FMasterLink);
  1107. end;
  1108. end;
  1109. Function TSQLQuery.GetDataSource : TDatasource;
  1110. begin
  1111. If Assigned(FMasterLink) then
  1112. Result:=FMasterLink.DataSource
  1113. else
  1114. Result:=Nil;
  1115. end;
  1116. procedure TSQLQuery.Notification(AComponent: TComponent; Operation: TOperation);
  1117. begin
  1118. Inherited;
  1119. If (Operation=opRemove) and (AComponent=DataSource) then
  1120. DataSource:=Nil;
  1121. end;
  1122. { TSQLScript }
  1123. procedure TSQLScript.SetScript(const AValue: TStrings);
  1124. begin
  1125. FScript.assign(AValue);
  1126. end;
  1127. procedure TSQLScript.SetDatabase(Value: TDatabase);
  1128. begin
  1129. FDatabase := Value;
  1130. end;
  1131. procedure TSQLScript.SetTransaction(Value: TDBTransaction);
  1132. begin
  1133. FTransaction := Value;
  1134. end;
  1135. procedure TSQLScript.CheckDatabase;
  1136. begin
  1137. If (FDatabase=Nil) then
  1138. DatabaseError(SErrNoDatabaseAvailable,Self)
  1139. end;
  1140. constructor TSQLScript.Create(AOwner: TComponent);
  1141. begin
  1142. inherited Create(AOwner);
  1143. FScript := TStringList.Create;
  1144. FQuery := TSQLQuery.Create(nil);
  1145. end;
  1146. destructor TSQLScript.Destroy;
  1147. begin
  1148. FScript.Free;
  1149. FQuery.Free;
  1150. inherited Destroy;
  1151. end;
  1152. procedure TSQLScript.ExecuteScript;
  1153. var BufStr : String;
  1154. pBufStatStart,
  1155. pBufPos : PChar;
  1156. Statement : String;
  1157. begin
  1158. FQuery.DataBase := FDatabase;
  1159. FQuery.Transaction := FTransaction;
  1160. BufStr := FScript.Text;
  1161. pBufPos := @BufStr[1];
  1162. repeat
  1163. pBufStatStart := pBufPos;
  1164. repeat
  1165. inc(pBufPos);
  1166. until (pBufPos^ = ';') or (pBufPos^ = #0);
  1167. SetLength(statement,pbufpos-pBufStatStart);
  1168. move(pBufStatStart^,Statement[1],pbufpos-pBufStatStart);
  1169. if trim(statement) <> '' then
  1170. begin
  1171. fquery.SQL.Text := Statement;
  1172. fquery.ExecSQL;
  1173. inc(pBufPos);
  1174. end;
  1175. until pBufPos^ = #0;
  1176. end;
  1177. { TSQLCursor }
  1178. constructor TSQLCursor.Create;
  1179. begin
  1180. FBlobStrings := TStringList.Create;
  1181. inherited;
  1182. end;
  1183. destructor TSQLCursor.Destroy;
  1184. begin
  1185. FBlobStrings.Free;
  1186. inherited Destroy;
  1187. end;
  1188. end.