sqldbtoolsunit.pas 27 KB

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