sqldb.pp 39 KB

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