sqldbtoolsunit.pas 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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. '', // ftWord
  31. 'BOOLEAN',
  32. 'DOUBLE PRECISION', // ftFloat
  33. '', // ftCurrency
  34. 'DECIMAL(18,4)',// ftBCD
  35. 'DATE',
  36. 'TIME',
  37. 'TIMESTAMP', // ftDateTime
  38. '', // ftBytes
  39. '', // ftVarBytes
  40. '', // ftAutoInc
  41. 'BLOB', // ftBlob
  42. 'BLOB', // ftMemo
  43. 'BLOB', // ftGraphic
  44. '',
  45. '',
  46. '',
  47. '',
  48. '',
  49. 'CHAR(10)', // ftFixedChar
  50. '', // ftWideString
  51. 'BIGINT', // ftLargeInt
  52. '',
  53. '',
  54. '',
  55. '',
  56. '',
  57. '',
  58. '',
  59. '',
  60. '',
  61. '', // ftGuid
  62. 'TIMESTAMP', // ftTimestamp
  63. 'NUMERIC(18,6)',// ftFmtBCD
  64. '', // ftFixedWideChar
  65. '' // ftWideMemo
  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. procedure CommitDDL;
  92. property Connection : TSQLConnection read FConnection;
  93. property Transaction : TSQLTransaction read FTransaction;
  94. property Query : TSQLQuery read FQuery;
  95. end;
  96. var SQLConnType : TSQLConnType;
  97. SQLServerType : TSQLServerType;
  98. FieldtypeDefinitions : Array [TFieldType] of String[20];
  99. implementation
  100. uses StrUtils;
  101. type
  102. TSQLServerTypesMapItem = record
  103. s: string;
  104. t: TSQLServerType;
  105. end;
  106. const
  107. // names as returned by ODBC SQLGetInfo(..., SQL_DBMS_NAME, ...) and GetConnectionInfo(citServerType)
  108. SQLServerTypesMap : array [0..7] of TSQLServerTypesMapItem = (
  109. (s: 'Firebird'; t: ssFirebird),
  110. (s: 'Interbase'; t: ssInterbase),
  111. (s: 'Microsoft SQL Server'; t: ssMSSQL),
  112. (s: 'MySQL'; t: ssMySQL),
  113. (s: 'Oracle'; t: ssOracle),
  114. (s: 'PostgreSQL'; t: ssPostgreSQL),
  115. (s: 'SQLite3'; t: ssSQLite),
  116. (s: 'ASE'; t: ssSybase)
  117. );
  118. // fall back mapping (e.g. in case GetConnectionInfo(citServerType) is not implemented)
  119. SQLConnTypeToServerTypeMap : array[TSQLConnType] of TSQLServerType =
  120. (ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssMySQL,ssPostgreSQL,ssFirebird,ssUnknown,ssOracle,ssSQLite,ssMSSQL,ssSybase);
  121. { TSQLDBConnector }
  122. procedure TSQLDBConnector.CreateFConnection;
  123. var t : TSQLConnType;
  124. i : integer;
  125. s : string;
  126. begin
  127. for t := low(SQLConnTypesNames) to high(SQLConnTypesNames) do
  128. if UpperCase(dbconnectorparams) = SQLConnTypesNames[t] then SQLConnType := t;
  129. if SQLConnType = MYSQL40 then Fconnection := TMySQL40Connection.Create(nil);
  130. if SQLConnType = MYSQL41 then Fconnection := TMySQL41Connection.Create(nil);
  131. if SQLConnType = MYSQL50 then Fconnection := TMySQL50Connection.Create(nil);
  132. if SQLConnType = MYSQL51 then Fconnection := TMySQL51Connection.Create(nil);
  133. if SQLConnType = MYSQL55 then Fconnection := TMySQL55Connection.Create(nil);
  134. if SQLConnType = SQLITE3 then Fconnection := TSQLite3Connection.Create(nil);
  135. if SQLConnType = POSTGRESQL then Fconnection := TPQConnection.Create(nil);
  136. if SQLConnType = INTERBASE then Fconnection := TIBConnection.Create(nil);
  137. if SQLConnType = ODBC then Fconnection := TODBCConnection.Create(nil);
  138. {$IFNDEF Win64}
  139. if SQLConnType = ORACLE then Fconnection := TOracleConnection.Create(nil);
  140. {$ENDIF Win64}
  141. if SQLConnType = MSSQL then Fconnection := TMSSQLConnection.Create(nil);
  142. if SQLConnType = SYBASE then Fconnection := TSybaseConnection.Create(nil);
  143. 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''');
  144. with Fconnection do
  145. begin
  146. DatabaseName := dbname;
  147. UserName := dbuser;
  148. Password := dbpassword;
  149. HostName := dbhostname;
  150. if (dbhostname='') and (SQLConnType=interbase) then
  151. begin
  152. // Firebird embedded: create database file if it doesn't yet exist
  153. // Note: pagesize parameter has influence on behavior. We're using
  154. // Firebird default here.
  155. if not(fileexists(dbname)) then
  156. CreateDB; //Create testdb
  157. end;
  158. if length(dbQuoteChars)>1 then
  159. FieldNameQuoteChars:=dbQuoteChars;
  160. Open;
  161. end;
  162. // determine remote SQL Server to which we are connected
  163. s := Fconnection.GetConnectionInfo(citServerType);
  164. if s = '' then
  165. SQLServerType := SQLConnTypeToServerTypeMap[SQLConnType] // if citServerType isn't implemented
  166. else
  167. for i := low(SQLServerTypesMap) to high(SQLServerTypesMap) do
  168. if SQLServerTypesMap[i].s = s then
  169. SQLServerType := SQLServerTypesMap[i].t;
  170. FieldtypeDefinitions := FieldtypeDefinitionsConst;
  171. case SQLServerType of
  172. ssFirebird:
  173. begin
  174. FieldtypeDefinitions[ftBoolean] := '';
  175. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  176. end;
  177. ssInterbase:
  178. begin
  179. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  180. FieldtypeDefinitions[ftLargeInt] := 'NUMERIC(18,0)';
  181. end;
  182. ssMSSQL, ssSybase:
  183. // todo: Sybase: copied over MSSQL; verify correctness
  184. begin
  185. FieldtypeDefinitions[ftBoolean] := 'BIT';
  186. FieldtypeDefinitions[ftFloat] := 'FLOAT';
  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. // Use 'DATETIME' for datetime-fields instead of timestamp, because
  202. // mysql's timestamps are only valid in the range 1970-2038.
  203. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  204. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  205. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  206. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  207. FieldtypeDefinitions[ftMemo] := 'TEXT';
  208. end;
  209. ssOracle:
  210. begin
  211. FieldtypeDefinitions[ftBoolean] := '';
  212. FieldtypeDefinitions[ftTime] := 'TIMESTAMP';
  213. FieldtypeDefinitions[ftMemo] := 'CLOB';
  214. end;
  215. ssPostgreSQL:
  216. begin
  217. FieldtypeDefinitions[ftCurrency] := 'MONEY';
  218. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  219. FieldtypeDefinitions[ftMemo] := 'TEXT';
  220. FieldtypeDefinitions[ftGraphic] := '';
  221. end;
  222. ssSQLite:
  223. begin
  224. FieldtypeDefinitions[ftWord] := 'WORD';
  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. case SQLServerType of
  426. ssFirebird:
  427. begin
  428. // This only works with Firebird 2+
  429. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  430. 'then execute statement ''drop table ' + ATableName + ';'';end');
  431. FTransaction.CommitRetaining;
  432. end;
  433. ssMSSQL:
  434. begin
  435. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  436. // which leads to the rollback not referring to the right transaction=>SQL error
  437. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  438. FConnection.ExecuteDirect(
  439. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  440. 'begin '+
  441. 'drop table ' + ATableName + ' '+
  442. 'end');
  443. end;
  444. ssSybase:
  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. end;
  456. except
  457. FTransaction.RollbackRetaining;
  458. end;
  459. end;
  460. procedure TSQLDBConnector.CommitDDL;
  461. begin
  462. // Commits schema definition and manipulation statements;
  463. // Firebird/Interbase need a commit after a DDL statement. Not necessary for the other connections
  464. if SQLServerType in [ssFirebird, ssInterbase] then
  465. Transaction.CommitRetaining;
  466. end;
  467. destructor TSQLDBConnector.Destroy;
  468. begin
  469. if assigned(FTransaction) then
  470. begin
  471. try
  472. if Ftransaction.Active then Ftransaction.Rollback;
  473. Ftransaction.StartTransaction;
  474. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  475. Ftransaction.Commit;
  476. Except
  477. if Ftransaction.Active then Ftransaction.Rollback;
  478. end; // try
  479. end;
  480. inherited Destroy;
  481. FreeAndNil(FQuery);
  482. FreeAndNil(FTransaction);
  483. FreeAndNil(FConnection);
  484. end;
  485. constructor TSQLDBConnector.Create;
  486. begin
  487. FConnection := nil;
  488. CreateFConnection;
  489. CreateFTransaction;
  490. FQuery := CreateQuery;
  491. FConnection.Transaction := FTransaction;
  492. Inherited;
  493. end;
  494. initialization
  495. RegisterClass(TSQLDBConnector);
  496. end.