sqldbtoolsunit.pas 28 KB

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