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