sqldbtoolsunit.pas 25 KB

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