sqldbtoolsunit.pas 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. unit SQLDBToolsUnit;
  2. {$mode objfpc}{$H+}
  3. interface
  4. uses
  5. Classes, SysUtils, toolsunit
  6. ,db, sqldb
  7. ,mysql40conn, mysql41conn, mysql50conn, mysql51conn, mysql55conn
  8. ,ibconnection
  9. ,pqconnection
  10. ,odbcconn
  11. {$IFNDEF WIN64}
  12. {See packages\fcl-db\fpmake.pp: Oracle connector is not built if PostgreSQL connectoris not built}
  13. ,oracleconnection
  14. {$ENDIF WIN64}
  15. ,sqlite3conn
  16. ,mssqlconn
  17. ;
  18. type
  19. TSQLConnType = (mysql40,mysql41,mysql50,mysql51,mysql55,postgresql,interbase,odbc,oracle,sqlite3,mssql,sybase);
  20. TSQLServerType = (ssFirebird, ssInterbase, ssMSSQL, ssMySQL, ssOracle, ssPostgreSQL, ssSQLite, ssSybase, ssUnknown);
  21. const MySQLConnTypes = [mysql40,mysql41,mysql50,mysql51,mysql55];
  22. SQLConnTypesNames : Array [TSQLConnType] of String[19] =
  23. ('MYSQL40','MYSQL41','MYSQL50','MYSQL51','MYSQL55','POSTGRESQL','INTERBASE','ODBC','ORACLE','SQLITE3','MSSQL','SYBASE');
  24. FieldtypeDefinitionsConst : Array [TFieldType] of String[20] =
  25. (
  26. '',
  27. 'VARCHAR(10)',
  28. 'SMALLINT',
  29. 'INTEGER',
  30. '',
  31. 'BOOLEAN',
  32. 'DOUBLE PRECISION', // ftFloat
  33. '', // ftCurrency
  34. 'DECIMAL(18,4)',// ftBCD
  35. 'DATE',
  36. 'TIME',
  37. 'TIMESTAMP', // ftDateTime
  38. '',
  39. '',
  40. '', // ftAutoInc
  41. 'BLOB', // ftBlob
  42. 'BLOB', // ftMemo
  43. 'BLOB', // ftGraphic
  44. '',
  45. '',
  46. '',
  47. '',
  48. '',
  49. 'CHAR(10)', // ftFixedChar
  50. '',
  51. 'BIGINT', // ftLargeInt
  52. '',
  53. '',
  54. '',
  55. '',
  56. '',
  57. '',
  58. '',
  59. '',
  60. '',
  61. '', // ftGuid
  62. 'TIMESTAMP', // ftTimestamp
  63. 'NUMERIC(18,6)',// ftFmtBCD
  64. '',
  65. ''
  66. );
  67. type
  68. { TSQLDBConnector }
  69. TSQLDBConnector = class(TDBConnector)
  70. private
  71. FConnection : TSQLConnection;
  72. FTransaction : TSQLTransaction;
  73. FQuery : TSQLQuery;
  74. FUniDirectional: boolean;
  75. procedure CreateFConnection;
  76. procedure CreateFTransaction;
  77. Function CreateQuery : TSQLQuery;
  78. protected
  79. procedure SetTestUniDirectional(const AValue: boolean); override;
  80. function GetTestUniDirectional: boolean; override;
  81. procedure CreateNDatasets; override;
  82. procedure CreateFieldDataset; override;
  83. procedure DropNDatasets; override;
  84. procedure DropFieldDataset; override;
  85. Function InternalGetNDataset(n : integer) : TDataset; override;
  86. Function InternalGetFieldDataset : TDataSet; override;
  87. procedure TryDropIfExist(ATableName : String);
  88. public
  89. destructor Destroy; override;
  90. constructor Create; override;
  91. property Connection : TSQLConnection read FConnection;
  92. property Transaction : TSQLTransaction read FTransaction;
  93. property Query : TSQLQuery read FQuery;
  94. end;
  95. var SQLConnType : TSQLConnType;
  96. SQLServerType : TSQLServerType;
  97. FieldtypeDefinitions : Array [TFieldType] of String[20];
  98. implementation
  99. uses StrUtils;
  100. type
  101. TSQLServerTypesMapItem = record
  102. s: string;
  103. t: TSQLServerType;
  104. end;
  105. const
  106. // names as returned by ODBC SQLGetInfo(..., SQL_DBMS_NAME, ...) and GetConnectionInfo(citServerType)
  107. SQLServerTypesMap : array [0..7] of TSQLServerTypesMapItem = (
  108. (s: 'Firebird'; t: ssFirebird),
  109. (s: 'Interbase'; t: ssInterbase),
  110. (s: 'Microsoft SQL Server'; t: ssMSSQL),
  111. (s: 'MySQL'; t: ssMySQL),
  112. (s: 'Oracle'; t: ssOracle),
  113. (s: 'PostgreSQL'; t: ssPostgreSQL),
  114. (s: 'SQLite3'; t: ssSQLite),
  115. (s: 'ASE'; t: ssSybase)
  116. );
  117. // fall back mapping (e.g. in case GetConnectionInfo(citServerType) is not implemented)
  118. SQLConnTypeToServerTypeMap : array[TSQLConnType] of TSQLServerType =
  119. (ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssPostgreSQL,ssFirebird,ssUnknown,ssOracle,ssSQLite,ssMSSQL,ssSybase);
  120. { TSQLDBConnector }
  121. procedure TSQLDBConnector.CreateFConnection;
  122. var t : TSQLConnType;
  123. i : integer;
  124. s : string;
  125. begin
  126. for t := low(SQLConnTypesNames) to high(SQLConnTypesNames) do
  127. if UpperCase(dbconnectorparams) = SQLConnTypesNames[t] then SQLConnType := t;
  128. if SQLConnType = MYSQL40 then Fconnection := TMySQL40Connection.Create(nil);
  129. if SQLConnType = MYSQL41 then Fconnection := TMySQL41Connection.Create(nil);
  130. if SQLConnType = MYSQL50 then Fconnection := TMySQL50Connection.Create(nil);
  131. if SQLConnType = MYSQL51 then Fconnection := TMySQL51Connection.Create(nil);
  132. if SQLConnType = MYSQL55 then Fconnection := TMySQL55Connection.Create(nil);
  133. if SQLConnType = SQLITE3 then Fconnection := TSQLite3Connection.Create(nil);
  134. if SQLConnType = POSTGRESQL then Fconnection := TPQConnection.Create(nil);
  135. if SQLConnType = INTERBASE then Fconnection := TIBConnection.Create(nil);
  136. if SQLConnType = ODBC then Fconnection := TODBCConnection.Create(nil);
  137. {$IFNDEF Win64}
  138. if SQLConnType = ORACLE then Fconnection := TOracleConnection.Create(nil);
  139. {$ENDIF Win64}
  140. if SQLConnType = MSSQL then Fconnection := TMSSQLConnection.Create(nil);
  141. if SQLConnType = SYBASE then Fconnection := TSybaseConnection.Create(nil);
  142. if not assigned(Fconnection) then writeln('Invalid database type, check if a valid database type for your achitecture was provided in the file ''database.ini''');
  143. with Fconnection do
  144. begin
  145. DatabaseName := dbname;
  146. UserName := dbuser;
  147. Password := dbpassword;
  148. HostName := dbhostname;
  149. if (dbhostname='') and (SQLConnType=interbase) then
  150. begin
  151. // Firebird embedded: create database file if it doesn't yet exist
  152. // Note: pagesize parameter has influence on behavior. We're using
  153. // Firebird default here.
  154. if not(fileexists(dbname)) then
  155. CreateDB; //Create testdb
  156. end;
  157. if length(dbQuoteChars)>1 then
  158. begin
  159. FieldNameQuoteChars:=dbquotechars;
  160. end;
  161. Open;
  162. end;
  163. // determine remote SQL Server to which we are connected
  164. s := Fconnection.GetConnectionInfo(citServerType);
  165. if s = '' then
  166. SQLServerType := SQLConnTypeToServerTypeMap[SQLConnType] // if citServerType isn't implemented
  167. else
  168. for i := low(SQLServerTypesMap) to high(SQLServerTypesMap) do
  169. if SQLServerTypesMap[i].s = s then
  170. SQLServerType := SQLServerTypesMap[i].t;
  171. FieldtypeDefinitions := FieldtypeDefinitionsConst;
  172. case SQLServerType of
  173. ssFirebird, ssInterbase:
  174. begin
  175. FieldtypeDefinitions[ftBoolean] := '';
  176. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  177. end;
  178. ssMSSQL, ssSybase:
  179. // todo: Sybase: copied over MSSQL; verify correctness
  180. begin
  181. FieldtypeDefinitions[ftBoolean] := 'BIT';
  182. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  183. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  184. FieldtypeDefinitions[ftDate] := 'DATETIME';
  185. FieldtypeDefinitions[ftTime] := '';
  186. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  187. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  188. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  189. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  190. FieldtypeDefinitions[ftMemo] := 'TEXT';
  191. FieldtypeDefinitions[ftGraphic] := '';
  192. end;
  193. ssMySQL:
  194. begin
  195. //MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  196. FieldtypeDefinitions[ftBoolean] := '';
  197. // Use 'DATETIME' for datetime-fields instead of timestamp, because
  198. // mysql's timestamps are only valid in the range 1970-2038.
  199. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  200. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  201. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  202. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  203. FieldtypeDefinitions[ftMemo] := 'TEXT';
  204. end;
  205. ssOracle:
  206. begin
  207. FieldtypeDefinitions[ftBoolean] := '';
  208. FieldtypeDefinitions[ftTime] := 'TIMESTAMP';
  209. FieldtypeDefinitions[ftMemo] := 'CLOB';
  210. end;
  211. ssPostgreSQL:
  212. begin
  213. FieldtypeDefinitions[ftCurrency] := 'MONEY';
  214. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  215. FieldtypeDefinitions[ftMemo] := 'TEXT';
  216. FieldtypeDefinitions[ftGraphic] := '';
  217. end;
  218. ssSQLite:
  219. begin
  220. FieldtypeDefinitions[ftCurrency] := 'CURRENCY';
  221. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  222. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  223. FieldtypeDefinitions[ftMemo] := 'CLOB'; //or TEXT SQLite supports both, but CLOB is sql standard (TEXT not)
  224. FieldtypeDefinitions[ftWideString] := 'NVARCHAR(10)';
  225. FieldtypeDefinitions[ftWideMemo] := 'NCLOB';
  226. end;
  227. end;
  228. if SQLConnType in [mysql40,mysql41] then
  229. begin
  230. // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar
  231. // fields on insertion. So to test properly, we have to do the same
  232. for i := 0 to testValuesCount-1 do
  233. testStringValues[i] := TrimRight(testStringValues[i]);
  234. end;
  235. if SQLServerType in [ssMySQL] then
  236. begin
  237. // Some DB's do not support milliseconds in datetime and time fields.
  238. for i := 0 to testValuesCount-1 do
  239. begin
  240. testTimeValues[i] := copy(testTimeValues[i],1,8)+'.000';
  241. testValues[ftTime,i] := copy(testTimeValues[i],1,8)+'.000';
  242. if length(testValues[ftDateTime,i]) > 19 then
  243. testValues[ftDateTime,i] := copy(testValues[ftDateTime,i],1,19)+'.000';
  244. end;
  245. end;
  246. if SQLServerType in [ssFirebird, ssInterbase, ssMSSQL, ssPostgreSQL, ssSybase] then
  247. begin
  248. // Some db's do not support times > 24:00:00
  249. testTimeValues[3]:='13:25:15.000';
  250. testValues[ftTime,3]:='13:25:15.000';
  251. if SQLServerType in [ssFirebird, ssInterbase] then
  252. begin
  253. // Firebird does not support time = 24:00:00
  254. testTimeValues[2]:='23:00:00.000';
  255. testValues[ftTime,2]:='23:00:00.000';
  256. end;
  257. end;
  258. if SQLServerType in [ssMSSQL, ssSybase] then
  259. // Some DB's do not support datetime values before 1753-01-01
  260. for i := 18 to testValuesCount-1 do
  261. begin
  262. testValues[ftDate,i] := testValues[ftDate,0];
  263. testValues[ftDateTime,i] := testValues[ftDateTime,0];
  264. end;
  265. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  266. // Here we assume, that locale on client side is same as locale on server
  267. if SQLServerType in [ssPostgreSQL] then
  268. for i := 0 to testValuesCount-1 do
  269. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  270. // SQLite does not support fixed length CHAR datatype
  271. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  272. // MSSQL set SET ANSI_PADDING ON
  273. // todo: verify Sybase behaviour
  274. if SQLServerType in [ssSQLite] then
  275. for i := 0 to testValuesCount-1 do
  276. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  277. end;
  278. procedure TSQLDBConnector.CreateFTransaction;
  279. begin
  280. Ftransaction := tsqltransaction.create(nil);
  281. with Ftransaction do
  282. database := Fconnection;
  283. end;
  284. Function TSQLDBConnector.CreateQuery : TSQLQuery;
  285. begin
  286. Result := TSQLQuery.create(nil);
  287. with Result do
  288. begin
  289. database := Fconnection;
  290. transaction := Ftransaction;
  291. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  292. end;
  293. end;
  294. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  295. begin
  296. FUniDirectional:=avalue;
  297. FQuery.UniDirectional:=AValue;
  298. end;
  299. function TSQLDBConnector.GetTestUniDirectional: boolean;
  300. begin
  301. result := FUniDirectional;
  302. end;
  303. procedure TSQLDBConnector.CreateNDatasets;
  304. var CountID : Integer;
  305. begin
  306. try
  307. Ftransaction.StartTransaction;
  308. TryDropIfExist('FPDEV');
  309. Fconnection.ExecuteDirect('create table FPDEV (' +
  310. ' ID INT NOT NULL, ' +
  311. ' NAME VARCHAR(50), ' +
  312. ' PRIMARY KEY (ID) ' +
  313. ')');
  314. FTransaction.CommitRetaining;
  315. for countID := 1 to MaxDataSet do
  316. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  317. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  318. Ftransaction.Commit;
  319. except
  320. if Ftransaction.Active then Ftransaction.Rollback
  321. end;
  322. end;
  323. procedure TSQLDBConnector.CreateFieldDataset;
  324. var CountID : Integer;
  325. FType : TFieldType;
  326. Sql,sql1: String;
  327. begin
  328. try
  329. Ftransaction.StartTransaction;
  330. TryDropIfExist('FPDEV_FIELD');
  331. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  332. for FType := low(TFieldType)to high(TFieldType) do
  333. if FieldtypeDefinitions[FType]<>'' then
  334. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +FieldtypeDefinitions[FType]+ ',';
  335. Sql := Sql + 'PRIMARY KEY (ID))';
  336. FConnection.ExecuteDirect(Sql);
  337. FTransaction.CommitRetaining;
  338. for countID := 0 to testValuesCount-1 do
  339. begin
  340. Sql := 'insert into FPDEV_FIELD (ID';
  341. Sql1 := 'values ('+IntToStr(countID);
  342. for FType := low(TFieldType)to high(TFieldType) do
  343. if FieldtypeDefinitions[FType]<>'' then
  344. begin
  345. sql := sql + ',F' + Fieldtypenames[FType];
  346. if testValues[FType,CountID] <> '' then
  347. if FType in [ftCurrency] then
  348. sql1 := sql1 + ',' + testValues[FType,CountID]
  349. else
  350. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  351. else
  352. sql1 := sql1 + ',NULL';
  353. end;
  354. Sql := sql + ')';
  355. Sql1 := sql1+ ')';
  356. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  357. end;
  358. Ftransaction.Commit;
  359. except
  360. on E: Exception do begin
  361. //writeln(E.Message);
  362. if Ftransaction.Active then Ftransaction.Rollback;
  363. end;
  364. end;
  365. end;
  366. procedure TSQLDBConnector.DropNDatasets;
  367. begin
  368. if assigned(FTransaction) then
  369. begin
  370. try
  371. if Ftransaction.Active then Ftransaction.Rollback;
  372. Ftransaction.StartTransaction;
  373. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  374. Ftransaction.Commit;
  375. Except
  376. if Ftransaction.Active then Ftransaction.Rollback
  377. end;
  378. end;
  379. end;
  380. procedure TSQLDBConnector.DropFieldDataset;
  381. begin
  382. if assigned(FTransaction) then
  383. begin
  384. try
  385. if Ftransaction.Active then Ftransaction.Rollback;
  386. Ftransaction.StartTransaction;
  387. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  388. Ftransaction.Commit;
  389. Except
  390. if Ftransaction.Active then Ftransaction.Rollback
  391. end;
  392. end;
  393. end;
  394. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  395. begin
  396. Result := CreateQuery;
  397. with (Result as TSQLQuery) do
  398. begin
  399. sql.clear;
  400. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  401. UniDirectional:=TestUniDirectional;
  402. end;
  403. end;
  404. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  405. begin
  406. Result := CreateQuery;
  407. with (Result as TSQLQuery) do
  408. begin
  409. sql.clear;
  410. sql.add('SELECT * FROM FPDEV_FIELD');
  411. tsqlquery(Result).UniDirectional:=TestUniDirectional;
  412. end;
  413. end;
  414. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  415. begin
  416. // This makes life soo much easier, since it avoids the exception if the table already
  417. // exists. And while this exeption is in a try..except statement, the debugger
  418. // always shows the exception, which is pretty annoying.
  419. try
  420. if SQLConnType = INTERBASE then
  421. begin
  422. // This only works with Firebird 2+
  423. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  424. 'then execute statement ''drop table ' + ATAbleName + ';'';end');
  425. FTransaction.CommitRetaining;
  426. end;
  427. if SQLConnType = mssql then
  428. begin
  429. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  430. // which leads to the rollback not referring to the right transaction=>SQL error
  431. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  432. FConnection.ExecuteDirect(
  433. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  434. 'begin '+
  435. 'drop table ' + ATAbleName + ' '+
  436. 'end');
  437. FTransaction.CommitRetaining;
  438. end;
  439. if SQLConnType = sybase then
  440. begin
  441. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  442. // which leads to the rollback not referring to the right transaction=>SQL error
  443. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  444. FConnection.ExecuteDirect(
  445. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  446. 'begin '+
  447. 'drop table ' + ATAbleName + ' '+
  448. 'end');
  449. end;
  450. except
  451. FTransaction.RollbackRetaining;
  452. end;
  453. end;
  454. destructor TSQLDBConnector.Destroy;
  455. begin
  456. if assigned(FTransaction) then
  457. begin
  458. try
  459. if Ftransaction.Active then Ftransaction.Rollback;
  460. Ftransaction.StartTransaction;
  461. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  462. Ftransaction.Commit;
  463. Except
  464. if Ftransaction.Active then Ftransaction.Rollback
  465. end; // try
  466. end;
  467. inherited Destroy;
  468. FreeAndNil(FQuery);
  469. FreeAndNil(FTransaction);
  470. FreeAndNil(FConnection);
  471. end;
  472. constructor TSQLDBConnector.Create;
  473. begin
  474. FConnection := nil;
  475. CreateFConnection;
  476. CreateFTransaction;
  477. FQuery := CreateQuery;
  478. FConnection.Transaction := FTransaction;
  479. Inherited;
  480. end;
  481. initialization
  482. RegisterClass(TSQLDBConnector);
  483. end.