sqldb.pp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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;
  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. TStatementType = (stNone, stSelect, stInsert, stUpdate, stDelete,
  24. stDDL, stGetSegment, stPutSegment, stExecProcedure,
  25. stStartTrans, stCommit, stRollback, stSelectForUpd);
  26. TSQLHandle = Class(TObject)
  27. end;
  28. TSQLCursor = Class(TSQLHandle)
  29. public
  30. FPrepared : Boolean;
  31. FInitFieldDef : Boolean;
  32. FStatementType : TStatementType;
  33. end;
  34. const
  35. StatementTokens : Array[TStatementType] of string = ('(none)', 'select',
  36. 'insert', 'update', 'delete',
  37. 'create', 'get', 'put', 'execute',
  38. 'start','commit','rollback', '?'
  39. );
  40. { TSQLConnection }
  41. type
  42. { TSQLConnection }
  43. TSQLConnection = class (TDatabase)
  44. private
  45. FPassword : string;
  46. FTransaction : TSQLTransaction;
  47. FUserName : string;
  48. FHostName : string;
  49. FCharSet : string;
  50. FRole : String;
  51. procedure SetTransaction(Value : TSQLTransaction);
  52. procedure GetDBInfo(const SchemaType : TSchemaType; const SchemaObjectName, ReturnField : string; List: TStrings);
  53. protected
  54. FConnOptions : TConnOptions;
  55. function StrToStatementType(s : string) : TStatementType; virtual;
  56. procedure DoInternalConnect; override;
  57. procedure DoInternalDisconnect; override;
  58. function GetAsSQLText(Field : TField) : string; virtual;
  59. function GetHandle : pointer; virtual; virtual;
  60. Function AllocateCursorHandle : TSQLCursor; virtual; abstract;
  61. Procedure DeAllocateCursorHandle(var cursor : TSQLCursor); virtual; abstract;
  62. Function AllocateTransactionHandle : TSQLHandle; virtual; abstract;
  63. procedure PrepareStatement(cursor: TSQLCursor;ATransaction : TSQLTransaction;buf : string; AParams : TParams); virtual; abstract;
  64. procedure Execute(cursor: TSQLCursor;atransaction:tSQLtransaction; AParams : TParams); virtual; abstract;
  65. function Fetch(cursor : TSQLCursor) : boolean; virtual; abstract;
  66. procedure AddFieldDefs(cursor: TSQLCursor; FieldDefs : TfieldDefs); virtual; abstract;
  67. procedure UnPrepareStatement(cursor : TSQLCursor); virtual; abstract;
  68. procedure FreeFldBuffers(cursor : TSQLCursor); virtual; abstract;
  69. function LoadField(cursor : TSQLCursor;FieldDef : TfieldDef;buffer : pointer) : boolean; virtual; abstract;
  70. function GetTransactionHandle(trans : TSQLHandle): pointer; virtual; abstract;
  71. function Commit(trans : TSQLHandle) : boolean; virtual; abstract;
  72. function RollBack(trans : TSQLHandle) : boolean; virtual; abstract;
  73. function StartdbTransaction(trans : TSQLHandle; aParams : string) : boolean; virtual; abstract;
  74. procedure CommitRetaining(trans : TSQLHandle); virtual; abstract;
  75. procedure RollBackRetaining(trans : TSQLHandle); virtual; abstract;
  76. procedure UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string); virtual;
  77. function GetSchemaInfoSQL(SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string; virtual;
  78. function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; virtual;
  79. public
  80. property Handle: Pointer read GetHandle;
  81. destructor Destroy; override;
  82. procedure StartTransaction; override;
  83. procedure EndTransaction; override;
  84. property ConnOptions: TConnOptions read FConnOptions;
  85. procedure ExecuteDirect(SQL : String); overload; virtual;
  86. procedure ExecuteDirect(SQL : String; ATransaction : TSQLTransaction); overload; virtual;
  87. procedure GetTableNames(List : TStrings; SystemTables : Boolean = false); virtual;
  88. procedure GetProcedureNames(List : TStrings); virtual;
  89. procedure GetFieldNames(const TableName : string; List : TStrings); virtual;
  90. published
  91. property Password : string read FPassword write FPassword;
  92. property Transaction : TSQLTransaction read FTransaction write SetTransaction;
  93. property UserName : string read FUserName write FUserName;
  94. property CharSet : string read FCharSet write FCharSet;
  95. property HostName : string Read FHostName Write FHostName;
  96. property Connected;
  97. Property Role : String read FRole write FRole;
  98. property DatabaseName;
  99. property KeepConnection;
  100. property LoginPrompt;
  101. property Params;
  102. property OnLogin;
  103. end;
  104. { TSQLTransaction }
  105. TCommitRollbackAction = (caNone, caCommit, caCommitRetaining, caRollback,
  106. caRollbackRetaining);
  107. TSQLTransaction = class (TDBTransaction)
  108. private
  109. FTrans : TSQLHandle;
  110. FAction : TCommitRollbackAction;
  111. FParams : TStringList;
  112. protected
  113. function GetHandle : Pointer; virtual;
  114. Procedure SetDatabase (Value : TDatabase); override;
  115. public
  116. procedure Commit; virtual;
  117. procedure CommitRetaining; virtual;
  118. procedure Rollback; virtual;
  119. procedure RollbackRetaining; virtual;
  120. procedure StartTransaction; override;
  121. constructor Create(AOwner : TComponent); override;
  122. destructor Destroy; override;
  123. property Handle: Pointer read GetHandle;
  124. procedure EndTransaction; override;
  125. published
  126. property Action : TCommitRollbackAction read FAction write FAction;
  127. property Database;
  128. property Params : TStringList read FParams write FParams;
  129. end;
  130. { TSQLQuery }
  131. TSQLQuery = class (Tbufdataset)
  132. private
  133. FCursor : TSQLCursor;
  134. FUpdateable : boolean;
  135. FTableName : string;
  136. FSQL : TStringList;
  137. FIsEOF : boolean;
  138. FLoadingFieldDefs : boolean;
  139. FIndexDefs : TIndexDefs;
  140. FReadOnly : boolean;
  141. FUpdateMode : TUpdateMode;
  142. FParams : TParams;
  143. FusePrimaryKeyAsKey : Boolean;
  144. FSQLBuf : String;
  145. FFromPart : String;
  146. FWhereStartPos : integer;
  147. FWhereStopPos : integer;
  148. FParseSQL : boolean;
  149. // FSchemaInfo : TSchemaInfo;
  150. procedure FreeFldBuffers;
  151. procedure InitUpdates(ASQL : string);
  152. function GetIndexDefs : TIndexDefs;
  153. function GetStatementType : TStatementType;
  154. procedure SetIndexDefs(AValue : TIndexDefs);
  155. procedure SetReadOnly(AValue : Boolean);
  156. procedure SetParseSQL(AValue : Boolean);
  157. procedure SetUsePrimaryKeyAsKey(AValue : Boolean);
  158. procedure SetUpdateMode(AValue : TUpdateMode);
  159. procedure OnChangeSQL(Sender : TObject);
  160. procedure Execute;
  161. Procedure SQLParser(var ASQL : string);
  162. procedure ApplyFilter;
  163. Function AddFilter(SQLstr : string) : string;
  164. protected
  165. // abstract & virtual methods of TBufDataset
  166. function Fetch : boolean; override;
  167. function LoadField(FieldDef : TFieldDef;buffer : pointer) : boolean; override;
  168. // abstract & virtual methods of TDataset
  169. procedure UpdateIndexDefs; override;
  170. procedure SetDatabase(Value : TDatabase); override;
  171. Procedure SetTransaction(Value : TDBTransaction); override;
  172. procedure InternalAddRecord(Buffer: Pointer; AAppend: Boolean); override;
  173. procedure InternalClose; override;
  174. procedure InternalInitFieldDefs; override;
  175. procedure InternalOpen; override;
  176. function GetCanModify: Boolean; override;
  177. function ApplyRecUpdate(UpdateKind : TUpdateKind) : boolean; override;
  178. Function IsPrepared : Boolean; virtual;
  179. Procedure SetActive (Value : Boolean); override;
  180. procedure SetFiltered(Value: Boolean); override;
  181. procedure SetFilterText(const Value: string); override;
  182. public
  183. procedure Prepare; virtual;
  184. procedure UnPrepare; virtual;
  185. procedure ExecSQL; virtual;
  186. constructor Create(AOwner : TComponent); override;
  187. destructor Destroy; override;
  188. procedure SetSchemaInfo( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string); virtual;
  189. function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream; override;
  190. property Prepared : boolean read IsPrepared;
  191. published
  192. // redeclared data set properties
  193. property Active;
  194. property Filter;
  195. property Filtered;
  196. // property FilterOptions;
  197. property BeforeOpen;
  198. property AfterOpen;
  199. property BeforeClose;
  200. property AfterClose;
  201. property BeforeInsert;
  202. property AfterInsert;
  203. property BeforeEdit;
  204. property AfterEdit;
  205. property BeforePost;
  206. property AfterPost;
  207. property BeforeCancel;
  208. property AfterCancel;
  209. property BeforeDelete;
  210. property AfterDelete;
  211. property BeforeScroll;
  212. property AfterScroll;
  213. property OnCalcFields;
  214. property OnDeleteError;
  215. property OnEditError;
  216. property OnFilterRecord;
  217. property OnNewRecord;
  218. property OnPostError;
  219. property AutoCalcFields;
  220. property Database;
  221. property Transaction;
  222. property ReadOnly : Boolean read FReadOnly write SetReadOnly;
  223. property SQL : TStringlist read FSQL write FSQL;
  224. property IndexDefs : TIndexDefs read GetIndexDefs;
  225. property Params : TParams read FParams write FParams;
  226. property UpdateMode : TUpdateMode read FUpdateMode write SetUpdateMode;
  227. property UsePrimaryKeyAsKey : boolean read FUsePrimaryKeyAsKey write SetUsePrimaryKeyAsKey;
  228. property StatementType : TStatementType read GetStatementType;
  229. property ParseSQL : Boolean read FParseSQL write SetParseSQL;
  230. // property SchemaInfo : TSchemaInfo read FSchemaInfo default stNoSchema;
  231. end;
  232. implementation
  233. uses dbconst, strutils;
  234. { TSQLConnection }
  235. function TSQLConnection.StrToStatementType(s : string) : TStatementType;
  236. var T : TStatementType;
  237. begin
  238. S:=Lowercase(s);
  239. For t:=stselect to strollback do
  240. if (S=StatementTokens[t]) then
  241. Exit(t);
  242. end;
  243. procedure TSQLConnection.SetTransaction(Value : TSQLTransaction);
  244. begin
  245. if FTransaction<>value then
  246. begin
  247. if Assigned(FTransaction) and FTransaction.Active then
  248. DatabaseError(SErrAssTransaction);
  249. if Assigned(Value) then
  250. Value.Database := Self;
  251. FTransaction := Value;
  252. end;
  253. end;
  254. procedure TSQLConnection.UpdateIndexDefs(var IndexDefs : TIndexDefs;TableName : string);
  255. begin
  256. // Empty abstract
  257. end;
  258. procedure TSQLConnection.DoInternalConnect;
  259. begin
  260. if (DatabaseName = '') then
  261. DatabaseError(SErrNoDatabaseName,self);
  262. end;
  263. procedure TSQLConnection.DoInternalDisconnect;
  264. begin
  265. end;
  266. destructor TSQLConnection.Destroy;
  267. begin
  268. inherited Destroy;
  269. end;
  270. procedure TSQLConnection.StartTransaction;
  271. begin
  272. if not assigned(Transaction) then
  273. DatabaseError(SErrConnTransactionnSet)
  274. else
  275. Transaction.StartTransaction;
  276. end;
  277. procedure TSQLConnection.EndTransaction;
  278. begin
  279. if not assigned(Transaction) then
  280. DatabaseError(SErrConnTransactionnSet)
  281. else
  282. Transaction.EndTransaction;
  283. end;
  284. Procedure TSQLConnection.ExecuteDirect(SQL: String);
  285. begin
  286. ExecuteDirect(SQL,FTransaction);
  287. end;
  288. Procedure TSQLConnection.ExecuteDirect(SQL: String; ATransaction : TSQLTransaction);
  289. var Cursor : TSQLCursor;
  290. begin
  291. if not assigned(ATransaction) then
  292. DatabaseError(SErrTransactionnSet);
  293. if not Connected then Open;
  294. if not ATransaction.Active then ATransaction.StartTransaction;
  295. try
  296. Cursor := AllocateCursorHandle;
  297. SQL := TrimRight(SQL);
  298. if SQL = '' then
  299. DatabaseError(SErrNoStatement);
  300. Cursor.FStatementType := stNone;
  301. PrepareStatement(cursor,ATransaction,SQL,Nil);
  302. execute(cursor,ATransaction, Nil);
  303. UnPrepareStatement(Cursor);
  304. finally;
  305. DeAllocateCursorHandle(Cursor);
  306. end;
  307. end;
  308. procedure TSQLConnection.GetDBInfo(const SchemaType : TSchemaType; const SchemaObjectName, ReturnField : string; List: TStrings);
  309. var qry : TSQLQuery;
  310. begin
  311. if not assigned(Transaction) then
  312. DatabaseError(SErrConnTransactionnSet);
  313. qry := tsqlquery.Create(nil);
  314. qry.transaction := Transaction;
  315. qry.database := Self;
  316. with qry do
  317. begin
  318. ParseSQL := False;
  319. SetSchemaInfo(SchemaType,SchemaObjectName,'');
  320. open;
  321. List.Clear;
  322. while not eof do
  323. begin
  324. List.Append(fieldbyname(ReturnField).asstring);
  325. Next;
  326. end;
  327. end;
  328. qry.free;
  329. end;
  330. procedure TSQLConnection.GetTableNames(List: TStrings; SystemTables: Boolean);
  331. begin
  332. if not systemtables then GetDBInfo(stTables,'','table_name',List)
  333. else GetDBInfo(stSysTables,'','table_name',List);
  334. end;
  335. procedure TSQLConnection.GetProcedureNames(List: TStrings);
  336. begin
  337. GetDBInfo(stProcedures,'','proc_name',List);
  338. end;
  339. procedure TSQLConnection.GetFieldNames(const TableName: string; List: TStrings);
  340. begin
  341. GetDBInfo(stColumns,TableName,'column_name',List);
  342. end;
  343. function TSQLConnection.GetAsSQLText(Field : TField) : string;
  344. begin
  345. if not assigned(field) then Result := 'Null'
  346. else case field.DataType of
  347. ftString : Result := '''' + field.asstring + '''';
  348. ftDate : Result := '''' + FormatDateTime('yyyy-mm-dd',Field.AsDateTime) + '''';
  349. ftDateTime : Result := '''' + FormatDateTime('yyyy-mm-dd hh:mm:ss',Field.AsDateTime) + ''''
  350. else
  351. Result := field.asstring;
  352. end; {case}
  353. end;
  354. function TSQLConnection.GetHandle: pointer;
  355. begin
  356. Result := nil;
  357. end;
  358. function TSQLConnection.GetSchemaInfoSQL( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string) : string;
  359. begin
  360. DatabaseError(SMetadataUnavailable);
  361. end;
  362. function TSQLConnection.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  363. begin
  364. DatabaseErrorFmt(SUnsupportedFieldType,['Blob']);
  365. end;
  366. { TSQLTransaction }
  367. procedure TSQLTransaction.EndTransaction;
  368. begin
  369. rollback;
  370. end;
  371. function TSQLTransaction.GetHandle: pointer;
  372. begin
  373. Result := (Database as tsqlconnection).GetTransactionHandle(FTrans);
  374. end;
  375. procedure TSQLTransaction.Commit;
  376. begin
  377. if active then
  378. begin
  379. closedatasets;
  380. if (Database as tsqlconnection).commit(FTrans) then
  381. begin
  382. closeTrans;
  383. FreeAndNil(FTrans);
  384. end;
  385. end;
  386. end;
  387. procedure TSQLTransaction.CommitRetaining;
  388. begin
  389. if active then
  390. (Database as tsqlconnection).commitRetaining(FTrans);
  391. end;
  392. procedure TSQLTransaction.Rollback;
  393. begin
  394. if active then
  395. begin
  396. closedatasets;
  397. if (Database as tsqlconnection).RollBack(FTrans) then
  398. begin
  399. CloseTrans;
  400. FreeAndNil(FTrans);
  401. end;
  402. end;
  403. end;
  404. procedure TSQLTransaction.RollbackRetaining;
  405. begin
  406. if active then
  407. (Database as tsqlconnection).RollBackRetaining(FTrans);
  408. end;
  409. procedure TSQLTransaction.StartTransaction;
  410. var db : TSQLConnection;
  411. begin
  412. if Active then
  413. DatabaseError(SErrTransAlreadyActive);
  414. db := (Database as tsqlconnection);
  415. if Db = nil then
  416. DatabaseError(SErrDatabasenAssigned);
  417. if not Db.Connected then
  418. Db.Open;
  419. if not assigned(FTrans) then FTrans := Db.AllocateTransactionHandle;
  420. if Db.StartdbTransaction(FTrans,FParams.CommaText) then OpenTrans;
  421. end;
  422. constructor TSQLTransaction.Create(AOwner : TComponent);
  423. begin
  424. inherited Create(AOwner);
  425. FParams := TStringList.Create;
  426. end;
  427. destructor TSQLTransaction.Destroy;
  428. begin
  429. Rollback;
  430. FreeAndNil(FParams);
  431. inherited Destroy;
  432. end;
  433. Procedure TSQLTransaction.SetDatabase(Value : TDatabase);
  434. begin
  435. If Value<>Database then
  436. begin
  437. CheckInactive;
  438. If Assigned(Database) then
  439. with Database as TSqlConnection do
  440. if Transaction = self then Transaction := nil;
  441. inherited SetDatabase(Value);
  442. end;
  443. end;
  444. { TSQLQuery }
  445. procedure TSQLQuery.OnChangeSQL(Sender : TObject);
  446. var s : string;
  447. i : integer;
  448. p : pchar;
  449. ParamName : String;
  450. begin
  451. UnPrepare;
  452. if (FSQL <> nil) then
  453. begin
  454. if not assigned(FParams) then FParams := TParams.create(self);
  455. FParams.ParseSQL(FSQL.Text,True);
  456. end;
  457. end;
  458. Procedure TSQLQuery.SetTransaction(Value : TDBTransaction);
  459. begin
  460. UnPrepare;
  461. inherited;
  462. end;
  463. procedure TSQLQuery.SetDatabase(Value : TDatabase);
  464. var db : tsqlconnection;
  465. begin
  466. if (Database <> Value) then
  467. begin
  468. UnPrepare;
  469. if assigned(FCursor) then (Database as TSQLConnection).DeAllocateCursorHandle(FCursor);
  470. db := value as tsqlconnection;
  471. inherited setdatabase(value);
  472. if assigned(value) and (Transaction = nil) and (Assigned(db.Transaction)) then
  473. transaction := Db.Transaction;
  474. end;
  475. end;
  476. Function TSQLQuery.IsPrepared : Boolean;
  477. begin
  478. Result := Assigned(FCursor) and FCursor.FPrepared;
  479. end;
  480. Function TSQLQuery.AddFilter(SQLstr : string) : string;
  481. begin
  482. if FWhereStartPos = 0 then
  483. SQLstr := SQLstr + ' where (' + Filter + ')'
  484. else if FWhereStopPos > 0 then
  485. system.insert(' and ('+Filter+') ',SQLstr,FWhereStopPos+1)
  486. else
  487. system.insert(' where ('+Filter+') ',SQLstr,FWhereStartPos);
  488. Result := SQLstr;
  489. end;
  490. procedure TSQLQuery.ApplyFilter;
  491. var S : String;
  492. begin
  493. FreeFldBuffers;
  494. (Database as tsqlconnection).UnPrepareStatement(FCursor);
  495. FIsEOF := False;
  496. inherited internalclose;
  497. s := FSQLBuf;
  498. if Filtered then s := AddFilter(s);
  499. (Database as tsqlconnection).PrepareStatement(Fcursor,(transaction as tsqltransaction),S,FParams);
  500. Execute;
  501. inherited InternalOpen;
  502. First;
  503. end;
  504. Procedure TSQLQuery.SetActive (Value : Boolean);
  505. begin
  506. inherited SetActive(Value);
  507. // The query is UnPrepared, so that if a transaction closes all datasets
  508. // they also get unprepared
  509. if not Value and IsPrepared then UnPrepare;
  510. end;
  511. procedure TSQLQuery.SetFiltered(Value: Boolean);
  512. begin
  513. if Value and not FParseSQL then DatabaseErrorFmt(SNoParseSQL,['Filtering ']);
  514. if (Filtered <> Value) then
  515. begin
  516. inherited setfiltered(Value);
  517. if active then ApplyFilter;
  518. end;
  519. end;
  520. procedure TSQLQuery.SetFilterText(const Value: string);
  521. begin
  522. if Value <> Filter then
  523. begin
  524. inherited SetFilterText(Value);
  525. if active then ApplyFilter;
  526. end;
  527. end;
  528. procedure TSQLQuery.Prepare;
  529. var
  530. db : tsqlconnection;
  531. sqltr : tsqltransaction;
  532. begin
  533. if not IsPrepared then
  534. begin
  535. db := (Database as tsqlconnection);
  536. sqltr := (transaction as tsqltransaction);
  537. if not assigned(Db) then
  538. DatabaseError(SErrDatabasenAssigned);
  539. if not assigned(sqltr) then
  540. DatabaseError(SErrTransactionnSet);
  541. if not Db.Connected then db.Open;
  542. if not sqltr.Active then sqltr.StartTransaction;
  543. // if assigned(fcursor) then FreeAndNil(fcursor);
  544. if not assigned(fcursor) then
  545. FCursor := Db.AllocateCursorHandle;
  546. FSQLBuf := TrimRight(FSQL.Text);
  547. if FSQLBuf = '' then
  548. DatabaseError(SErrNoStatement);
  549. SQLParser(FSQLBuf);
  550. if filtered then
  551. Db.PrepareStatement(Fcursor,sqltr,AddFilter(FSQLBuf),FParams)
  552. else
  553. Db.PrepareStatement(Fcursor,sqltr,FSQLBuf,FParams);
  554. if (FCursor.FStatementType = stSelect) then
  555. begin
  556. FCursor.FInitFieldDef := True;
  557. if not ReadOnly then InitUpdates(FSQLBuf);
  558. end;
  559. end;
  560. end;
  561. procedure TSQLQuery.UnPrepare;
  562. begin
  563. CheckInactive;
  564. if IsPrepared then with Database as TSQLConnection do
  565. UnPrepareStatement(FCursor);
  566. end;
  567. procedure TSQLQuery.FreeFldBuffers;
  568. begin
  569. if assigned(FCursor) then (Database as tsqlconnection).FreeFldBuffers(FCursor);
  570. end;
  571. function TSQLQuery.Fetch : boolean;
  572. begin
  573. if not (Fcursor.FStatementType in [stSelect]) then
  574. Exit;
  575. if not FIsEof then FIsEOF := not (Database as tsqlconnection).Fetch(Fcursor);
  576. Result := not FIsEOF;
  577. end;
  578. procedure TSQLQuery.Execute;
  579. begin
  580. (Database as tsqlconnection).execute(Fcursor,Transaction as tsqltransaction, FParams);
  581. end;
  582. function TSQLQuery.LoadField(FieldDef : TFieldDef;buffer : pointer) : boolean;
  583. begin
  584. result := (Database as tSQLConnection).LoadField(FCursor,FieldDef,buffer)
  585. end;
  586. procedure TSQLQuery.InternalAddRecord(Buffer: Pointer; AAppend: Boolean);
  587. begin
  588. // not implemented - sql dataset
  589. end;
  590. procedure TSQLQuery.InternalClose;
  591. begin
  592. if StatementType = stSelect then FreeFldBuffers;
  593. if not IsPrepared then (database as TSQLconnection).UnPrepareStatement(FCursor);
  594. if DefaultFields then
  595. DestroyFields;
  596. FIsEOF := False;
  597. // FRecordSize := 0;
  598. inherited internalclose;
  599. end;
  600. procedure TSQLQuery.InternalInitFieldDefs;
  601. begin
  602. if FLoadingFieldDefs then
  603. Exit;
  604. FLoadingFieldDefs := True;
  605. try
  606. FieldDefs.Clear;
  607. (Database as tsqlconnection).AddFieldDefs(fcursor,FieldDefs);
  608. finally
  609. FLoadingFieldDefs := False;
  610. end;
  611. end;
  612. procedure TSQLQuery.SQLParser(var ASQL : string);
  613. type TParsePart = (ppStart,ppSelect,ppWhere,ppFrom,ppOrder,ppComment,ppBogus);
  614. Var
  615. PSQL,CurrentP,
  616. PhraseP, PStatementPart : pchar;
  617. S : string;
  618. ParsePart : TParsePart;
  619. StrLength : Integer;
  620. begin
  621. PSQL:=Pchar(ASQL);
  622. ParsePart := ppStart;
  623. CurrentP := PSQL-1;
  624. PhraseP := PSQL;
  625. FWhereStartPos := 0;
  626. FWhereStopPos := 0;
  627. repeat
  628. begin
  629. inc(CurrentP);
  630. if CurrentP^ in [' ',#13,#10,#9,#0,'(',')',';'] then
  631. begin
  632. if (CurrentP-PhraseP > 0) or (CurrentP^ in [';',#0]) then
  633. begin
  634. strLength := CurrentP-PhraseP;
  635. Setlength(S,strLength);
  636. if strLength > 0 then Move(PhraseP^,S[1],(strLength));
  637. s := uppercase(s);
  638. case ParsePart of
  639. ppStart : begin
  640. FCursor.FStatementType := (Database as tsqlconnection).StrToStatementType(s);
  641. if FCursor.FStatementType = stSelect then ParsePart := ppSelect
  642. else break;
  643. if not FParseSQL then break;
  644. PStatementPart := CurrentP;
  645. end;
  646. ppSelect : begin
  647. if s = 'FROM' then
  648. begin
  649. ParsePart := ppFrom;
  650. PhraseP := CurrentP;
  651. PStatementPart := CurrentP;
  652. end;
  653. end;
  654. ppFrom : begin
  655. if (s = 'WHERE') or (s = 'ORDER') or (CurrentP^=#0) or (CurrentP^=';') then
  656. begin
  657. if (s = 'WHERE') then
  658. begin
  659. ParsePart := ppWhere;
  660. StrLength := PhraseP-PStatementPart;
  661. end
  662. else if (s = 'ORDER') then
  663. begin
  664. ParsePart := ppOrder;
  665. StrLength := PhraseP-PStatementPart
  666. end
  667. else
  668. begin
  669. ParsePart := ppBogus;
  670. StrLength := CurrentP-PStatementPart;
  671. end;
  672. Setlength(FFromPart,StrLength);
  673. Move(PStatementPart^,FFromPart[1],(StrLength));
  674. FFrompart := trim(FFrompart);
  675. FWhereStartPos := PStatementPart-PSQL+StrLength+1;
  676. PStatementPart := CurrentP;
  677. end;
  678. end;
  679. ppWhere : begin
  680. if (s = 'ORDER') or (CurrentP^=#0) or (CurrentP^=';') then
  681. begin
  682. ParsePart := ppBogus;
  683. FWhereStartPos := PStatementPart-PSQL;
  684. if s = 'ORDER' then
  685. FWhereStopPos := PhraseP-PSQL+1
  686. else
  687. FWhereStopPos := CurrentP-PSQL+1;
  688. end;
  689. end;
  690. end; {case}
  691. end;
  692. PhraseP := CurrentP+1;
  693. end
  694. end;
  695. until CurrentP^=#0;
  696. if (FWhereStartPos > 0) and (FWhereStopPos > 0) then
  697. begin
  698. system.insert('(',ASQL,FWhereStartPos+1);
  699. inc(FWhereStopPos);
  700. system.insert(')',ASQL,FWhereStopPos);
  701. end
  702. end;
  703. procedure TSQLQuery.InitUpdates(ASQL : string);
  704. begin
  705. if pos(',',FFromPart) > 0 then
  706. FUpdateable := False // select-statements from more then one table are not updateable
  707. else
  708. begin
  709. FUpdateable := True;
  710. FTableName := FFromPart;
  711. end;
  712. end;
  713. procedure TSQLQuery.InternalOpen;
  714. var tel : integer;
  715. f : TField;
  716. s : string;
  717. begin
  718. try
  719. Prepare;
  720. if FCursor.FStatementType in [stSelect] then
  721. begin
  722. Execute;
  723. if FCursor.FInitFieldDef then InternalInitFieldDefs;
  724. if DefaultFields then
  725. begin
  726. CreateFields;
  727. if FUpdateable and FusePrimaryKeyAsKey then
  728. begin
  729. UpdateIndexDefs;
  730. for tel := 0 to indexdefs.count-1 do {with indexdefs[tel] do}
  731. begin
  732. if ixPrimary in indexdefs[tel].options then
  733. begin
  734. // Todo: If there is more then one field in the key, that must be parsed
  735. s := indexdefs[tel].fields;
  736. F := Findfield(s);
  737. if F <> nil then
  738. F.ProviderFlags := F.ProviderFlags + [pfInKey];
  739. end;
  740. end;
  741. end;
  742. end;
  743. end
  744. else
  745. DatabaseError(SErrNoSelectStatement,Self);
  746. except
  747. on E:Exception do
  748. raise;
  749. end;
  750. inherited InternalOpen;
  751. end;
  752. // public part
  753. procedure TSQLQuery.ExecSQL;
  754. begin
  755. try
  756. Prepare;
  757. Execute;
  758. finally
  759. if not IsPrepared then (database as TSQLConnection).UnPrepareStatement(Fcursor);
  760. end;
  761. end;
  762. constructor TSQLQuery.Create(AOwner : TComponent);
  763. begin
  764. inherited Create(AOwner);
  765. FSQL := TStringList.Create;
  766. FSQL.OnChange := @OnChangeSQL;
  767. FIndexDefs := TIndexDefs.Create(Self);
  768. FReadOnly := false;
  769. FParseSQL := True;
  770. // Delphi has upWhereAll as default, but since strings and oldvalue's don't work yet
  771. // (variants) set it to upWhereKeyOnly
  772. FUpdateMode := upWhereKeyOnly;
  773. FUsePrimaryKeyAsKey := True;
  774. end;
  775. destructor TSQLQuery.Destroy;
  776. begin
  777. if Active then Close;
  778. UnPrepare;
  779. if assigned(FCursor) then (Database as TSQLConnection).DeAllocateCursorHandle(FCursor);
  780. FreeAndNil(FParams);
  781. FreeAndNil(FSQL);
  782. FreeAndNil(FIndexDefs);
  783. inherited Destroy;
  784. end;
  785. procedure TSQLQuery.SetReadOnly(AValue : Boolean);
  786. begin
  787. CheckInactive;
  788. if not AValue then
  789. begin
  790. if FParseSQL then FReadOnly := False
  791. else DatabaseErrorFmt(SNoParseSQL,['Updating ']);
  792. end
  793. else FReadOnly := True;
  794. end;
  795. procedure TSQLQuery.SetParseSQL(AValue : Boolean);
  796. begin
  797. CheckInactive;
  798. if not AValue then
  799. begin
  800. FReadOnly := True;
  801. Filtered := False;
  802. FParseSQL := False;
  803. end
  804. else
  805. FParseSQL := True;
  806. end;
  807. procedure TSQLQuery.SetUsePrimaryKeyAsKey(AValue : Boolean);
  808. begin
  809. if not Active then FusePrimaryKeyAsKey := AValue
  810. else
  811. begin
  812. // Just temporary, this should be possible in the future
  813. DatabaseError(SActiveDataset);
  814. end;
  815. end;
  816. Procedure TSQLQuery.UpdateIndexDefs;
  817. begin
  818. if assigned(DataBase) then
  819. (DataBase as TSQLConnection).UpdateIndexDefs(FIndexDefs,FTableName);
  820. end;
  821. function TSQLQuery.ApplyRecUpdate(UpdateKind : TUpdateKind) : boolean;
  822. var
  823. s : string;
  824. procedure UpdateWherePart(var sql_where : string;x : integer);
  825. begin
  826. if (pfInKey in Fields[x].ProviderFlags) or
  827. ((FUpdateMode = upWhereAll) and (pfInWhere in Fields[x].ProviderFlags)) or
  828. ((FUpdateMode = UpWhereChanged) and (pfInWhere in Fields[x].ProviderFlags) and (fields[x].value <> fields[x].oldvalue)) then
  829. begin
  830. // This should be converted to something like GetAsSQLText, but better wait until variants (oldvalue) are working for strings
  831. s := fields[x].oldvalue; // This directly int the line below raises a variant-error
  832. sql_where := sql_where + '(' + fields[x].FieldName + '=' + s + ') and ';
  833. end;
  834. end;
  835. function ModifyRecQuery : string;
  836. var x : integer;
  837. sql_set : string;
  838. sql_where : string;
  839. begin
  840. sql_set := '';
  841. sql_where := '';
  842. for x := 0 to Fields.Count -1 do
  843. begin
  844. UpdateWherePart(sql_where,x);
  845. if (pfInUpdate in Fields[x].ProviderFlags) then
  846. if fields[x].IsNull then // check for null
  847. sql_set := sql_set + fields[x].FieldName + '=' + (Database as TSQLConnection).GetAsSQLText(nil) + ','
  848. else
  849. sql_set := sql_set + fields[x].FieldName + '=' + (Database as TSQLConnection).GetAsSQLText(fields[x]) + ',';
  850. end;
  851. setlength(sql_set,length(sql_set)-1);
  852. setlength(sql_where,length(sql_where)-5);
  853. result := 'update ' + FTableName + ' set ' + sql_set + ' where ' + sql_where;
  854. end;
  855. function InsertRecQuery : string;
  856. var x : integer;
  857. sql_fields : string;
  858. sql_values : string;
  859. begin
  860. sql_fields := '';
  861. sql_values := '';
  862. for x := 0 to Fields.Count -1 do
  863. begin
  864. if not fields[x].IsNull then
  865. begin
  866. sql_fields := sql_fields + fields[x].DisplayName + ',';
  867. sql_values := sql_values + (Database as TSQLConnection).GetAsSQLText(fields[x]) + ',';
  868. end;
  869. end;
  870. setlength(sql_fields,length(sql_fields)-1);
  871. setlength(sql_values,length(sql_values)-1);
  872. result := 'insert into ' + FTableName + ' (' + sql_fields + ') values (' + sql_values + ')';
  873. end;
  874. function DeleteRecQuery : string;
  875. var x : integer;
  876. sql_where : string;
  877. begin
  878. sql_where := '';
  879. for x := 0 to Fields.Count -1 do
  880. UpdateWherePart(sql_where,x);
  881. setlength(sql_where,length(sql_where)-5);
  882. result := 'delete from ' + FTableName + ' where ' + sql_where;
  883. end;
  884. begin
  885. Result := True;
  886. case UpdateKind of
  887. ukModify : s := ModifyRecQuery;
  888. ukInsert : s := InsertRecQuery;
  889. ukDelete : s := DeleteRecQuery;
  890. end; {case}
  891. try
  892. (Database as TSQLConnection).ExecuteDirect(s,Transaction as TSQLTransaction);
  893. except
  894. on EDatabaseError do Result := False
  895. else
  896. raise;
  897. end;
  898. end;
  899. Function TSQLQuery.GetCanModify: Boolean;
  900. begin
  901. if FCursor.FStatementType = stSelect then
  902. Result:= Active and FUpdateable and (not FReadOnly)
  903. else
  904. Result := False;
  905. end;
  906. function TSQLQuery.GetIndexDefs : TIndexDefs;
  907. begin
  908. Result := FIndexDefs;
  909. end;
  910. procedure TSQLQuery.SetIndexDefs(AValue : TIndexDefs);
  911. begin
  912. FIndexDefs := AValue;
  913. end;
  914. procedure TSQLQuery.SetUpdateMode(AValue : TUpdateMode);
  915. begin
  916. FUpdateMode := AValue;
  917. end;
  918. procedure TSQLQuery.SetSchemaInfo( SchemaType : TSchemaType; SchemaObjectName, SchemaPattern : string);
  919. begin
  920. ReadOnly := True;
  921. SQL.Clear;
  922. SQL.Add((DataBase as tsqlconnection).GetSchemaInfoSQL(SchemaType, SchemaObjectName, SchemaPattern));
  923. end;
  924. function TSQLQuery.CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
  925. begin
  926. result := (DataBase as tsqlconnection).CreateBlobStream(Field, Mode);
  927. end;
  928. function TSQLQuery.GetStatementType : TStatementType;
  929. begin
  930. if assigned(FCursor) then Result := FCursor.FStatementType
  931. else Result := stNone;
  932. end;
  933. end.