sqldbtoolsunit.pas 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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. {ftUnknown} '',
  75. {ftString} 'VARCHAR(10)',
  76. {ftSmallint} 'SMALLINT',
  77. {ftInteger} 'INTEGER',
  78. {ftWord} '',
  79. {ftBoolean} 'BOOLEAN',
  80. {ftFloat} 'DOUBLE PRECISION',
  81. {ftCurrency} '',
  82. {ftBCD} 'DECIMAL(18,4)',
  83. {ftDate} 'DATE',
  84. {ftTime} 'TIME',
  85. {ftDateTime} 'TIMESTAMP',
  86. {ftBytes} '',
  87. {ftVarBytes} '',
  88. {ftAutoInc} '',
  89. {ftBlob} 'BLOB',
  90. {ftMemo} 'BLOB',
  91. {ftGraphic} 'BLOB',
  92. {ftFmtMemo} '',
  93. {ftParadoxOle} '',
  94. {ftDBaseOle} '',
  95. {ftTypedBinary} '',
  96. {ftCursor} '',
  97. {ftFixedChar} 'CHAR(10)',
  98. {ftWideString} '',
  99. {ftLargeint} 'BIGINT',
  100. {ftADT} '',
  101. {ftArray} '',
  102. {ftReference} '',
  103. {ftDataSet} '',
  104. {ftOraBlob} '',
  105. {ftOraClob} '',
  106. {ftVariant} '',
  107. {ftInterface} '',
  108. {ftIDispatch} '',
  109. {ftGuid} '',
  110. {ftTimeStamp} 'TIMESTAMP',
  111. {ftFMTBcd} 'NUMERIC(18,6)',
  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, ssMSSQL, ssOracle] then
  335. begin
  336. // Firebird, Oracle, MS SQL Server do not support time = 24:00:00
  337. // MS SQL Server "datetime" supports only time up to 23:59:59.997
  338. testTimeValues[2]:='23:59:59.997';
  339. testValues[ftTime,2]:='23:59:59.997';
  340. end;
  341. end;
  342. if SQLServerType in [ssMSSQL, ssSybase] then
  343. // Some DB's do not support datetime values before 1753-01-01
  344. for i := 18 to testValuesCount-1 do
  345. begin
  346. testValues[ftDate,i] := testValues[ftDate,0];
  347. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  348. end;
  349. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  350. // Here we assume, that locale on client side is same as locale on server
  351. if SQLServerType in [ssPostgreSQL] then
  352. for i := 0 to testValuesCount-1 do
  353. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  354. // SQLite does not support fixed length CHAR datatype
  355. if SQLServerType in [ssSQLite] then
  356. for i := 0 to testValuesCount-1 do
  357. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  358. end;
  359. function TSQLDBConnector.CreateQuery: TSQLQuery;
  360. begin
  361. Result := TSQLQuery.create(nil);
  362. with Result do
  363. begin
  364. database := Fconnection;
  365. transaction := Ftransaction;
  366. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  367. end;
  368. end;
  369. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  370. begin
  371. FUniDirectional:=avalue;
  372. FQuery.UniDirectional:=AValue;
  373. end;
  374. function TSQLDBConnector.GetTestUniDirectional: boolean;
  375. begin
  376. result := FUniDirectional;
  377. end;
  378. procedure TSQLDBConnector.CreateNDatasets;
  379. var CountID : Integer;
  380. begin
  381. try
  382. Ftransaction.StartTransaction;
  383. TryDropIfExist('FPDEV');
  384. Fconnection.ExecuteDirect('create table FPDEV (' +
  385. ' ID INT NOT NULL, ' +
  386. ' NAME VARCHAR(50), ' +
  387. ' PRIMARY KEY (ID) ' +
  388. ')');
  389. FTransaction.CommitRetaining;
  390. for countID := 1 to MaxDataSet do
  391. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME) ' +
  392. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  393. Ftransaction.Commit;
  394. except
  395. on E: Exception do begin
  396. if dblogfilename<>'' then
  397. DoLogEvent(nil,detCustom,'Exception running CreateNDatasets: '+E.Message);
  398. if Ftransaction.Active then
  399. Ftransaction.Rollback
  400. end;
  401. end;
  402. end;
  403. procedure TSQLDBConnector.CreateFieldDataset;
  404. var
  405. CountID : Integer;
  406. FType : TFieldType;
  407. Sql,sql1: String;
  408. function String2Hex(Source: string): string;
  409. // Converts ASCII codes into hex
  410. var
  411. i: integer;
  412. begin
  413. result := '';
  414. for i := 1 to length(Source) do
  415. result := result + inttohex(ord(Source[i]),2);
  416. end;
  417. begin
  418. try
  419. Ftransaction.StartTransaction;
  420. TryDropIfExist('FPDEV_FIELD');
  421. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  422. for FType := low(TFieldType)to high(TFieldType) do
  423. if FieldtypeDefinitions[FType]<>'' then
  424. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +
  425. FieldtypeDefinitions[FType] + ',';
  426. Sql := Sql + 'PRIMARY KEY (ID))';
  427. FConnection.ExecuteDirect(Sql);
  428. FTransaction.CommitRetaining;
  429. for countID := 0 to testValuesCount-1 do
  430. begin
  431. Sql := 'insert into FPDEV_FIELD (ID';
  432. Sql1 := 'values ('+IntToStr(countID);
  433. for FType := low(TFieldType)to high(TFieldType) do
  434. if FieldtypeDefinitions[FType]<>'' then
  435. begin
  436. sql := sql + ',F' + Fieldtypenames[FType];
  437. if testValues[FType,CountID] <> '' then
  438. case FType of
  439. ftBlob, ftBytes, ftGraphic, ftVarBytes:
  440. if SQLServerType in [ssOracle] then
  441. // Oracle does not accept string literals in blob insert statements
  442. // convert 'DEADBEEF' hex literal to binary:
  443. sql1 := sql1 + ', HEXTORAW(' + QuotedStr(String2Hex(testValues[FType,CountID])) + ') '
  444. else // other dbs have no problems with the original string values
  445. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  446. ftCurrency:
  447. sql1 := sql1 + ',' + testValues[FType,CountID];
  448. ftDate:
  449. // Oracle requires date conversion; otherwise
  450. // ORA-01861: literal does not match format string
  451. if SQLServerType in [ssOracle] then
  452. // ANSI/ISO date literal:
  453. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID])
  454. else
  455. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  456. ftDateTime:
  457. // similar to ftDate handling
  458. if SQLServerType in [ssOracle] then
  459. begin
  460. // Could be a real date+time or only date. Does not consider only time.
  461. if pos(' ',testValues[FType,CountID])>0 then
  462. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr(testValues[FType,CountID])
  463. else
  464. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID]);
  465. end
  466. else
  467. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  468. ftTime:
  469. // similar to ftDate handling
  470. if SQLServerType in [ssOracle] then
  471. // More or less arbitrary default time; there is no time-only data type in Oracle.
  472. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr('0001-01-01 '+testValues[FType,CountID])
  473. else
  474. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID]);
  475. else
  476. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  477. end
  478. else
  479. sql1 := sql1 + ',NULL';
  480. end;
  481. Sql := sql + ')';
  482. Sql1 := sql1+ ')';
  483. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  484. end;
  485. Ftransaction.Commit;
  486. except
  487. on E: Exception do begin
  488. if dblogfilename<>'' then
  489. DoLogEvent(nil,detCustom,'Exception running CreateFieldDataset: '+E.Message);
  490. if Ftransaction.Active then Ftransaction.Rollback;
  491. end;
  492. end;
  493. end;
  494. procedure TSQLDBConnector.DoLogEvent(Sender: TSQLConnection;
  495. EventType: TDBEventType; const Msg: String);
  496. var
  497. Category: string;
  498. begin
  499. case EventType of
  500. detCustom: Category:='Custom';
  501. detPrepare: Category:='Prepare';
  502. detExecute: Category:='Execute';
  503. detFetch: Category:='Fetch';
  504. detCommit: Category:='Commit';
  505. detRollBack: Category:='Rollback';
  506. else Category:='Unknown event. Please fix program code.';
  507. end;
  508. LogMessage(Category,Msg);
  509. end;
  510. procedure TSQLDBConnector.DropNDatasets;
  511. begin
  512. if assigned(FTransaction) then
  513. begin
  514. try
  515. if Ftransaction.Active then Ftransaction.Rollback;
  516. Ftransaction.StartTransaction;
  517. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  518. Ftransaction.Commit;
  519. Except
  520. on E: Exception do begin
  521. if dblogfilename<>'' then
  522. DoLogEvent(nil,detCustom,'Exception running DropNDatasets: '+E.Message);
  523. if Ftransaction.Active then Ftransaction.Rollback
  524. end;
  525. end;
  526. end;
  527. end;
  528. procedure TSQLDBConnector.DropFieldDataset;
  529. begin
  530. if assigned(FTransaction) then
  531. begin
  532. try
  533. if Ftransaction.Active then Ftransaction.Rollback;
  534. Ftransaction.StartTransaction;
  535. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  536. Ftransaction.Commit;
  537. Except
  538. on E: Exception do begin
  539. if dblogfilename<>'' then
  540. DoLogEvent(nil,detCustom,'Exception running DropFieldDataset: '+E.Message);
  541. if Ftransaction.Active then Ftransaction.Rollback
  542. end;
  543. end;
  544. end;
  545. end;
  546. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  547. begin
  548. Result := CreateQuery;
  549. with (Result as TSQLQuery) do
  550. begin
  551. sql.clear;
  552. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  553. UniDirectional:=TestUniDirectional;
  554. end;
  555. end;
  556. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  557. begin
  558. Result := CreateQuery;
  559. with (Result as TSQLQuery) do
  560. begin
  561. sql.clear;
  562. sql.add('SELECT * FROM FPDEV_FIELD');
  563. UniDirectional:=TestUniDirectional;
  564. end;
  565. end;
  566. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  567. begin
  568. // This makes life so much easier, since it avoids the exception if the table already
  569. // exists. And while this exception is in a try..except statement, the debugger
  570. // always shows the exception, which is pretty annoying.
  571. try
  572. case SQLServerType of
  573. ssFirebird:
  574. begin
  575. // This only works with Firebird 2+
  576. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  577. 'then execute statement ''drop table ' + ATableName + ';'';end');
  578. FTransaction.CommitRetaining;
  579. end;
  580. ssMSSQL:
  581. begin
  582. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  583. // which leads to the rollback not referring to the right transaction=>SQL error
  584. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  585. FConnection.ExecuteDirect(
  586. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  587. 'begin '+
  588. 'drop table ' + ATableName + ' '+
  589. 'end');
  590. end;
  591. ssMySQL:
  592. begin
  593. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  594. end;
  595. ssOracle:
  596. begin
  597. FConnection.ExecuteDirect(
  598. 'declare ' +
  599. ' c int; ' +
  600. 'begin ' +
  601. ' select count(*) into c from all_tables where table_name = upper(''' + ATableName + '''); ' +
  602. ' if c = 1 then ' +
  603. ' execute immediate ''drop table ' + ATableName + '''; ' +
  604. ' end if; ' +
  605. 'end; ');
  606. end;
  607. ssSybase:
  608. begin
  609. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  610. // which leads to the rollback not referring to the right transaction=>SQL error
  611. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  612. FConnection.ExecuteDirect(
  613. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  614. 'begin '+
  615. 'drop table ' + ATableName + ' '+
  616. 'end');
  617. end;
  618. end;
  619. except
  620. FTransaction.RollbackRetaining;
  621. end;
  622. end;
  623. procedure TSQLDBConnector.ExecuteDirect(const SQL: string);
  624. begin
  625. Connection.ExecuteDirect(SQL);
  626. end;
  627. procedure TSQLDBConnector.CommitDDL;
  628. begin
  629. // Commits schema definition and manipulation statements;
  630. // Firebird/Interbase need a commit after a DDL statement. Not necessary for the other connections
  631. if SQLServerType in [ssFirebird, ssInterbase] then
  632. Transaction.CommitRetaining;
  633. end;
  634. destructor TSQLDBConnector.Destroy;
  635. begin
  636. if assigned(FTransaction) then
  637. begin
  638. try
  639. if Ftransaction.Active then Ftransaction.Rollback;
  640. Ftransaction.StartTransaction;
  641. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  642. Ftransaction.Commit;
  643. Except
  644. if Ftransaction.Active then Ftransaction.Rollback;
  645. end; // try
  646. end;
  647. inherited Destroy;
  648. FreeAndNil(FQuery);
  649. FreeAndNil(FTransaction);
  650. FreeAndNil(FConnection);
  651. end;
  652. constructor TSQLDBConnector.Create;
  653. begin
  654. FConnection := nil;
  655. CreateFConnection;
  656. FQuery := CreateQuery;
  657. Inherited;
  658. end;
  659. initialization
  660. RegisterClass(TSQLDBConnector);
  661. end.