sqldbtoolsunit.pas 17 KB

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