sqldbtoolsunit.pas 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. // When running CREATE TABLE statements, allow NULLs by default - without
  212. // having to specify NULL all the time:
  213. // http://msdn.microsoft.com/en-us/library/ms174979.aspx
  214. FConnection.ExecuteDirect('SET ANSI_NULL_DFLT_ON ON');
  215. TempTrans.Commit;
  216. TempTrans.Free;
  217. FConnection.Transaction:=nil;
  218. end;
  219. ssMySQL:
  220. begin
  221. // Add into my.ini: sql-mode="...,PAD_CHAR_TO_FULL_LENGTH,ANSI_QUOTES"
  222. FieldtypeDefinitions[ftWord] := 'SMALLINT UNSIGNED';
  223. // MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  224. FieldtypeDefinitions[ftBoolean] := '';
  225. // Use 'DATETIME' for datetime-fields instead of timestamp, because
  226. // mysql's timestamps are only valid in the range 1970-2038.
  227. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  228. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  229. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  230. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  231. FieldtypeDefinitions[ftMemo] := 'TEXT';
  232. end;
  233. ssOracle:
  234. begin
  235. FieldtypeDefinitions[ftBoolean] := '';
  236. // At least Oracle 10, 11 do not support a BIGINT field:
  237. FieldtypeDefinitions[ftLargeInt] := 'NUMBER(19,0)';
  238. FieldtypeDefinitions[ftTime] := 'TIMESTAMP';
  239. FieldtypeDefinitions[ftMemo] := 'CLOB';
  240. end;
  241. ssPostgreSQL:
  242. begin
  243. FieldtypeDefinitions[ftCurrency] := 'MONEY'; // ODBC?!
  244. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  245. FieldtypeDefinitions[ftMemo] := 'TEXT';
  246. FieldtypeDefinitions[ftGraphic] := '';
  247. FieldtypeDefinitions[ftGuid] := 'UUID';
  248. end;
  249. ssSQLite:
  250. begin
  251. FieldtypeDefinitions[ftWord] := 'WORD';
  252. FieldtypeDefinitions[ftCurrency] := 'CURRENCY';
  253. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  254. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  255. FieldtypeDefinitions[ftMemo] := 'CLOB'; //or TEXT SQLite supports both, but CLOB is sql standard (TEXT not)
  256. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  257. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  258. FieldtypeDefinitions[ftWideMemo] := 'NCLOB';
  259. end;
  260. end;
  261. if SQLConnType in [mysql40,mysql41] then
  262. begin
  263. // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar
  264. // fields on insertion. So to test properly, we have to do the same
  265. for i := 0 to testValuesCount-1 do
  266. testStringValues[i] := TrimRight(testStringValues[i]);
  267. end;
  268. if SQLServerType in [ssMySQL] then
  269. begin
  270. // Some DB's do not support milliseconds in datetime and time fields.
  271. for i := 0 to testValuesCount-1 do
  272. begin
  273. testTimeValues[i] := copy(testTimeValues[i],1,8)+'.000';
  274. testValues[ftTime,i] := copy(testTimeValues[i],1,8)+'.000';
  275. if length(testValues[ftDateTime,i]) > 19 then
  276. testValues[ftDateTime,i] := copy(testValues[ftDateTime,i],1,19)+'.000';
  277. end;
  278. end;
  279. if SQLServerType in [ssFirebird, ssInterbase, ssMSSQL, ssOracle, ssPostgreSQL, ssSybase] then
  280. begin
  281. // Some db's do not support times > 24:00:00
  282. testTimeValues[3]:='13:25:15.000';
  283. testValues[ftTime,3]:='13:25:15.000';
  284. if SQLServerType in [ssFirebird, ssInterbase, ssOracle] then
  285. begin
  286. // Firebird, Oracle do not support time = 24:00:00
  287. testTimeValues[2]:='23:00:00.000';
  288. testValues[ftTime,2]:='23:00:00.000';
  289. end;
  290. end;
  291. if SQLServerType in [ssMSSQL, ssSybase] then
  292. // Some DB's do not support datetime values before 1753-01-01
  293. for i := 18 to testValuesCount-1 do
  294. begin
  295. testValues[ftDate,i] := testValues[ftDate,0];
  296. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  297. end;
  298. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  299. // Here we assume, that locale on client side is same as locale on server
  300. if SQLServerType in [ssPostgreSQL] then
  301. for i := 0 to testValuesCount-1 do
  302. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  303. // SQLite does not support fixed length CHAR datatype
  304. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  305. // MSSQL set SET ANSI_PADDING ON
  306. // todo: verify Sybase behaviour
  307. if SQLServerType in [ssSQLite] then
  308. for i := 0 to testValuesCount-1 do
  309. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  310. end;
  311. procedure TSQLDBConnector.CreateFTransaction;
  312. begin
  313. Ftransaction := tsqltransaction.create(nil);
  314. with Ftransaction do
  315. database := Fconnection;
  316. end;
  317. function TSQLDBConnector.CreateQuery: TSQLQuery;
  318. begin
  319. Result := TSQLQuery.create(nil);
  320. with Result do
  321. begin
  322. database := Fconnection;
  323. transaction := Ftransaction;
  324. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  325. end;
  326. end;
  327. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  328. begin
  329. FUniDirectional:=avalue;
  330. FQuery.UniDirectional:=AValue;
  331. end;
  332. function TSQLDBConnector.GetTestUniDirectional: boolean;
  333. begin
  334. result := FUniDirectional;
  335. end;
  336. procedure TSQLDBConnector.CreateNDatasets;
  337. var CountID : Integer;
  338. begin
  339. try
  340. Ftransaction.StartTransaction;
  341. TryDropIfExist('FPDEV');
  342. Fconnection.ExecuteDirect('create table FPDEV (' +
  343. ' ID INT NOT NULL, ' +
  344. ' NAME VARCHAR(50), ' +
  345. ' PRIMARY KEY (ID) ' +
  346. ')');
  347. FTransaction.CommitRetaining;
  348. for countID := 1 to MaxDataSet do
  349. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  350. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  351. Ftransaction.Commit;
  352. except
  353. if Ftransaction.Active then Ftransaction.Rollback
  354. end;
  355. end;
  356. procedure TSQLDBConnector.CreateFieldDataset;
  357. var
  358. CountID : Integer;
  359. FType : TFieldType;
  360. Sql,sql1: String;
  361. function String2Hex(Source: string): string;
  362. // Converts ASCII codes into hex
  363. // Inverse of hex2string
  364. var
  365. i: integer;
  366. begin
  367. result := '';
  368. for i := 1 to length(Source) do
  369. result := result + inttohex(ord(Source[i]),2);
  370. end;
  371. begin
  372. try
  373. Ftransaction.StartTransaction;
  374. TryDropIfExist('FPDEV_FIELD');
  375. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  376. for FType := low(TFieldType)to high(TFieldType) do
  377. if FieldtypeDefinitions[FType]<>'' then
  378. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +
  379. FieldtypeDefinitions[FType] + ',';
  380. Sql := Sql + 'PRIMARY KEY (ID))';
  381. FConnection.ExecuteDirect(Sql);
  382. FTransaction.CommitRetaining;
  383. for countID := 0 to testValuesCount-1 do
  384. begin
  385. Sql := 'insert into FPDEV_FIELD (ID';
  386. Sql1 := 'values ('+IntToStr(countID);
  387. for FType := low(TFieldType)to high(TFieldType) do
  388. if FieldtypeDefinitions[FType]<>'' then
  389. begin
  390. sql := sql + ',F' + Fieldtypenames[FType];
  391. if testValues[FType,CountID] <> '' then
  392. case FType of
  393. ftBlob, ftBytes, ftGraphic, ftVarBytes:
  394. if SQLServerType in [ssOracle] then
  395. // Oracle does not accept string literals in blob insert statements
  396. // convert 'DEADBEEF' hex literal to binary:
  397. sql1 := sql1 + ', HEXTORAW(' + QuotedStr(String2Hex(testValues[FType,CountID])) + ') '
  398. else // other dbs have no problems with the original string values
  399. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  400. ftCurrency:
  401. sql1 := sql1 + ',' + testValues[FType,CountID];
  402. ftDate:
  403. // Oracle requires date conversion; otherwise
  404. // ORA-01861: literal does not match format string
  405. if SQLServerType in [ssOracle] then
  406. // ANSI/ISO date literal:
  407. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID])
  408. else
  409. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  410. ftDateTime:
  411. // similar to ftDate handling
  412. if SQLServerType in [ssOracle] then
  413. begin
  414. // Could be a real date+time or only date. Does not consider only time.
  415. if pos(' ',testValues[FType,CountID])>0 then
  416. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr(testValues[FType,CountID])
  417. else
  418. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID]);
  419. end
  420. else
  421. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  422. ftTime:
  423. // similar to ftDate handling
  424. if SQLServerType in [ssOracle] then
  425. // More or less arbitrary default time; there is no time-only data type in Oracle.
  426. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr('0001-01-01 '+testValues[FType,CountID])
  427. else
  428. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  429. else
  430. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  431. end
  432. else
  433. sql1 := sql1 + ',NULL';
  434. end;
  435. Sql := sql + ')';
  436. Sql1 := sql1+ ')';
  437. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  438. end;
  439. Ftransaction.Commit;
  440. except
  441. on E: Exception do begin
  442. //writeln(E.Message);
  443. if Ftransaction.Active then Ftransaction.Rollback;
  444. end;
  445. end;
  446. end;
  447. procedure TSQLDBConnector.DropNDatasets;
  448. begin
  449. if assigned(FTransaction) then
  450. begin
  451. try
  452. if Ftransaction.Active then Ftransaction.Rollback;
  453. Ftransaction.StartTransaction;
  454. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  455. Ftransaction.Commit;
  456. Except
  457. if Ftransaction.Active then Ftransaction.Rollback
  458. end;
  459. end;
  460. end;
  461. procedure TSQLDBConnector.DropFieldDataset;
  462. begin
  463. if assigned(FTransaction) then
  464. begin
  465. try
  466. if Ftransaction.Active then Ftransaction.Rollback;
  467. Ftransaction.StartTransaction;
  468. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  469. Ftransaction.Commit;
  470. Except
  471. if Ftransaction.Active then Ftransaction.Rollback
  472. end;
  473. end;
  474. end;
  475. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  476. begin
  477. Result := CreateQuery;
  478. with (Result as TSQLQuery) do
  479. begin
  480. sql.clear;
  481. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  482. UniDirectional:=TestUniDirectional;
  483. end;
  484. end;
  485. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  486. begin
  487. Result := CreateQuery;
  488. with (Result as TSQLQuery) do
  489. begin
  490. sql.clear;
  491. sql.add('SELECT * FROM FPDEV_FIELD');
  492. UniDirectional:=TestUniDirectional;
  493. end;
  494. end;
  495. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  496. begin
  497. // This makes life so much easier, since it avoids the exception if the table already
  498. // exists. And while this exception is in a try..except statement, the debugger
  499. // always shows the exception, which is pretty annoying.
  500. try
  501. case SQLServerType of
  502. ssFirebird:
  503. begin
  504. // This only works with Firebird 2+
  505. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  506. 'then execute statement ''drop table ' + ATableName + ';'';end');
  507. FTransaction.CommitRetaining;
  508. end;
  509. ssMSSQL:
  510. begin
  511. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  512. // which leads to the rollback not referring to the right transaction=>SQL error
  513. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  514. FConnection.ExecuteDirect(
  515. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  516. 'begin '+
  517. 'drop table ' + ATableName + ' '+
  518. 'end');
  519. end;
  520. ssMySQL:
  521. begin
  522. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  523. end;
  524. ssOracle:
  525. begin
  526. FConnection.ExecuteDirect(
  527. 'declare ' +
  528. ' c int; ' +
  529. 'begin ' +
  530. ' select count(*) into c from all_tables where table_name = upper(''' + ATableName + '''); ' +
  531. ' if c = 1 then ' +
  532. ' execute immediate ''drop table ' + ATableName + '''; ' +
  533. ' end if; ' +
  534. 'end; ');
  535. end;
  536. ssSybase:
  537. begin
  538. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  539. // which leads to the rollback not referring to the right transaction=>SQL error
  540. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  541. FConnection.ExecuteDirect(
  542. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  543. 'begin '+
  544. 'drop table ' + ATableName + ' '+
  545. 'end');
  546. end;
  547. end;
  548. except
  549. FTransaction.RollbackRetaining;
  550. end;
  551. end;
  552. procedure TSQLDBConnector.ExecuteDirect(const SQL: string);
  553. begin
  554. Connection.ExecuteDirect(SQL);
  555. end;
  556. procedure TSQLDBConnector.CommitDDL;
  557. begin
  558. // Commits schema definition and manipulation statements;
  559. // Firebird/Interbase need a commit after a DDL statement. Not necessary for the other connections
  560. if SQLServerType in [ssFirebird, ssInterbase] then
  561. Transaction.CommitRetaining;
  562. end;
  563. destructor TSQLDBConnector.Destroy;
  564. begin
  565. if assigned(FTransaction) then
  566. begin
  567. try
  568. if Ftransaction.Active then Ftransaction.Rollback;
  569. Ftransaction.StartTransaction;
  570. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  571. Ftransaction.Commit;
  572. Except
  573. if Ftransaction.Active then Ftransaction.Rollback;
  574. end; // try
  575. end;
  576. inherited Destroy;
  577. FreeAndNil(FQuery);
  578. FreeAndNil(FTransaction);
  579. FreeAndNil(FConnection);
  580. end;
  581. constructor TSQLDBConnector.Create;
  582. begin
  583. FConnection := nil;
  584. CreateFConnection;
  585. CreateFTransaction;
  586. FQuery := CreateQuery;
  587. FConnection.Transaction := FTransaction;
  588. Inherited;
  589. end;
  590. initialization
  591. RegisterClass(TSQLDBConnector);
  592. end.