sqldbtoolsunit.pas 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. unit SQLDBToolsUnit;
  2. {$mode objfpc}{$H+}
  3. interface
  4. uses
  5. Classes, SysUtils, toolsunit
  6. ,db, sqldb
  7. ,mysql40conn, mysql41conn, mysql50conn, mysql51conn, mysql55conn, mysql56conn
  8. ,ibconnection
  9. ,pqconnection
  10. ,odbcconn
  11. {$IFNDEF WIN64}
  12. {See packages\fcl-db\fpmake.pp: Oracle connector not built yet on Win64}
  13. ,oracleconnection
  14. {$ENDIF WIN64}
  15. ,sqlite3conn
  16. ,mssqlconn
  17. ;
  18. type
  19. TSQLConnType = (mysql40,mysql41,mysql50,mysql51,mysql55,mysql56,postgresql,interbase,odbc,oracle,sqlite3,mssql,sybase);
  20. TSQLServerType = (ssFirebird, ssInterbase, ssMSSQL, ssMySQL, ssOracle, ssPostgreSQL, ssSQLite, ssSybase, ssUnknown);
  21. const
  22. MySQLConnTypes = [mysql40,mysql41,mysql50,mysql51,mysql55,mysql56];
  23. SQLConnTypesNames : Array [TSQLConnType] of String[19] =
  24. ('MYSQL40','MYSQL41','MYSQL50','MYSQL51','MYSQL55','MYSQL56','POSTGRESQL','INTERBASE','ODBC','ORACLE','SQLITE3','MSSQL','SYBASE');
  25. STestNotApplicable = 'This test does not apply to this sqldb connection type';
  26. type
  27. { TSQLDBConnector }
  28. TSQLDBConnector = class(TDBConnector)
  29. private
  30. FConnection : TSQLConnection;
  31. FTransaction : TSQLTransaction;
  32. FQuery : TSQLQuery;
  33. FUniDirectional: boolean;
  34. procedure CreateFConnection;
  35. procedure CreateFTransaction;
  36. Function CreateQuery : TSQLQuery;
  37. protected
  38. procedure SetTestUniDirectional(const AValue: boolean); override;
  39. function GetTestUniDirectional: boolean; override;
  40. procedure CreateNDatasets; override;
  41. procedure CreateFieldDataset; override;
  42. procedure DropNDatasets; override;
  43. procedure DropFieldDataset; override;
  44. Function InternalGetNDataset(n : integer) : TDataset; override;
  45. Function InternalGetFieldDataset : TDataSet; override;
  46. procedure TryDropIfExist(ATableName : String);
  47. public
  48. destructor Destroy; override;
  49. constructor Create; override;
  50. procedure ExecuteDirect(const SQL: string);
  51. procedure CommitDDL;
  52. property Connection : TSQLConnection read FConnection;
  53. property Transaction : TSQLTransaction read FTransaction;
  54. property Query : TSQLQuery read FQuery;
  55. end;
  56. var SQLConnType : TSQLConnType;
  57. SQLServerType : TSQLServerType;
  58. FieldtypeDefinitions : Array [TFieldType] of String[20];
  59. implementation
  60. uses StrUtils;
  61. type
  62. TSQLServerTypesMapItem = record
  63. s: string;
  64. t: TSQLServerType;
  65. end;
  66. const
  67. FieldtypeDefinitionsConst : Array [TFieldType] of String[20] =
  68. (
  69. '',
  70. 'VARCHAR(10)',
  71. 'SMALLINT',
  72. 'INTEGER',
  73. '', // ftWord
  74. 'BOOLEAN',
  75. 'DOUBLE PRECISION', // ftFloat
  76. '', // ftCurrency
  77. 'DECIMAL(18,4)',// ftBCD
  78. 'DATE',
  79. 'TIME',
  80. 'TIMESTAMP', // ftDateTime
  81. '', // ftBytes
  82. '', // ftVarBytes
  83. '', // ftAutoInc
  84. 'BLOB', // ftBlob
  85. 'BLOB', // ftMemo
  86. 'BLOB', // ftGraphic
  87. '',
  88. '',
  89. '',
  90. '',
  91. '',
  92. 'CHAR(10)', // ftFixedChar
  93. '', // ftWideString
  94. 'BIGINT', // ftLargeInt
  95. '',
  96. '',
  97. '',
  98. '',
  99. '',
  100. '',
  101. '',
  102. '',
  103. '',
  104. '', // ftGuid
  105. 'TIMESTAMP', // ftTimestamp
  106. 'NUMERIC(18,6)',// ftFmtBCD
  107. '', // ftFixedWideChar
  108. '' // ftWideMemo
  109. );
  110. // names as returned by ODBC SQLGetInfo(..., SQL_DBMS_NAME, ...) and GetConnectionInfo(citServerType)
  111. SQLServerTypesMap : array [0..7] of TSQLServerTypesMapItem = (
  112. (s: 'Firebird'; t: ssFirebird),
  113. (s: 'Interbase'; t: ssInterbase),
  114. (s: 'Microsoft SQL Server'; t: ssMSSQL),
  115. (s: 'MySQL'; t: ssMySQL),
  116. (s: 'Oracle'; t: ssOracle),
  117. (s: 'PostgreSQL'; t: ssPostgreSQL),
  118. (s: 'SQLite3'; t: ssSQLite),
  119. (s: 'ASE'; t: ssSybase)
  120. );
  121. // fall back mapping (e.g. in case GetConnectionInfo(citServerType) is not implemented)
  122. SQLConnTypeToServerTypeMap : array[TSQLConnType] of TSQLServerType =
  123. (ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssPostgreSQL,ssFirebird,ssUnknown,ssOracle,ssSQLite,ssMSSQL,ssSybase);
  124. { TSQLDBConnector }
  125. procedure TSQLDBConnector.CreateFConnection;
  126. var t : TSQLConnType;
  127. i : integer;
  128. s : string;
  129. TempTrans: TSQLTransaction;
  130. begin
  131. for t := low(SQLConnTypesNames) to high(SQLConnTypesNames) do
  132. if UpperCase(dbconnectorparams) = SQLConnTypesNames[t] then SQLConnType := t;
  133. if SQLConnType = MYSQL40 then Fconnection := TMySQL40Connection.Create(nil);
  134. if SQLConnType = MYSQL41 then Fconnection := TMySQL41Connection.Create(nil);
  135. if SQLConnType = MYSQL50 then Fconnection := TMySQL50Connection.Create(nil);
  136. if SQLConnType = MYSQL51 then Fconnection := TMySQL51Connection.Create(nil);
  137. if SQLConnType = MYSQL55 then Fconnection := TMySQL55Connection.Create(nil);
  138. if SQLConnType = MYSQL56 then Fconnection := TMySQL56Connection.Create(nil);
  139. if SQLConnType = SQLITE3 then Fconnection := TSQLite3Connection.Create(nil);
  140. if SQLConnType = POSTGRESQL then Fconnection := TPQConnection.Create(nil);
  141. if SQLConnType = INTERBASE then Fconnection := TIBConnection.Create(nil);
  142. if SQLConnType = ODBC then Fconnection := TODBCConnection.Create(nil);
  143. {$IFNDEF Win64}
  144. if SQLConnType = ORACLE then Fconnection := TOracleConnection.Create(nil);
  145. {$ENDIF Win64}
  146. if SQLConnType = MSSQL then Fconnection := TMSSQLConnection.Create(nil);
  147. if SQLConnType = SYBASE then Fconnection := TSybaseConnection.Create(nil);
  148. if not assigned(Fconnection) then writeln('Invalid database type, check if a valid database type for your achitecture was provided in the file ''database.ini''');
  149. with Fconnection do
  150. begin
  151. DatabaseName := dbname;
  152. UserName := dbuser;
  153. Password := dbpassword;
  154. HostName := dbhostname;
  155. if (dbhostname='') and (SQLConnType=interbase) then
  156. begin
  157. // Firebird embedded: create database file if it doesn't yet exist
  158. // Note: pagesize parameter has influence on behavior. We're using
  159. // Firebird default here.
  160. if not(fileexists(dbname)) then
  161. CreateDB; //Create testdb
  162. end;
  163. if length(dbQuoteChars)>1 then
  164. FieldNameQuoteChars:=dbQuoteChars;
  165. Open;
  166. end;
  167. // determine remote SQL Server to which we are connected
  168. s := Fconnection.GetConnectionInfo(citServerType);
  169. if s = '' then
  170. SQLServerType := SQLConnTypeToServerTypeMap[SQLConnType] // if citServerType isn't implemented
  171. else
  172. for i := low(SQLServerTypesMap) to high(SQLServerTypesMap) do
  173. if SQLServerTypesMap[i].s = s then
  174. SQLServerType := SQLServerTypesMap[i].t;
  175. FieldtypeDefinitions := FieldtypeDefinitionsConst;
  176. // Server-specific initialization
  177. case SQLServerType of
  178. ssFirebird:
  179. begin
  180. // Firebird < 3.0 has no support for Boolean data type:
  181. FieldtypeDefinitions[ftBoolean] := '';
  182. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  183. end;
  184. ssInterbase:
  185. begin
  186. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  187. FieldtypeDefinitions[ftLargeInt] := 'NUMERIC(18,0)';
  188. end;
  189. ssMSSQL, ssSybase:
  190. // todo: Sybase: copied over MSSQL; verify correctness
  191. begin
  192. FieldtypeDefinitions[ftBoolean] := 'BIT';
  193. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  194. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  195. FieldtypeDefinitions[ftDate] := 'DATETIME';
  196. FieldtypeDefinitions[ftTime] := '';
  197. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  198. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  199. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  200. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  201. FieldtypeDefinitions[ftMemo] := 'TEXT';
  202. FieldtypeDefinitions[ftGraphic] := '';
  203. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  204. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  205. //FieldtypeDefinitions[ftWideMemo] := 'NTEXT'; // Sybase has UNITEXT?
  206. TempTrans:=TSQLTransaction.Create(nil);
  207. FConnection.Transaction:=TempTrans;
  208. TempTrans.StartTransaction;
  209. // Proper blob support:
  210. FConnection.ExecuteDirect('SET TEXTSIZE 2147483647');
  211. if SQLServerType=ssMSSQL then
  212. begin
  213. // When running CREATE TABLE statements, allow NULLs by default - without
  214. // having to specify NULL all the time:
  215. // http://msdn.microsoft.com/en-us/library/ms174979.aspx
  216. FConnection.ExecuteDirect('SET ANSI_NULL_DFLT_ON ON');
  217. // Padding character fields is expected by ANSI and sqldb, as well as
  218. // recommended by Microsoft:
  219. // http://msdn.microsoft.com/en-us/library/ms187403.aspx
  220. FConnection.ExecuteDirect('SET ANSI_PADDING ON');
  221. end;
  222. TempTrans.Commit;
  223. TempTrans.Free;
  224. FConnection.Transaction:=nil;
  225. end;
  226. ssMySQL:
  227. begin
  228. // Add into my.ini: sql-mode="...,PAD_CHAR_TO_FULL_LENGTH,ANSI_QUOTES"
  229. FieldtypeDefinitions[ftWord] := 'SMALLINT UNSIGNED';
  230. // MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  231. FieldtypeDefinitions[ftBoolean] := '';
  232. // Use 'DATETIME' for datetime-fields instead of timestamp, because
  233. // mysql's timestamps are only valid in the range 1970-2038.
  234. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  235. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  236. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  237. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  238. FieldtypeDefinitions[ftMemo] := 'TEXT';
  239. end;
  240. ssOracle:
  241. begin
  242. FieldtypeDefinitions[ftBoolean] := '';
  243. // At least Oracle 10, 11 do not support a BIGINT field:
  244. FieldtypeDefinitions[ftLargeInt] := 'NUMBER(19,0)';
  245. FieldtypeDefinitions[ftTime] := 'TIMESTAMP';
  246. FieldtypeDefinitions[ftMemo] := 'CLOB';
  247. end;
  248. ssPostgreSQL:
  249. begin
  250. FieldtypeDefinitions[ftCurrency] := 'MONEY'; // ODBC?!
  251. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  252. FieldtypeDefinitions[ftMemo] := 'TEXT';
  253. FieldtypeDefinitions[ftGraphic] := '';
  254. FieldtypeDefinitions[ftGuid] := 'UUID';
  255. end;
  256. ssSQLite:
  257. begin
  258. FieldtypeDefinitions[ftWord] := 'WORD';
  259. FieldtypeDefinitions[ftCurrency] := 'CURRENCY';
  260. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  261. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  262. FieldtypeDefinitions[ftMemo] := 'CLOB'; //or TEXT SQLite supports both, but CLOB is sql standard (TEXT not)
  263. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  264. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  265. FieldtypeDefinitions[ftWideMemo] := 'NCLOB';
  266. end;
  267. end;
  268. if SQLConnType in [mysql40,mysql41] then
  269. begin
  270. // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar
  271. // fields on insertion. So to test properly, we have to do the same
  272. for i := 0 to testValuesCount-1 do
  273. testStringValues[i] := TrimRight(testStringValues[i]);
  274. end;
  275. if SQLServerType in [ssMySQL] then
  276. begin
  277. // Some DB's do not support milliseconds in datetime and time fields.
  278. for i := 0 to testValuesCount-1 do
  279. begin
  280. testTimeValues[i] := copy(testTimeValues[i],1,8)+'.000';
  281. testValues[ftTime,i] := copy(testTimeValues[i],1,8)+'.000';
  282. if length(testValues[ftDateTime,i]) > 19 then
  283. testValues[ftDateTime,i] := copy(testValues[ftDateTime,i],1,19)+'.000';
  284. end;
  285. end;
  286. if SQLServerType in [ssFirebird, ssInterbase, ssMSSQL, ssOracle, ssPostgreSQL, ssSybase] then
  287. begin
  288. // Some db's do not support times > 24:00:00
  289. testTimeValues[3]:='13:25:15.000';
  290. testValues[ftTime,3]:='13:25:15.000';
  291. if SQLServerType in [ssFirebird, ssInterbase, ssOracle] then
  292. begin
  293. // Firebird, Oracle do not support time = 24:00:00
  294. testTimeValues[2]:='23:00:00.000';
  295. testValues[ftTime,2]:='23:00:00.000';
  296. end;
  297. end;
  298. if SQLServerType in [ssMSSQL, ssSybase] then
  299. // Some DB's do not support datetime values before 1753-01-01
  300. for i := 18 to testValuesCount-1 do
  301. begin
  302. testValues[ftDate,i] := testValues[ftDate,0];
  303. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  304. end;
  305. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  306. // Here we assume, that locale on client side is same as locale on server
  307. if SQLServerType in [ssPostgreSQL] then
  308. for i := 0 to testValuesCount-1 do
  309. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  310. // SQLite does not support fixed length CHAR datatype
  311. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  312. // MSSQL set SET ANSI_PADDING ON
  313. // todo: verify Sybase behaviour
  314. if SQLServerType in [ssSQLite] then
  315. for i := 0 to testValuesCount-1 do
  316. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  317. end;
  318. procedure TSQLDBConnector.CreateFTransaction;
  319. begin
  320. Ftransaction := tsqltransaction.create(nil);
  321. with Ftransaction do
  322. database := Fconnection;
  323. end;
  324. function TSQLDBConnector.CreateQuery: TSQLQuery;
  325. begin
  326. Result := TSQLQuery.create(nil);
  327. with Result do
  328. begin
  329. database := Fconnection;
  330. transaction := Ftransaction;
  331. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  332. end;
  333. end;
  334. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  335. begin
  336. FUniDirectional:=avalue;
  337. FQuery.UniDirectional:=AValue;
  338. end;
  339. function TSQLDBConnector.GetTestUniDirectional: boolean;
  340. begin
  341. result := FUniDirectional;
  342. end;
  343. procedure TSQLDBConnector.CreateNDatasets;
  344. var CountID : Integer;
  345. begin
  346. try
  347. Ftransaction.StartTransaction;
  348. TryDropIfExist('FPDEV');
  349. Fconnection.ExecuteDirect('create table FPDEV (' +
  350. ' ID INT NOT NULL, ' +
  351. ' NAME VARCHAR(50), ' +
  352. ' PRIMARY KEY (ID) ' +
  353. ')');
  354. FTransaction.CommitRetaining;
  355. for countID := 1 to MaxDataSet do
  356. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  357. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  358. Ftransaction.Commit;
  359. except
  360. if Ftransaction.Active then Ftransaction.Rollback
  361. end;
  362. end;
  363. procedure TSQLDBConnector.CreateFieldDataset;
  364. var
  365. CountID : Integer;
  366. FType : TFieldType;
  367. Sql,sql1: String;
  368. function String2Hex(Source: string): string;
  369. // Converts ASCII codes into hex
  370. var
  371. i: integer;
  372. begin
  373. result := '';
  374. for i := 1 to length(Source) do
  375. result := result + inttohex(ord(Source[i]),2);
  376. end;
  377. begin
  378. try
  379. Ftransaction.StartTransaction;
  380. TryDropIfExist('FPDEV_FIELD');
  381. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  382. for FType := low(TFieldType)to high(TFieldType) do
  383. if FieldtypeDefinitions[FType]<>'' then
  384. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +
  385. FieldtypeDefinitions[FType] + ',';
  386. Sql := Sql + 'PRIMARY KEY (ID))';
  387. FConnection.ExecuteDirect(Sql);
  388. FTransaction.CommitRetaining;
  389. for countID := 0 to testValuesCount-1 do
  390. begin
  391. Sql := 'insert into FPDEV_FIELD (ID';
  392. Sql1 := 'values ('+IntToStr(countID);
  393. for FType := low(TFieldType)to high(TFieldType) do
  394. if FieldtypeDefinitions[FType]<>'' then
  395. begin
  396. sql := sql + ',F' + Fieldtypenames[FType];
  397. if testValues[FType,CountID] <> '' then
  398. case FType of
  399. ftBlob, ftBytes, ftGraphic, ftVarBytes:
  400. if SQLServerType in [ssOracle] then
  401. // Oracle does not accept string literals in blob insert statements
  402. // convert 'DEADBEEF' hex literal to binary:
  403. sql1 := sql1 + ', HEXTORAW(' + QuotedStr(String2Hex(testValues[FType,CountID])) + ') '
  404. else // other dbs have no problems with the original string values
  405. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  406. ftCurrency:
  407. sql1 := sql1 + ',' + testValues[FType,CountID];
  408. ftDate:
  409. // Oracle requires date conversion; otherwise
  410. // ORA-01861: literal does not match format string
  411. if SQLServerType in [ssOracle] then
  412. // ANSI/ISO date literal:
  413. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID])
  414. else
  415. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  416. ftDateTime:
  417. // similar to ftDate handling
  418. if SQLServerType in [ssOracle] then
  419. begin
  420. // Could be a real date+time or only date. Does not consider only time.
  421. if pos(' ',testValues[FType,CountID])>0 then
  422. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr(testValues[FType,CountID])
  423. else
  424. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID]);
  425. end
  426. else
  427. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  428. ftTime:
  429. // similar to ftDate handling
  430. if SQLServerType in [ssOracle] then
  431. // More or less arbitrary default time; there is no time-only data type in Oracle.
  432. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr('0001-01-01 '+testValues[FType,CountID])
  433. else
  434. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  435. else
  436. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  437. end
  438. else
  439. sql1 := sql1 + ',NULL';
  440. end;
  441. Sql := sql + ')';
  442. Sql1 := sql1+ ')';
  443. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  444. end;
  445. Ftransaction.Commit;
  446. except
  447. on E: Exception do begin
  448. //writeln(E.Message);
  449. if Ftransaction.Active then Ftransaction.Rollback;
  450. end;
  451. end;
  452. end;
  453. procedure TSQLDBConnector.DropNDatasets;
  454. begin
  455. if assigned(FTransaction) then
  456. begin
  457. try
  458. if Ftransaction.Active then Ftransaction.Rollback;
  459. Ftransaction.StartTransaction;
  460. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  461. Ftransaction.Commit;
  462. Except
  463. if Ftransaction.Active then Ftransaction.Rollback
  464. end;
  465. end;
  466. end;
  467. procedure TSQLDBConnector.DropFieldDataset;
  468. begin
  469. if assigned(FTransaction) then
  470. begin
  471. try
  472. if Ftransaction.Active then Ftransaction.Rollback;
  473. Ftransaction.StartTransaction;
  474. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  475. Ftransaction.Commit;
  476. Except
  477. if Ftransaction.Active then Ftransaction.Rollback
  478. end;
  479. end;
  480. end;
  481. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  482. begin
  483. Result := CreateQuery;
  484. with (Result as TSQLQuery) do
  485. begin
  486. sql.clear;
  487. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  488. UniDirectional:=TestUniDirectional;
  489. end;
  490. end;
  491. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  492. begin
  493. Result := CreateQuery;
  494. with (Result as TSQLQuery) do
  495. begin
  496. sql.clear;
  497. sql.add('SELECT * FROM FPDEV_FIELD');
  498. UniDirectional:=TestUniDirectional;
  499. end;
  500. end;
  501. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  502. begin
  503. // This makes life so much easier, since it avoids the exception if the table already
  504. // exists. And while this exception is in a try..except statement, the debugger
  505. // always shows the exception, which is pretty annoying.
  506. try
  507. case SQLServerType of
  508. ssFirebird:
  509. begin
  510. // This only works with Firebird 2+
  511. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  512. 'then execute statement ''drop table ' + ATableName + ';'';end');
  513. FTransaction.CommitRetaining;
  514. end;
  515. ssMSSQL:
  516. begin
  517. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  518. // which leads to the rollback not referring to the right transaction=>SQL error
  519. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  520. FConnection.ExecuteDirect(
  521. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  522. 'begin '+
  523. 'drop table ' + ATableName + ' '+
  524. 'end');
  525. end;
  526. ssMySQL:
  527. begin
  528. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  529. end;
  530. ssOracle:
  531. begin
  532. FConnection.ExecuteDirect(
  533. 'declare ' +
  534. ' c int; ' +
  535. 'begin ' +
  536. ' select count(*) into c from all_tables where table_name = upper(''' + ATableName + '''); ' +
  537. ' if c = 1 then ' +
  538. ' execute immediate ''drop table ' + ATableName + '''; ' +
  539. ' end if; ' +
  540. 'end; ');
  541. end;
  542. ssSybase:
  543. begin
  544. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  545. // which leads to the rollback not referring to the right transaction=>SQL error
  546. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  547. FConnection.ExecuteDirect(
  548. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  549. 'begin '+
  550. 'drop table ' + ATableName + ' '+
  551. 'end');
  552. end;
  553. end;
  554. except
  555. FTransaction.RollbackRetaining;
  556. end;
  557. end;
  558. procedure TSQLDBConnector.ExecuteDirect(const SQL: string);
  559. begin
  560. Connection.ExecuteDirect(SQL);
  561. end;
  562. procedure TSQLDBConnector.CommitDDL;
  563. begin
  564. // Commits schema definition and manipulation statements;
  565. // Firebird/Interbase need a commit after a DDL statement. Not necessary for the other connections
  566. if SQLServerType in [ssFirebird, ssInterbase] then
  567. Transaction.CommitRetaining;
  568. end;
  569. destructor TSQLDBConnector.Destroy;
  570. begin
  571. if assigned(FTransaction) then
  572. begin
  573. try
  574. if Ftransaction.Active then Ftransaction.Rollback;
  575. Ftransaction.StartTransaction;
  576. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  577. Ftransaction.Commit;
  578. Except
  579. if Ftransaction.Active then Ftransaction.Rollback;
  580. end; // try
  581. end;
  582. inherited Destroy;
  583. FreeAndNil(FQuery);
  584. FreeAndNil(FTransaction);
  585. FreeAndNil(FConnection);
  586. end;
  587. constructor TSQLDBConnector.Create;
  588. begin
  589. FConnection := nil;
  590. CreateFConnection;
  591. CreateFTransaction;
  592. FQuery := CreateQuery;
  593. FConnection.Transaction := FTransaction;
  594. Inherited;
  595. end;
  596. initialization
  597. RegisterClass(TSQLDBConnector);
  598. end.