sqldb.pp 34 KB

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