2
0

sqldbtoolsunit.pas 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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. begin
  220. FieldtypeDefinitions[ftBoolean] := 'BIT';
  221. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  222. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  223. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  224. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  225. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  226. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  227. FieldtypeDefinitions[ftMemo] := 'TEXT';
  228. FieldtypeDefinitions[ftGraphic] := '';
  229. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  230. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  231. //FieldtypeDefinitions[ftWideMemo] := 'NTEXT'; // Sybase has UNITEXT?
  232. // Proper blob support:
  233. FConnection.ExecuteDirect('SET TEXTSIZE 2147483647');
  234. if SQLServerType=ssMSSQL then
  235. begin
  236. // When running CREATE TABLE statements, allow NULLs by default - without
  237. // having to specify NULL all the time:
  238. // http://msdn.microsoft.com/en-us/library/ms174979.aspx
  239. //
  240. // Padding character fields is expected by ANSI and sqldb, as well as
  241. // recommended by Microsoft:
  242. // http://msdn.microsoft.com/en-us/library/ms187403.aspx
  243. FConnection.ExecuteDirect('SET ANSI_NULL_DFLT_ON ON; SET ANSI_PADDING ON; SET ANSI_WARNINGS OFF');
  244. end;
  245. if SQLServerType=ssSybase then
  246. begin
  247. // Evaluate NULL expressions according to ANSI SQL:
  248. // http://infocenter.sybase.com/archive/index.jsp?topic=/com.sybase.help.ase_15.0.commands/html/commands/commands85.htm
  249. FConnection.ExecuteDirect('SET ANSINULL ON');
  250. { Tests require these database options set
  251. 1) with ddl in tran; e.g.
  252. use master
  253. go
  254. sp_dboption pubs3, 'ddl in tran', true
  255. go
  256. Avoid errors like
  257. The 'CREATE TABLE' command is not allowed within a multi-statement transaction in the 'test' database.
  258. 2) allow nulls by default, e.g.
  259. use master
  260. go
  261. sp_dboption pubs3, 'allow nulls by default', true
  262. go
  263. }
  264. end;
  265. FTransaction.Commit;
  266. end;
  267. ssMySQL:
  268. begin
  269. FieldtypeDefinitions[ftWord] := 'SMALLINT UNSIGNED';
  270. // MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  271. FieldtypeDefinitions[ftBoolean] := '';
  272. // Use 'DATETIME' for datetime fields instead of timestamp, because
  273. // mysql's timestamps are only valid in the range 1970-2038.
  274. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  275. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  276. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  277. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  278. FieldtypeDefinitions[ftMemo] := 'TEXT';
  279. // Add into my.ini: sql-mode="...,PAD_CHAR_TO_FULL_LENGTH,ANSI_QUOTES" or set it explicitly by:
  280. // PAD_CHAR_TO_FULL_LENGTH to avoid trimming trailing spaces contrary to SQL standard (MySQL 5.1.20+)
  281. FConnection.ExecuteDirect('SET SESSION sql_mode=''STRICT_ALL_TABLES,PAD_CHAR_TO_FULL_LENGTH,ANSI_QUOTES''');
  282. FTransaction.Commit;
  283. end;
  284. ssOracle:
  285. begin
  286. FieldtypeDefinitions[ftBoolean] := '';
  287. // At least Oracle 10, 11 do not support a BIGINT field:
  288. FieldtypeDefinitions[ftLargeInt] := 'NUMBER(19,0)';
  289. FieldtypeDefinitions[ftTime] := 'TIMESTAMP';
  290. FieldtypeDefinitions[ftMemo] := 'CLOB';
  291. FieldtypeDefinitions[ftWideString] := 'NVARCHAR2(10)';
  292. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  293. FieldtypeDefinitions[ftWideMemo] := 'NCLOB';
  294. end;
  295. ssPostgreSQL:
  296. begin
  297. FieldtypeDefinitions[ftCurrency] := 'MONEY'; // ODBC?!
  298. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  299. FieldtypeDefinitions[ftMemo] := 'TEXT';
  300. FieldtypeDefinitions[ftGraphic] := '';
  301. FieldtypeDefinitions[ftGuid] := 'UUID';
  302. end;
  303. ssSQLite:
  304. begin
  305. // SQLite stores all values with decimal point as 8 byte (double) IEEE floating point numbers
  306. // (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)
  307. FieldtypeDefinitions[ftWord] := 'WORD';
  308. FieldtypeDefinitions[ftCurrency] := 'CURRENCY';
  309. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  310. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  311. FieldtypeDefinitions[ftMemo] := 'CLOB'; //or TEXT SQLite supports both, but CLOB is sql standard (TEXT not)
  312. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  313. FieldtypeDefinitions[ftFixedWideChar] := 'NCHAR(10)';
  314. FieldtypeDefinitions[ftWideMemo] := 'NCLOB';
  315. end;
  316. end;
  317. if SQLConnType in [mysql40,mysql41] then
  318. begin
  319. // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar
  320. // fields on insertion. So to test properly, we have to do the same
  321. for i := 0 to testValuesCount-1 do
  322. testStringValues[i] := TrimRight(testStringValues[i]);
  323. end;
  324. if SQLServerType in [ssMSSQL, ssSQLite, ssSybase] then
  325. // Some DB's do not support sql compliant boolean data type.
  326. for i := 0 to testValuesCount-1 do
  327. testValues[ftBoolean, i] := BoolToStr(testBooleanValues[i], '1', '0');
  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. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  356. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  357. // Here we assume, that locale on client side is same as locale on server
  358. if SQLServerType in [ssPostgreSQL] then
  359. for i := 0 to testValuesCount-1 do
  360. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  361. // SQLite does not support fixed length CHAR datatype
  362. if SQLServerType in [ssSQLite] then
  363. for i := 0 to testValuesCount-1 do
  364. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  365. end;
  366. Function TSQLDBConnector.CreateQuery: TSQLQuery;
  367. begin
  368. Result := TSQLQuery.create(nil);
  369. with Result do
  370. begin
  371. database := Fconnection;
  372. transaction := Ftransaction;
  373. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  374. end;
  375. end;
  376. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  377. begin
  378. FUniDirectional:=avalue;
  379. FQuery.UniDirectional:=AValue;
  380. end;
  381. function TSQLDBConnector.GetTestUniDirectional: boolean;
  382. begin
  383. result := FUniDirectional;
  384. end;
  385. procedure TSQLDBConnector.CreateNDatasets;
  386. var CountID : Integer;
  387. begin
  388. try
  389. Ftransaction.StartTransaction;
  390. TryDropIfExist('FPDEV');
  391. Fconnection.ExecuteDirect('create table FPDEV (' +
  392. ' ID INT NOT NULL, ' +
  393. ' NAME VARCHAR(50), ' +
  394. ' PRIMARY KEY (ID) ' +
  395. ')');
  396. FTransaction.CommitRetaining;
  397. for countID := 1 to MaxDataSet do
  398. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME) ' +
  399. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  400. Ftransaction.Commit;
  401. except
  402. on E: Exception do begin
  403. if dblogfilename<>'' then
  404. DoLogEvent(nil,detCustom,'Exception running CreateNDatasets: '+E.Message);
  405. if Ftransaction.Active then
  406. Ftransaction.Rollback
  407. end;
  408. end;
  409. end;
  410. procedure TSQLDBConnector.CreateFieldDataset;
  411. var
  412. CountID : Integer;
  413. FType : TFieldType;
  414. Sql,sql1: String;
  415. function String2Hex(Source: string): string;
  416. // Converts ASCII codes into hex
  417. var
  418. i: integer;
  419. begin
  420. result := '';
  421. for i := 1 to length(Source) do
  422. result := result + inttohex(ord(Source[i]),2);
  423. end;
  424. begin
  425. try
  426. Ftransaction.StartTransaction;
  427. TryDropIfExist('FPDEV_FIELD');
  428. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  429. for FType := low(TFieldType)to high(TFieldType) do
  430. if FieldtypeDefinitions[FType]<>'' then
  431. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +
  432. FieldtypeDefinitions[FType] + ',';
  433. Sql := Sql + 'PRIMARY KEY (ID))';
  434. FConnection.ExecuteDirect(Sql);
  435. FTransaction.CommitRetaining;
  436. for countID := 0 to testValuesCount-1 do
  437. begin
  438. Sql := 'insert into FPDEV_FIELD (ID';
  439. Sql1 := 'values ('+IntToStr(countID);
  440. for FType := low(TFieldType)to high(TFieldType) do
  441. if FieldtypeDefinitions[FType]<>'' then
  442. begin
  443. sql := sql + ',F' + Fieldtypenames[FType];
  444. if testValues[FType,CountID] <> '' then
  445. if FType in [ftBoolean, ftCurrency] then
  446. sql1 := sql1 + ',' + testValues[FType,CountID]
  447. else if (FType in [ftBlob, ftBytes, ftGraphic, ftVarBytes]) and
  448. (SQLServerType = ssOracle) then
  449. // Oracle does not accept string literals in blob insert statements
  450. // convert 'DEADBEEF' hex literal to binary:
  451. sql1 := sql1 + ', HEXTORAW(' + QuotedStr(String2Hex(testValues[FType,CountID])) + ') '
  452. else if (FType = ftDate) and
  453. (SQLServerType = ssOracle) then
  454. // Oracle requires date conversion; otherwise
  455. // ORA-01861: literal does not match format string
  456. // ANSI/ISO date literal:
  457. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID])
  458. else if (FType = ftDateTime) and
  459. (SQLServerType = ssOracle) then begin
  460. // similar to ftDate handling
  461. // Could be a real date+time or only date. Does not consider only time.
  462. if pos(' ',testValues[FType,CountID])>0 then
  463. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr(testValues[FType,CountID])
  464. else
  465. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID]);
  466. end
  467. else if (FType = ftTime) and
  468. (SQLServerType = ssOracle) then
  469. // similar to ftDate handling
  470. // More or less arbitrary default time; there is no time-only data type in Oracle.
  471. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr('0001-01-01 '+testValues[FType,CountID])
  472. else
  473. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  474. else
  475. sql1 := sql1 + ',NULL';
  476. end;
  477. Sql := sql + ')';
  478. Sql1 := sql1+ ')';
  479. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  480. end;
  481. Ftransaction.Commit;
  482. except
  483. on E: Exception do begin
  484. if dblogfilename<>'' then
  485. DoLogEvent(nil,detCustom,'Exception running CreateFieldDataset: '+E.Message);
  486. if Ftransaction.Active then Ftransaction.Rollback;
  487. end;
  488. end;
  489. end;
  490. procedure TSQLDBConnector.DoLogEvent(Sender: TSQLConnection;
  491. EventType: TDBEventType; Const Msg: String);
  492. var
  493. Category: string;
  494. begin
  495. case EventType of
  496. detCustom: Category:='Custom';
  497. detPrepare: Category:='Prepare';
  498. detExecute: Category:='Execute';
  499. detFetch: Category:='Fetch';
  500. detCommit: Category:='Commit';
  501. detRollBack: Category:='Rollback';
  502. else Category:='Unknown event. Please fix program code.';
  503. end;
  504. LogMessage(Category,Msg);
  505. end;
  506. procedure TSQLDBConnector.DropNDatasets;
  507. begin
  508. if assigned(FTransaction) then
  509. begin
  510. try
  511. if Ftransaction.Active then Ftransaction.Rollback;
  512. Ftransaction.StartTransaction;
  513. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  514. Ftransaction.Commit;
  515. Except
  516. on E: Exception do begin
  517. if dblogfilename<>'' then
  518. DoLogEvent(nil,detCustom,'Exception running DropNDatasets: '+E.Message);
  519. if Ftransaction.Active then Ftransaction.Rollback
  520. end;
  521. end;
  522. end;
  523. end;
  524. procedure TSQLDBConnector.DropFieldDataset;
  525. begin
  526. if assigned(FTransaction) then
  527. begin
  528. try
  529. if Ftransaction.Active then Ftransaction.Rollback;
  530. Ftransaction.StartTransaction;
  531. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  532. Ftransaction.Commit;
  533. Except
  534. on E: Exception do begin
  535. if dblogfilename<>'' then
  536. DoLogEvent(nil,detCustom,'Exception running DropFieldDataset: '+E.Message);
  537. if Ftransaction.Active then Ftransaction.Rollback
  538. end;
  539. end;
  540. end;
  541. end;
  542. Function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  543. begin
  544. Result := CreateQuery;
  545. with (Result as TSQLQuery) do
  546. begin
  547. sql.clear;
  548. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1)+' ORDER BY ID');
  549. UniDirectional:=TestUniDirectional;
  550. end;
  551. end;
  552. Function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  553. begin
  554. Result := CreateQuery;
  555. with (Result as TSQLQuery) do
  556. begin
  557. sql.clear;
  558. sql.add('SELECT * FROM FPDEV_FIELD');
  559. UniDirectional:=TestUniDirectional;
  560. end;
  561. end;
  562. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  563. begin
  564. // This makes life so much easier, since it avoids the exception if the table already
  565. // exists. And while this exception is in a try..except statement, the debugger
  566. // always shows the exception, which is pretty annoying.
  567. try
  568. case SQLServerType of
  569. ssFirebird:
  570. begin
  571. // This only works with Firebird 2+
  572. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where upper(rdb$relation_name)=''' + UpperCase(ATableName) + ''')) '+
  573. 'then execute statement ''drop table ' + ATableName + ';'';end');
  574. FTransaction.CommitRetaining;
  575. end;
  576. ssMSSQL:
  577. begin
  578. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  579. // which leads to the rollback not referring to the right transaction=>SQL error
  580. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  581. FConnection.ExecuteDirect(
  582. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''')'+
  583. ' drop table ' + ATableName );
  584. end;
  585. ssMySQL:
  586. begin
  587. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  588. end;
  589. ssPostgreSQL,
  590. ssSQLite:
  591. begin
  592. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  593. FTransaction.CommitRetaining;
  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. Procedure TSQLDBConnector.FreeTransaction;
  635. begin
  636. FreeAndNil(FTransaction);
  637. end;
  638. destructor TSQLDBConnector.Destroy;
  639. begin
  640. FreeAndNil(FQuery);
  641. if assigned(FTransaction) then
  642. begin
  643. try
  644. if not (stoUseImplicit in Transaction.Options) then
  645. begin
  646. if Ftransaction.Active then
  647. Ftransaction.Rollback;
  648. Ftransaction.StartTransaction;
  649. end;
  650. TryDropIfExist('FPDEV2');
  651. if not (stoUseImplicit in Transaction.Options) then
  652. Ftransaction.Commit;
  653. Except
  654. if Ftransaction.Active and not (stoUseImplicit in Transaction.Options) then
  655. Ftransaction.Rollback;
  656. end; // try
  657. end;
  658. FreeTransaction;
  659. FreeAndNil(FConnection);
  660. inherited Destroy;
  661. end;
  662. constructor TSQLDBConnector.Create;
  663. begin
  664. FConnection := nil;
  665. CreateFConnection;
  666. FQuery := CreateQuery;
  667. Inherited;
  668. end;
  669. initialization
  670. RegisterClass(TSQLDBConnector);
  671. end.