sqldbtoolsunit.pas 23 KB

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