sqldbtoolsunit.pas 24 KB

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