sqldb.pp 40 KB

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