sqldbtoolsunit.pas 26 KB

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