sqldb.pp 30 KB

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