sqldbtoolsunit.pas 26 KB

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