sqldbtoolsunit.pas 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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. Function CreateQuery : TSQLQuery;
  36. protected
  37. procedure SetTestUniDirectional(const AValue: boolean); override;
  38. function GetTestUniDirectional: boolean; override;
  39. procedure CreateNDatasets; override;
  40. procedure CreateFieldDataset; override;
  41. procedure DropNDatasets; override;
  42. procedure DropFieldDataset; override;
  43. Function InternalGetNDataset(n : integer) : TDataset; override;
  44. Function InternalGetFieldDataset : TDataSet; override;
  45. procedure TryDropIfExist(ATableName : String);
  46. public
  47. destructor Destroy; override;
  48. constructor Create; override;
  49. procedure ExecuteDirect(const SQL: string);
  50. procedure CommitDDL;
  51. property Connection : TSQLConnection read FConnection;
  52. property Transaction : TSQLTransaction read FTransaction;
  53. property Query : TSQLQuery read FQuery;
  54. end;
  55. var SQLConnType : TSQLConnType;
  56. SQLServerType : TSQLServerType;
  57. FieldtypeDefinitions : Array [TFieldType] of String[20];
  58. implementation
  59. uses StrUtils;
  60. type
  61. TSQLServerTypesMapItem = record
  62. s: string;
  63. t: TSQLServerType;
  64. end;
  65. const
  66. FieldtypeDefinitionsConst : Array [TFieldType] of String[20] =
  67. (
  68. '',
  69. 'VARCHAR(10)',
  70. 'SMALLINT',
  71. 'INTEGER',
  72. '', // ftWord
  73. 'BOOLEAN',
  74. 'DOUBLE PRECISION', // ftFloat
  75. '', // ftCurrency
  76. 'DECIMAL(18,4)',// ftBCD
  77. 'DATE',
  78. 'TIME',
  79. 'TIMESTAMP', // ftDateTime
  80. '', // ftBytes
  81. '', // ftVarBytes
  82. '', // ftAutoInc
  83. 'BLOB', // ftBlob
  84. 'BLOB', // ftMemo
  85. 'BLOB', // ftGraphic
  86. '',
  87. '',
  88. '',
  89. '',
  90. '',
  91. 'CHAR(10)', // ftFixedChar
  92. '', // ftWideString
  93. 'BIGINT', // ftLargeInt
  94. '',
  95. '',
  96. '',
  97. '',
  98. '',
  99. '',
  100. '',
  101. '',
  102. '',
  103. '', // ftGuid
  104. 'TIMESTAMP', // ftTimestamp
  105. 'NUMERIC(18,6)',// ftFmtBCD
  106. '', // ftFixedWideChar
  107. '' // ftWideMemo
  108. );
  109. // names as returned by ODBC SQLGetInfo(..., SQL_DBMS_NAME, ...) and GetConnectionInfo(citServerType)
  110. SQLServerTypesMap : array [0..7] of TSQLServerTypesMapItem = (
  111. (s: 'Firebird'; t: ssFirebird),
  112. (s: 'Interbase'; t: ssInterbase),
  113. (s: 'Microsoft SQL Server'; t: ssMSSQL),
  114. (s: 'MySQL'; t: ssMySQL),
  115. (s: 'Oracle'; t: ssOracle),
  116. (s: 'PostgreSQL'; t: ssPostgreSQL),
  117. (s: 'SQLite3'; t: ssSQLite),
  118. (s: 'ASE'; t: ssSybase)
  119. );
  120. // fall back mapping (e.g. in case GetConnectionInfo(citServerType) is not implemented)
  121. SQLConnTypeToServerTypeMap : array[TSQLConnType] of TSQLServerType =
  122. (ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssPostgreSQL,ssFirebird,ssUnknown,ssOracle,ssSQLite,ssMSSQL,ssSybase);
  123. { TSQLDBConnector }
  124. procedure TSQLDBConnector.CreateFConnection;
  125. var t : TSQLConnType;
  126. i : integer;
  127. s : string;
  128. begin
  129. for t := low(SQLConnTypesNames) to high(SQLConnTypesNames) do
  130. if UpperCase(dbconnectorparams) = SQLConnTypesNames[t] then SQLConnType := t;
  131. if SQLConnType = MYSQL40 then Fconnection := TMySQL40Connection.Create(nil);
  132. if SQLConnType = MYSQL41 then Fconnection := TMySQL41Connection.Create(nil);
  133. if SQLConnType = MYSQL50 then Fconnection := TMySQL50Connection.Create(nil);
  134. if SQLConnType = MYSQL51 then Fconnection := TMySQL51Connection.Create(nil);
  135. if SQLConnType = MYSQL55 then Fconnection := TMySQL55Connection.Create(nil);
  136. if SQLConnType = MYSQL56 then Fconnection := TMySQL56Connection.Create(nil);
  137. if SQLConnType = SQLITE3 then Fconnection := TSQLite3Connection.Create(nil);
  138. if SQLConnType = POSTGRESQL then Fconnection := TPQConnection.Create(nil);
  139. if SQLConnType = INTERBASE then Fconnection := TIBConnection.Create(nil);
  140. if SQLConnType = ODBC then Fconnection := TODBCConnection.Create(nil);
  141. {$IFNDEF Win64}
  142. if SQLConnType = ORACLE then Fconnection := TOracleConnection.Create(nil);
  143. {$ENDIF Win64}
  144. if SQLConnType = MSSQL then Fconnection := TMSSQLConnection.Create(nil);
  145. if SQLConnType = SYBASE then Fconnection := TSybaseConnection.Create(nil);
  146. 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''');
  147. FTransaction := TSQLTransaction.Create(nil);
  148. with Fconnection do
  149. begin
  150. Transaction := FTransaction;
  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. // note: test database should have case-insensitive collation
  192. // todo: SQL Server 2008 and later supports DATE, TIME and DATETIME2 data types,
  193. // but these are not supported by FreeTDS yet
  194. begin
  195. FieldtypeDefinitions[ftBoolean] := 'BIT';
  196. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  197. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  198. FieldtypeDefinitions[ftDate] := 'DATETIME';
  199. FieldtypeDefinitions[ftTime] := '';
  200. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  201. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  202. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  203. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  204. FieldtypeDefinitions[ftMemo] := 'TEXT';
  205. FieldtypeDefinitions[ftGraphic] := '';
  206. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  207. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  208. //FieldtypeDefinitions[ftWideMemo] := 'NTEXT'; // Sybase has UNITEXT?
  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. //
  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_NULL_DFLT_ON ON; SET ANSI_PADDING ON; SET ANSI_WARNINGS OFF');
  221. end;
  222. FTransaction.Commit;
  223. end;
  224. ssMySQL:
  225. begin
  226. FieldtypeDefinitions[ftWord] := 'SMALLINT UNSIGNED';
  227. // MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  228. FieldtypeDefinitions[ftBoolean] := '';
  229. // Use 'DATETIME' for datetime-fields instead of timestamp, because
  230. // mysql's timestamps are only valid in the range 1970-2038.
  231. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  232. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  233. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  234. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  235. FieldtypeDefinitions[ftMemo] := 'TEXT';
  236. // Add into my.ini: sql-mode="...,PAD_CHAR_TO_FULL_LENGTH,ANSI_QUOTES" or set it explicitly by:
  237. FConnection.ExecuteDirect('SET SESSION sql_mode=''PAD_CHAR_TO_FULL_LENGTH,ANSI_QUOTES''');
  238. FTransaction.Commit;
  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. function TSQLDBConnector.CreateQuery: TSQLQuery;
  319. begin
  320. Result := TSQLQuery.create(nil);
  321. with Result do
  322. begin
  323. database := Fconnection;
  324. transaction := Ftransaction;
  325. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  326. end;
  327. end;
  328. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  329. begin
  330. FUniDirectional:=avalue;
  331. FQuery.UniDirectional:=AValue;
  332. end;
  333. function TSQLDBConnector.GetTestUniDirectional: boolean;
  334. begin
  335. result := FUniDirectional;
  336. end;
  337. procedure TSQLDBConnector.CreateNDatasets;
  338. var CountID : Integer;
  339. begin
  340. try
  341. Ftransaction.StartTransaction;
  342. TryDropIfExist('FPDEV');
  343. Fconnection.ExecuteDirect('create table FPDEV (' +
  344. ' ID INT NOT NULL, ' +
  345. ' NAME VARCHAR(50), ' +
  346. ' PRIMARY KEY (ID) ' +
  347. ')');
  348. FTransaction.CommitRetaining;
  349. for countID := 1 to MaxDataSet do
  350. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  351. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  352. Ftransaction.Commit;
  353. except
  354. if Ftransaction.Active then Ftransaction.Rollback
  355. end;
  356. end;
  357. procedure TSQLDBConnector.CreateFieldDataset;
  358. var
  359. CountID : Integer;
  360. FType : TFieldType;
  361. Sql,sql1: String;
  362. function String2Hex(Source: string): string;
  363. // Converts ASCII codes into hex
  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. FQuery := CreateQuery;
  586. Inherited;
  587. end;
  588. initialization
  589. RegisterClass(TSQLDBConnector);
  590. end.