sqldbtoolsunit.pas 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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, mysql80conn
  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,mysql80,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,mysql80];
  23. SQLConnTypesNames : Array [TSQLConnType] of String[19] =
  24. ('MYSQL40','MYSQL41','MYSQL50','MYSQL51','MYSQL55','MYSQL56','MYSQL57','MYSQL80','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. MYSQL80: Fconnection := TMySQL80Connection.Create(nil);
  160. SQLITE3: Fconnection := TSQLite3Connection.Create(nil);
  161. POSTGRESQL: Fconnection := TPQConnection.Create(nil);
  162. INTERBASE : Fconnection := TIBConnection.Create(nil);
  163. ODBC: Fconnection := TODBCConnection.Create(nil);
  164. {$IFNDEF Win64}
  165. ORACLE: Fconnection := TOracleConnection.Create(nil);
  166. {$ENDIF Win64}
  167. MSSQL: Fconnection := TMSSQLConnection.Create(nil);
  168. SYBASE: Fconnection := TSybaseConnection.Create(nil);
  169. else writeln('Invalid database type, check if a valid database type for your achitecture was provided in the file ''database.ini''');
  170. end;
  171. FTransaction := TSQLTransaction.Create(nil);
  172. with Fconnection do
  173. begin
  174. Transaction := FTransaction;
  175. DatabaseName := dbname;
  176. UserName := dbuser;
  177. Password := dbpassword;
  178. HostName := dbhostname;
  179. CharSet := dbcharset;
  180. if dblogfilename<>'' then
  181. begin
  182. LogEvents:=[detCustom,detCommit,detExecute,detRollBack];
  183. OnLog:=@DoLogEvent;
  184. end;
  185. if (dbhostname='') and (SQLConnType=interbase) then
  186. begin
  187. // Firebird embedded: create database file if it doesn't yet exist
  188. // Note: pagesize parameter has influence on behavior. We're using
  189. // Firebird default here.
  190. if not(fileexists(dbname)) then
  191. CreateDB; //Create testdb
  192. end;
  193. if length(dbQuoteChars)>1 then
  194. FieldNameQuoteChars:=dbQuoteChars;
  195. Open;
  196. end;
  197. // determine remote SQL Server to which we are connected
  198. s := Fconnection.GetConnectionInfo(citServerType);
  199. if s = '' then
  200. SQLServerType := SQLConnTypeToServerTypeMap[SQLConnType] // if citServerType isn't implemented
  201. else
  202. for i := low(SQLServerTypesMap) to high(SQLServerTypesMap) do
  203. if SQLServerTypesMap[i].s = s then
  204. SQLServerType := SQLServerTypesMap[i].t;
  205. FieldtypeDefinitions := FieldtypeDefinitionsConst;
  206. // Server-specific initialization
  207. case SQLServerType of
  208. ssFirebird:
  209. begin
  210. // Firebird < 3.0 has no support for Boolean data type:
  211. FieldtypeDefinitions[ftBoolean] := '';
  212. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  213. end;
  214. ssInterbase:
  215. begin
  216. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  217. FieldtypeDefinitions[ftLargeInt] := 'NUMERIC(18,0)';
  218. end;
  219. ssMSSQL, ssSybase:
  220. // todo: Sybase: copied over MSSQL; verify correctness
  221. // note: test database should have case-insensitive collation
  222. begin
  223. FieldtypeDefinitions[ftBoolean] := 'BIT';
  224. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  225. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  226. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  227. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  228. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  229. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  230. FieldtypeDefinitions[ftMemo] := 'TEXT';
  231. FieldtypeDefinitions[ftGraphic] := '';
  232. FieldtypeDefinitions[ftGuid] := 'UNIQUEIDENTIFIER';
  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 [ssMSSQL, ssSQLite, ssSybase] then
  329. // Some DB's do not support sql compliant boolean data type.
  330. for i := 0 to testValuesCount-1 do
  331. testValues[ftBoolean, i] := BoolToStr(testBooleanValues[i], '1', '0');
  332. if SQLServerType in [ssMySQL] then
  333. begin
  334. // Some DB's do not support milliseconds in datetime and time fields.
  335. for i := 0 to testValuesCount-1 do
  336. begin
  337. testTimeValues[i] := copy(testTimeValues[i],1,8)+'.000';
  338. testValues[ftTime,i] := copy(testTimeValues[i],1,8)+'.000';
  339. if length(testValues[ftDateTime,i]) > 19 then
  340. testValues[ftDateTime,i] := copy(testValues[ftDateTime,i],1,19)+'.000';
  341. end;
  342. end;
  343. if SQLServerType in [ssFirebird, ssInterbase, ssMSSQL, ssOracle, ssPostgreSQL, ssSybase] then
  344. begin
  345. // Some db's do not support times > 24:00:00
  346. testTimeValues[3]:='13:25:15.000';
  347. testValues[ftTime,3]:='13:25:15.000';
  348. if SQLServerType in [ssFirebird, ssInterbase, ssMSSQL, ssOracle] then
  349. begin
  350. // Firebird, Oracle, MS SQL Server do not support time = 24:00:00
  351. // MS SQL Server "datetime" supports only time up to 23:59:59.997
  352. testTimeValues[2]:='23:59:59.997';
  353. testValues[ftTime,2]:='23:59:59.997';
  354. end;
  355. end;
  356. if SQLServerType in [ssMSSQL, ssSybase] then
  357. // Some DB's do not support datetime values before 1753-01-01
  358. for i := 18 to testValuesCount-1 do
  359. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  360. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  361. // Here we assume, that locale on client side is same as locale on server
  362. if SQLServerType in [ssPostgreSQL] then
  363. for i := 0 to testValuesCount-1 do
  364. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  365. // SQLite does not support fixed length CHAR datatype
  366. if SQLServerType in [ssSQLite] then
  367. for i := 0 to testValuesCount-1 do
  368. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  369. end;
  370. Function TSQLDBConnector.CreateQuery: TSQLQuery;
  371. begin
  372. Result := TSQLQuery.create(nil);
  373. with Result do
  374. begin
  375. database := Fconnection;
  376. transaction := Ftransaction;
  377. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  378. end;
  379. end;
  380. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  381. begin
  382. FUniDirectional:=avalue;
  383. FQuery.UniDirectional:=AValue;
  384. end;
  385. function TSQLDBConnector.GetTestUniDirectional: boolean;
  386. begin
  387. result := FUniDirectional;
  388. end;
  389. procedure TSQLDBConnector.CreateNDatasets;
  390. var CountID : Integer;
  391. begin
  392. try
  393. Ftransaction.StartTransaction;
  394. TryDropIfExist('FPDEV');
  395. Fconnection.ExecuteDirect('create table FPDEV (' +
  396. ' ID INT NOT NULL, ' +
  397. ' NAME VARCHAR(50), ' +
  398. ' PRIMARY KEY (ID) ' +
  399. ')');
  400. FTransaction.CommitRetaining;
  401. for countID := 1 to MaxDataSet do
  402. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME) ' +
  403. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  404. Ftransaction.Commit;
  405. except
  406. on E: Exception do begin
  407. if dblogfilename<>'' then
  408. DoLogEvent(nil,detCustom,'Exception running CreateNDatasets: '+E.Message);
  409. if Ftransaction.Active then
  410. Ftransaction.Rollback
  411. end;
  412. end;
  413. end;
  414. procedure TSQLDBConnector.CreateFieldDataset;
  415. var
  416. CountID : Integer;
  417. FType : TFieldType;
  418. Sql,sql1: String;
  419. function String2Hex(Source: string): string;
  420. // Converts ASCII codes into hex
  421. var
  422. i: integer;
  423. begin
  424. result := '';
  425. for i := 1 to length(Source) do
  426. result := result + inttohex(ord(Source[i]),2);
  427. end;
  428. begin
  429. try
  430. Ftransaction.StartTransaction;
  431. TryDropIfExist('FPDEV_FIELD');
  432. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  433. for FType := low(TFieldType)to high(TFieldType) do
  434. if FieldtypeDefinitions[FType]<>'' then
  435. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +
  436. FieldtypeDefinitions[FType] + ',';
  437. Sql := Sql + 'PRIMARY KEY (ID))';
  438. FConnection.ExecuteDirect(Sql);
  439. FTransaction.CommitRetaining;
  440. for countID := 0 to testValuesCount-1 do
  441. begin
  442. Sql := 'insert into FPDEV_FIELD (ID';
  443. Sql1 := 'values ('+IntToStr(countID);
  444. for FType := low(TFieldType)to high(TFieldType) do
  445. if FieldtypeDefinitions[FType]<>'' then
  446. begin
  447. sql := sql + ',F' + Fieldtypenames[FType];
  448. if testValues[FType,CountID] <> '' then
  449. if FType in [ftBoolean, ftCurrency] then
  450. sql1 := sql1 + ',' + testValues[FType,CountID]
  451. else if (FType in [ftBlob, ftBytes, ftGraphic, ftVarBytes]) and
  452. (SQLServerType = ssOracle) then
  453. // Oracle does not accept string literals in blob insert statements
  454. // convert 'DEADBEEF' hex literal to binary:
  455. sql1 := sql1 + ', HEXTORAW(' + QuotedStr(String2Hex(testValues[FType,CountID])) + ') '
  456. else if (FType = ftDate) and
  457. (SQLServerType = ssOracle) then
  458. // Oracle requires date conversion; otherwise
  459. // ORA-01861: literal does not match format string
  460. // ANSI/ISO date literal:
  461. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID])
  462. else if (FType = ftDateTime) and
  463. (SQLServerType = ssOracle) then begin
  464. // similar to ftDate handling
  465. // Could be a real date+time or only date. Does not consider only time.
  466. if pos(' ',testValues[FType,CountID])>0 then
  467. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr(testValues[FType,CountID])
  468. else
  469. sql1 := sql1 + ', DATE ' + QuotedStr(testValues[FType,CountID]);
  470. end
  471. else if (FType = ftTime) and
  472. (SQLServerType = ssOracle) then
  473. // similar to ftDate handling
  474. // More or less arbitrary default time; there is no time-only data type in Oracle.
  475. sql1 := sql1 + ', TIMESTAMP ' + QuotedStr('0001-01-01 '+testValues[FType,CountID])
  476. else
  477. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  478. else
  479. sql1 := sql1 + ',NULL';
  480. end;
  481. Sql := sql + ')';
  482. Sql1 := sql1+ ')';
  483. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  484. end;
  485. Ftransaction.Commit;
  486. except
  487. on E: Exception do begin
  488. if dblogfilename<>'' then
  489. DoLogEvent(nil,detCustom,'Exception running CreateFieldDataset: '+E.Message);
  490. if Ftransaction.Active then Ftransaction.Rollback;
  491. end;
  492. end;
  493. end;
  494. procedure TSQLDBConnector.DoLogEvent(Sender: TSQLConnection;
  495. EventType: TDBEventType; Const Msg: String);
  496. var
  497. Category: string;
  498. begin
  499. case EventType of
  500. detCustom: Category:='Custom';
  501. detPrepare: Category:='Prepare';
  502. detExecute: Category:='Execute';
  503. detFetch: Category:='Fetch';
  504. detCommit: Category:='Commit';
  505. detRollBack: Category:='Rollback';
  506. else Category:='Unknown event. Please fix program code.';
  507. end;
  508. LogMessage(Category,Msg);
  509. end;
  510. procedure TSQLDBConnector.DropNDatasets;
  511. begin
  512. if assigned(FTransaction) then
  513. begin
  514. try
  515. if Ftransaction.Active then Ftransaction.Rollback;
  516. Ftransaction.StartTransaction;
  517. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  518. Ftransaction.Commit;
  519. Except
  520. on E: Exception do begin
  521. if dblogfilename<>'' then
  522. DoLogEvent(nil,detCustom,'Exception running DropNDatasets: '+E.Message);
  523. if Ftransaction.Active then Ftransaction.Rollback
  524. end;
  525. end;
  526. end;
  527. end;
  528. procedure TSQLDBConnector.DropFieldDataset;
  529. begin
  530. if assigned(FTransaction) then
  531. begin
  532. try
  533. if Ftransaction.Active then Ftransaction.Rollback;
  534. Ftransaction.StartTransaction;
  535. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  536. Ftransaction.Commit;
  537. Except
  538. on E: Exception do begin
  539. if dblogfilename<>'' then
  540. DoLogEvent(nil,detCustom,'Exception running DropFieldDataset: '+E.Message);
  541. if Ftransaction.Active then Ftransaction.Rollback
  542. end;
  543. end;
  544. end;
  545. end;
  546. Function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  547. begin
  548. Result := CreateQuery;
  549. with (Result as TSQLQuery) do
  550. begin
  551. sql.clear;
  552. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1)+' ORDER BY ID');
  553. UniDirectional:=TestUniDirectional;
  554. end;
  555. end;
  556. Function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  557. begin
  558. Result := CreateQuery;
  559. with (Result as TSQLQuery) do
  560. begin
  561. sql.clear;
  562. sql.add('SELECT * FROM FPDEV_FIELD');
  563. UniDirectional:=TestUniDirectional;
  564. end;
  565. end;
  566. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  567. begin
  568. // This makes life so much easier, since it avoids the exception if the table already
  569. // exists. And while this exception is in a try..except statement, the debugger
  570. // always shows the exception, which is pretty annoying.
  571. try
  572. case SQLServerType of
  573. ssFirebird:
  574. begin
  575. // This only works with Firebird 2+
  576. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where upper(rdb$relation_name)=''' + UpperCase(ATableName) + ''')) '+
  577. 'then execute statement ''drop table ' + ATableName + ';'';end');
  578. FTransaction.CommitRetaining;
  579. end;
  580. ssMSSQL:
  581. begin
  582. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  583. // which leads to the rollback not referring to the right transaction=>SQL error
  584. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  585. FConnection.ExecuteDirect(
  586. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''')'+
  587. ' drop table ' + ATableName );
  588. end;
  589. ssMySQL:
  590. begin
  591. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  592. end;
  593. ssPostgreSQL,
  594. ssSQLite:
  595. begin
  596. FConnection.ExecuteDirect('drop table if exists ' + ATableName);
  597. FTransaction.CommitRetaining;
  598. end;
  599. ssOracle:
  600. begin
  601. FConnection.ExecuteDirect(
  602. 'declare ' +
  603. ' c int; ' +
  604. 'begin ' +
  605. ' select count(*) into c from all_tables where table_name = upper(''' + ATableName + '''); ' +
  606. ' if c = 1 then ' +
  607. ' execute immediate ''drop table ' + ATableName + '''; ' +
  608. ' end if; ' +
  609. 'end; ');
  610. end;
  611. ssSybase:
  612. begin
  613. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  614. // which leads to the rollback not referring to the right transaction=>SQL error
  615. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  616. FConnection.ExecuteDirect(
  617. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  618. 'begin '+
  619. 'drop table ' + ATableName + ' '+
  620. 'end');
  621. end;
  622. end;
  623. except
  624. FTransaction.RollbackRetaining;
  625. end;
  626. end;
  627. procedure TSQLDBConnector.TryDropSequence(ASequenceName: String);
  628. var
  629. NoSeq : Boolean;
  630. begin
  631. NoSeq:=False;
  632. try
  633. case SQLServerType of
  634. ssInterbase,
  635. ssFirebird: FConnection.ExecuteDirect('DROP GENERATOR '+ASequenceName);
  636. ssOracle,
  637. ssPostgreSQL,
  638. ssSybase,
  639. ssMSSQL : FConnection.ExecuteDirect('DROP SEQUENCE '+ASequenceName+' START WITH 1 INCREMENT BY 1');
  640. ssSQLite : FConnection.ExecuteDirect('delete from sqlite_sequence where (name='''+ASequenceName+''')');
  641. else
  642. NoSeq:=True;
  643. end;
  644. except
  645. FTransaction.RollbackRetaining;
  646. end;
  647. if NoSeq then
  648. Raise EDatabaseError.Create('Engine does not support sequences');
  649. end;
  650. procedure TSQLDBConnector.TryCreateSequence(ASequenceName: String);
  651. var
  652. NoSeq : Boolean;
  653. begin
  654. NoSeq:=False;
  655. case SQLServerType of
  656. ssInterbase,
  657. ssFirebird: FConnection.ExecuteDirect('CREATE GENERATOR '+ASequenceName);
  658. ssOracle,
  659. ssPostgreSQL,
  660. ssSybase,
  661. ssMSSQL : FConnection.ExecuteDirect('CREATE SEQUENCE '+ASequenceName+' START WITH 1 INCREMENT BY 1');
  662. ssSQLite : FConnection.ExecuteDirect('insert into sqlite_sequence (name,seq) values ('''+ASequenceName+''',1)');
  663. else
  664. Raise EDatabaseError.Create('Engine does not support sequences');
  665. end;
  666. end;
  667. procedure TSQLDBConnector.ExecuteDirect(const SQL: string);
  668. begin
  669. Connection.ExecuteDirect(SQL);
  670. end;
  671. procedure TSQLDBConnector.CommitDDL;
  672. begin
  673. // Commits schema definition and manipulation statements;
  674. // Firebird/Interbase need a commit after a DDL statement. Not necessary for the other connections
  675. if SQLServerType in [ssFirebird, ssInterbase] then
  676. Transaction.CommitRetaining;
  677. end;
  678. Procedure TSQLDBConnector.FreeTransaction;
  679. begin
  680. FreeAndNil(FTransaction);
  681. end;
  682. destructor TSQLDBConnector.Destroy;
  683. begin
  684. FreeAndNil(FQuery);
  685. if assigned(FTransaction) then
  686. begin
  687. try
  688. if not (stoUseImplicit in Transaction.Options) then
  689. begin
  690. if Ftransaction.Active then
  691. Ftransaction.Rollback;
  692. Ftransaction.StartTransaction;
  693. end;
  694. TryDropIfExist('FPDEV2');
  695. if not (stoUseImplicit in Transaction.Options) then
  696. Ftransaction.Commit;
  697. Except
  698. if Ftransaction.Active and not (stoUseImplicit in Transaction.Options) then
  699. Ftransaction.Rollback;
  700. end; // try
  701. end;
  702. FreeTransaction;
  703. FreeAndNil(FConnection);
  704. inherited Destroy;
  705. end;
  706. constructor TSQLDBConnector.Create;
  707. begin
  708. FConnection := nil;
  709. CreateFConnection;
  710. FQuery := CreateQuery;
  711. Inherited;
  712. end;
  713. initialization
  714. RegisterClass(TSQLDBConnector);
  715. end.