sqldb.pp 38 KB

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