sqldbtoolsunit.pas 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  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. procedure TryCreateSequence(ASequenceName : String);
  52. procedure TryDropSequence(ASequenceName: String);
  53. destructor Destroy; override;
  54. constructor Create; override;
  55. procedure ExecuteDirect(const SQL: string);
  56. // Issue a commit(retaining) for databases that need it (e.g. in DDL)
  57. procedure CommitDDL;
  58. Procedure FreeTransaction;
  59. property Connection : TSQLConnection read FConnection;
  60. property Transaction : TSQLTransaction read FTransaction;
  61. property Query : TSQLQuery read FQuery;
  62. end;
  63. var SQLConnType : TSQLConnType;
  64. SQLServerType : TSQLServerType;
  65. FieldtypeDefinitions : Array [TFieldType] of String[20];
  66. function IdentifierCase(const s: string): string;
  67. implementation
  68. uses StrUtils;
  69. type
  70. TSQLServerTypesMapItem = record
  71. s: string;
  72. t: TSQLServerType;
  73. end;
  74. const
  75. FieldtypeDefinitionsConst : Array [TFieldType] of String[20] =
  76. (
  77. {ftUnknown} '',
  78. {ftString} 'VARCHAR(10)',
  79. {ftSmallint} 'SMALLINT',
  80. {ftInteger} 'INTEGER',
  81. {ftWord} '',
  82. {ftBoolean} 'BOOLEAN',
  83. {ftFloat} 'DOUBLE PRECISION',
  84. {ftCurrency} '',
  85. {ftBCD} 'DECIMAL(18,4)',
  86. {ftDate} 'DATE',
  87. {ftTime} 'TIME',
  88. {ftDateTime} 'TIMESTAMP',
  89. {ftBytes} '',
  90. {ftVarBytes} '',
  91. {ftAutoInc} '',
  92. {ftBlob} 'BLOB',
  93. {ftMemo} 'BLOB',
  94. {ftGraphic} 'BLOB',
  95. {ftFmtMemo} '',
  96. {ftParadoxOle} '',
  97. {ftDBaseOle} '',
  98. {ftTypedBinary} '',
  99. {ftCursor} '',
  100. {ftFixedChar} 'CHAR(10)',
  101. {ftWideString} '',
  102. {ftLargeint} 'BIGINT',
  103. {ftADT} '',
  104. {ftArray} '',
  105. {ftReference} '',
  106. {ftDataSet} '',
  107. {ftOraBlob} '',
  108. {ftOraClob} '',
  109. {ftVariant} '',
  110. {ftInterface} '',
  111. {ftIDispatch} '',
  112. {ftGuid} '',
  113. {ftTimeStamp} 'TIMESTAMP',
  114. {ftFMTBcd} 'NUMERIC(18,6)',
  115. {ftFixedWideChar} '',
  116. {ftWideMemo} ''
  117. );
  118. // names as returned by ODBC SQLGetInfo(..., SQL_DBMS_NAME, ...) and GetConnectionInfo(citServerType)
  119. SQLServerTypesMap : array [0..7] of TSQLServerTypesMapItem = (
  120. (s: 'Firebird'; t: ssFirebird),
  121. (s: 'Interbase'; t: ssInterbase),
  122. (s: 'Microsoft SQL Server'; t: ssMSSQL),
  123. (s: 'MySQL'; t: ssMySQL),
  124. (s: 'Oracle'; t: ssOracle),
  125. (s: 'PostgreSQL'; t: ssPostgreSQL),
  126. (s: 'SQLite3'; t: ssSQLite),
  127. (s: 'ASE'; t: ssSybase)
  128. );
  129. // fall back mapping (e.g. in case GetConnectionInfo(citServerType) is not implemented)
  130. SQLConnTypeToServerTypeMap : array[TSQLConnType] of TSQLServerType =
  131. (ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssPostgreSQL,ssFirebird,ssUnknown,ssOracle,ssSQLite,ssMSSQL,ssSybase);
  132. function IdentifierCase(const s: string): string;
  133. begin
  134. // format unquoted identifier name as required by SQL servers
  135. case SQLServerType of
  136. ssPostgreSQL: Result := LowerCase(s); // PostgreSQL stores unquoted identifiers in lowercase (incompatible with the SQL standard)
  137. ssInterbase,
  138. ssFirebird : Result := UpperCase(s); // Dialect 1 requires uppercase; dialect 3 is case agnostic
  139. else
  140. Result := s; // mixed case
  141. end;
  142. end;
  143. { TSQLDBConnector }
  144. procedure TSQLDBConnector.CreateFConnection;
  145. var t : TSQLConnType;
  146. i : integer;
  147. s : string;
  148. begin
  149. for t := low(SQLConnTypesNames) to high(SQLConnTypesNames) do
  150. if UpperCase(dbconnectorparams) = SQLConnTypesNames[t] then SQLConnType := t;
  151. case SQLConnType of
  152. MYSQL40: Fconnection := TMySQL40Connection.Create(nil);
  153. MYSQL41: Fconnection := TMySQL41Connection.Create(nil);
  154. MYSQL50: Fconnection := TMySQL50Connection.Create(nil);
  155. MYSQL51: Fconnection := TMySQL51Connection.Create(nil);
  156. MYSQL55: Fconnection := TMySQL55Connection.Create(nil);
  157. MYSQL56: Fconnection := TMySQL56Connection.Create(nil);
  158. MYSQL57: Fconnection := TMySQL57Connection.Create(nil);
  159. SQLITE3: Fconnection := TSQLite3Connection.Create(nil);
  160. POSTGRESQL: Fconnection := TPQConnection.Create(nil);
  161. INTERBASE : Fconnection := TIBConnection.Create(nil);
  162. ODBC: Fconnection := TODBCConnection.Create(nil);
  163. {$IFNDEF Win64}
  164. ORACLE: Fconnection := TOracleConnection.Create(nil);
  165. {$ENDIF Win64}
  166. MSSQL: Fconnection := TMSSQLConnection.Create(nil);
  167. SYBASE: Fconnection := TSybaseConnection.Create(nil);
  168. else writeln('Invalid database type, check if a valid database type for your achitecture was provided in the file ''database.ini''');
  169. end;
  170. FTransaction := TSQLTransaction.Create(nil);
  171. with Fconnection do
  172. begin
  173. Transaction := FTransaction;
  174. DatabaseName := dbname;
  175. UserName := dbuser;
  176. Password := dbpassword;
  177. HostName := dbhostname;
  178. CharSet := dbcharset;
  179. if dblogfilename<>'' then
  180. begin
  181. LogEvents:=[detCustom,detCommit,detExecute,detRollBack];
  182. OnLog:=@DoLogEvent;
  183. end;
  184. if (dbhostname='') and (SQLConnType=interbase) then
  185. begin
  186. // Firebird embedded: create database file if it doesn't yet exist
  187. // Note: pagesize parameter has influence on behavior. We're using
  188. // Firebird default here.
  189. if not(fileexists(dbname)) then
  190. CreateDB; //Create testdb
  191. end;
  192. if length(dbQuoteChars)>1 then
  193. FieldNameQuoteChars:=dbQuoteChars;
  194. Open;
  195. end;
  196. // determine remote SQL Server to which we are connected
  197. s := Fconnection.GetConnectionInfo(citServerType);
  198. if s = '' then
  199. SQLServerType := SQLConnTypeToServerTypeMap[SQLConnType] // if citServerType isn't implemented
  200. else
  201. for i := low(SQLServerTypesMap) to high(SQLServerTypesMap) do
  202. if SQLServerTypesMap[i].s = s then
  203. SQLServerType := SQLServerTypesMap[i].t;
  204. FieldtypeDefinitions := FieldtypeDefinitionsConst;
  205. // Server-specific initialization
  206. case SQLServerType of
  207. ssFirebird:
  208. begin
  209. // Firebird < 3.0 has no support for Boolean data type:
  210. FieldtypeDefinitions[ftBoolean] := '';
  211. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  212. end;
  213. ssInterbase:
  214. begin
  215. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  216. FieldtypeDefinitions[ftLargeInt] := 'NUMERIC(18,0)';
  217. end;
  218. ssMSSQL, ssSybase:
  219. // todo: Sybase: copied over MSSQL; verify correctness
  220. // note: test database should have case-insensitive collation
  221. begin
  222. FieldtypeDefinitions[ftBoolean] := 'BIT';
  223. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  224. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  225. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  226. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  227. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  228. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  229. FieldtypeDefinitions[ftMemo] := 'TEXT';
  230. FieldtypeDefinitions[ftGraphic] := '';
  231. FieldtypeDefinitions[ftGuid] := 'UNIQUEIDENTIFIER';
  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. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  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. if FType in [ftBoolean, ftCurrency] then
  449. sql1 := sql1 + ',' + testValues[FType,CountID]
  450. else if (FType in [ftBlob, ftBytes, ftGraphic, ftVarBytes]) and
  451. (SQLServerType = ssOracle) then
  452. // Oracle does not accept string literals in blob insert statements
  453. // convert 'DEADBEEF' hex literal to binary:
  454. sql1 := sql1 + ', HEXTORAW(' + QuotedStr(String2Hex(testValues[FType,CountID])) + ') '
  455. else if (FType = ftDate) and
  456. (SQLServerType = ssOracle) then
  457. // Oracle requires date conversion; otherwise
  458. // ORA-01861: literal does not match format string
  459. // ANSI/ISO date literal:
  460. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID])
  461. else if (FType = ftDateTime) and
  462. (SQLServerType = ssOracle) then begin
  463. // similar to ftDate handling
  464. // Could be a real date+time or only date. Does not consider only time.
  465. if pos(' ',testValues[FType,CountID])>0 then
  466. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr(testValues[FType,CountID])
  467. else
  468. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID]);
  469. end
  470. else if (FType = ftTime) and
  471. (SQLServerType = ssOracle) then
  472. // similar to ftDate handling
  473. // More or less arbitrary default time; there is no time-only data type in Oracle.
  474. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr('0001-01-01 '+testValues[FType,CountID])
  475. else
  476. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  477. else
  478. sql1 := sql1 + ',NULL';
  479. end;
  480. Sql := sql + ')';
  481. Sql1 := sql1+ ')';
  482. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  483. end;
  484. Ftransaction.Commit;
  485. except
  486. on E: Exception do begin
  487. if dblogfilename<>'' then
  488. DoLogEvent(nil,detCustom,'Exception running CreateFieldDataset: '+E.Message);
  489. if Ftransaction.Active then Ftransaction.Rollback;
  490. end;
  491. end;
  492. end;
  493. procedure TSQLDBConnector.DoLogEvent(Sender: TSQLConnection;
  494. EventType: TDBEventType; Const Msg: String);
  495. var
  496. Category: string;
  497. begin
  498. case EventType of
  499. detCustom: Category:='Custom';
  500. detPrepare: Category:='Prepare';
  501. detExecute: Category:='Execute';
  502. detFetch: Category:='Fetch';
  503. detCommit: Category:='Commit';
  504. detRollBack: Category:='Rollback';
  505. else Category:='Unknown event. Please fix program code.';
  506. end;
  507. LogMessage(Category,Msg);
  508. end;
  509. procedure TSQLDBConnector.DropNDatasets;
  510. begin
  511. if assigned(FTransaction) then
  512. begin
  513. try
  514. if Ftransaction.Active then Ftransaction.Rollback;
  515. Ftransaction.StartTransaction;
  516. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  517. Ftransaction.Commit;
  518. Except
  519. on E: Exception do begin
  520. if dblogfilename<>'' then
  521. DoLogEvent(nil,detCustom,'Exception running DropNDatasets: '+E.Message);
  522. if Ftransaction.Active then Ftransaction.Rollback
  523. end;
  524. end;
  525. end;
  526. end;
  527. procedure TSQLDBConnector.DropFieldDataset;
  528. begin
  529. if assigned(FTransaction) then
  530. begin
  531. try
  532. if Ftransaction.Active then Ftransaction.Rollback;
  533. Ftransaction.StartTransaction;
  534. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  535. Ftransaction.Commit;
  536. Except
  537. on E: Exception do begin
  538. if dblogfilename<>'' then
  539. DoLogEvent(nil,detCustom,'Exception running DropFieldDataset: '+E.Message);
  540. if Ftransaction.Active then Ftransaction.Rollback
  541. end;
  542. end;
  543. end;
  544. end;
  545. Function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  546. begin
  547. Result := CreateQuery;
  548. with (Result as TSQLQuery) do
  549. begin
  550. sql.clear;
  551. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1)+' ORDER BY ID');
  552. UniDirectional:=TestUniDirectional;
  553. end;
  554. end;
  555. Function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  556. begin
  557. Result := CreateQuery;
  558. with (Result as TSQLQuery) do
  559. begin
  560. sql.clear;
  561. sql.add('SELECT * FROM FPDEV_FIELD');
  562. UniDirectional:=TestUniDirectional;
  563. end;
  564. end;
  565. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  566. begin
  567. // This makes life so much easier, since it avoids the exception if the table already
  568. // exists. And while this exception is in a try..except statement, the debugger
  569. // always shows the exception, which is pretty annoying.
  570. try
  571. case SQLServerType of
  572. ssFirebird:
  573. begin
  574. // This only works with Firebird 2+
  575. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where upper(rdb$relation_name)=''' + UpperCase(ATableName) + ''')) '+
  576. 'then execute statement ''drop table ' + ATableName + ';'';end');
  577. FTransaction.CommitRetaining;
  578. end;
  579. ssMSSQL:
  580. begin
  581. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  582. // which leads to the rollback not referring to the right transaction=>SQL error
  583. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  584. FConnection.ExecuteDirect(
  585. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''')'+
  586. ' drop table ' + ATableName );
  587. end;
  588. ssMySQL:
  589. begin
  590. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  591. end;
  592. ssPostgreSQL,
  593. ssSQLite:
  594. begin
  595. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  596. FTransaction.CommitRetaining;
  597. end;
  598. ssOracle:
  599. begin
  600. FConnection.ExecuteDirect(
  601. 'declare ' +
  602. ' c int; ' +
  603. 'begin ' +
  604. ' select count(*) into c from all_tables where table_name = upper(''' + ATableName + '''); ' +
  605. ' if c = 1 then ' +
  606. ' execute immediate ''drop table ' + ATableName + '''; ' +
  607. ' end if; ' +
  608. 'end; ');
  609. end;
  610. ssSybase:
  611. begin
  612. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  613. // which leads to the rollback not referring to the right transaction=>SQL error
  614. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  615. FConnection.ExecuteDirect(
  616. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  617. 'begin '+
  618. 'drop table ' + ATableName + ' '+
  619. 'end');
  620. end;
  621. end;
  622. except
  623. FTransaction.RollbackRetaining;
  624. end;
  625. end;
  626. procedure TSQLDBConnector.TryDropSequence(ASequenceName: String);
  627. var
  628. NoSeq : Boolean;
  629. begin
  630. NoSeq:=False;
  631. try
  632. case SQLServerType of
  633. ssInterbase,
  634. ssFirebird: FConnection.ExecuteDirect('DROP GENERATOR '+ASequenceName);
  635. ssOracle,
  636. ssPostgreSQL,
  637. ssSybase,
  638. ssMSSQL : FConnection.ExecuteDirect('DROP SEQUENCE '+ASequenceName+' START WITH 1 INCREMENT BY 1');
  639. ssSQLite : FConnection.ExecuteDirect('delete from sqlite_sequence where (name='''+ASequenceName+''')');
  640. else
  641. NoSeq:=True;
  642. end;
  643. except
  644. FTransaction.RollbackRetaining;
  645. end;
  646. if NoSeq then
  647. Raise EDatabaseError.Create('Engine does not support sequences');
  648. end;
  649. procedure TSQLDBConnector.TryCreateSequence(ASequenceName: String);
  650. var
  651. NoSeq : Boolean;
  652. begin
  653. NoSeq:=False;
  654. case SQLServerType of
  655. ssInterbase,
  656. ssFirebird: FConnection.ExecuteDirect('CREATE GENERATOR '+ASequenceName);
  657. ssOracle,
  658. ssPostgreSQL,
  659. ssSybase,
  660. ssMSSQL : FConnection.ExecuteDirect('CREATE SEQUENCE '+ASequenceName+' START WITH 1 INCREMENT BY 1');
  661. ssSQLite : FConnection.ExecuteDirect('insert into sqlite_sequence (name,seq) values ('''+ASequenceName+''',1)');
  662. else
  663. Raise EDatabaseError.Create('Engine does not support sequences');
  664. end;
  665. end;
  666. procedure TSQLDBConnector.ExecuteDirect(const SQL: string);
  667. begin
  668. Connection.ExecuteDirect(SQL);
  669. end;
  670. procedure TSQLDBConnector.CommitDDL;
  671. begin
  672. // Commits schema definition and manipulation statements;
  673. // Firebird/Interbase need a commit after a DDL statement. Not necessary for the other connections
  674. if SQLServerType in [ssFirebird, ssInterbase] then
  675. Transaction.CommitRetaining;
  676. end;
  677. Procedure TSQLDBConnector.FreeTransaction;
  678. begin
  679. FreeAndNil(FTransaction);
  680. end;
  681. destructor TSQLDBConnector.Destroy;
  682. begin
  683. FreeAndNil(FQuery);
  684. if assigned(FTransaction) then
  685. begin
  686. try
  687. if not (stoUseImplicit in Transaction.Options) then
  688. begin
  689. if Ftransaction.Active then
  690. Ftransaction.Rollback;
  691. Ftransaction.StartTransaction;
  692. end;
  693. TryDropIfExist('FPDEV2');
  694. if not (stoUseImplicit in Transaction.Options) then
  695. Ftransaction.Commit;
  696. Except
  697. if Ftransaction.Active and not (stoUseImplicit in Transaction.Options) then
  698. Ftransaction.Rollback;
  699. end; // try
  700. end;
  701. FreeTransaction;
  702. FreeAndNil(FConnection);
  703. inherited Destroy;
  704. end;
  705. constructor TSQLDBConnector.Create;
  706. begin
  707. FConnection := nil;
  708. CreateFConnection;
  709. FQuery := CreateQuery;
  710. Inherited;
  711. end;
  712. initialization
  713. RegisterClass(TSQLDBConnector);
  714. end.