sqldbtoolsunit.pas 28 KB

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