sqldbtoolsunit.pas 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. 'FLOAT',
  33. '', // ftCurrency
  34. 'DECIMAL(18,4)',// ftBCD
  35. 'DATE',
  36. 'TIME',
  37. 'TIMESTAMP', // ftDateTime
  38. '',
  39. '',
  40. '',
  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[ftDate] := 'DATETIME';
  184. FieldtypeDefinitions[ftTime] := '';
  185. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  186. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  187. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  188. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  189. FieldtypeDefinitions[ftMemo] := 'TEXT';
  190. FieldtypeDefinitions[ftGraphic] := '';
  191. end;
  192. ssMySQL:
  193. begin
  194. //MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  195. FieldtypeDefinitions[ftBoolean] := '';
  196. FieldtypeDefinitions[ftFloat] := 'DOUBLE';
  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. end;
  225. end;
  226. if SQLConnType in [mysql40,mysql41] then
  227. begin
  228. // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar
  229. // fields on insertion. So to test properly, we have to do the same
  230. for i := 0 to testValuesCount-1 do
  231. testStringValues[i] := TrimRight(testStringValues[i]);
  232. end;
  233. if SQLServerType in [ssMySQL] then
  234. begin
  235. // Some DB's do not support milliseconds in datetime and time fields.
  236. for i := 0 to testValuesCount-1 do
  237. begin
  238. testTimeValues[i] := copy(testTimeValues[i],1,8)+'.000';
  239. testValues[ftTime,i] := copy(testTimeValues[i],1,8)+'.000';
  240. if length(testValues[ftDateTime,i]) > 19 then
  241. testValues[ftDateTime,i] := copy(testValues[ftDateTime,i],1,19)+'.000';
  242. end;
  243. end;
  244. if SQLServerType in [ssFirebird, ssInterbase, ssMSSQL, ssPostgreSQL, ssSybase] then
  245. begin
  246. // Some db's do not support times > 24:00:00
  247. testTimeValues[3]:='13:25:15.000';
  248. testValues[ftTime,3]:='13:25:15.000';
  249. if SQLServerType in [ssFirebird, ssInterbase] then
  250. begin
  251. // Firebird does not support time = 24:00:00
  252. testTimeValues[2]:='23:00:00.000';
  253. testValues[ftTime,2]:='23:00:00.000';
  254. end;
  255. end;
  256. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  257. // Here we assume, that locale on client side is same as locale on server
  258. if SQLServerType in [ssPostgreSQL] then
  259. for i := 0 to testValuesCount-1 do
  260. testValues[ftCurrency,i] := QuotedStr(CurrToStr(testCurrencyValues[i]));
  261. // SQLite does not support fixed length CHAR datatype
  262. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  263. // MSSQL set SET ANSI_PADDING ON
  264. // todo: verify Sybase behaviour
  265. if SQLServerType in [ssSQLite] then
  266. for i := 0 to testValuesCount-1 do
  267. testValues[ftFixedChar,i] := PadRight(testValues[ftFixedChar,i], 10);
  268. end;
  269. procedure TSQLDBConnector.CreateFTransaction;
  270. begin
  271. Ftransaction := tsqltransaction.create(nil);
  272. with Ftransaction do
  273. database := Fconnection;
  274. end;
  275. Function TSQLDBConnector.CreateQuery : TSQLQuery;
  276. begin
  277. Result := TSQLQuery.create(nil);
  278. with Result do
  279. begin
  280. database := Fconnection;
  281. transaction := Ftransaction;
  282. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  283. end;
  284. end;
  285. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  286. begin
  287. FUniDirectional:=avalue;
  288. FQuery.UniDirectional:=AValue;
  289. end;
  290. function TSQLDBConnector.GetTestUniDirectional: boolean;
  291. begin
  292. result := FUniDirectional;
  293. end;
  294. procedure TSQLDBConnector.CreateNDatasets;
  295. var CountID : Integer;
  296. begin
  297. try
  298. Ftransaction.StartTransaction;
  299. TryDropIfExist('FPDEV');
  300. Fconnection.ExecuteDirect('create table FPDEV (' +
  301. ' ID INT NOT NULL, ' +
  302. ' NAME VARCHAR(50), ' +
  303. ' PRIMARY KEY (ID) ' +
  304. ')');
  305. FTransaction.CommitRetaining;
  306. for countID := 1 to MaxDataSet do
  307. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  308. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  309. Ftransaction.Commit;
  310. except
  311. if Ftransaction.Active then Ftransaction.Rollback
  312. end;
  313. end;
  314. procedure TSQLDBConnector.CreateFieldDataset;
  315. var CountID : Integer;
  316. FType : TFieldType;
  317. Sql,sql1: String;
  318. begin
  319. try
  320. Ftransaction.StartTransaction;
  321. TryDropIfExist('FPDEV_FIELD');
  322. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  323. for FType := low(TFieldType)to high(TFieldType) do
  324. if FieldtypeDefinitions[FType]<>'' then
  325. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +FieldtypeDefinitions[FType]+ ',';
  326. Sql := Sql + 'PRIMARY KEY (ID))';
  327. FConnection.ExecuteDirect(Sql);
  328. FTransaction.CommitRetaining;
  329. for countID := 0 to testValuesCount-1 do
  330. begin
  331. Sql := 'insert into FPDEV_FIELD (ID';
  332. Sql1 := 'values ('+IntToStr(countID);
  333. for FType := low(TFieldType)to high(TFieldType) do
  334. if FieldtypeDefinitions[FType]<>'' then
  335. begin
  336. sql := sql + ',F' + Fieldtypenames[FType];
  337. if testValues[FType,CountID] <> '' then
  338. if FType in [ftCurrency] then
  339. sql1 := sql1 + ',' + testValues[FType,CountID]
  340. else
  341. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  342. else
  343. sql1 := sql1 + ',NULL';
  344. end;
  345. Sql := sql + ')';
  346. Sql1 := sql1+ ')';
  347. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  348. end;
  349. Ftransaction.Commit;
  350. except
  351. on E: Exception do begin
  352. //writeln(E.Message);
  353. if Ftransaction.Active then Ftransaction.Rollback;
  354. end;
  355. end;
  356. end;
  357. procedure TSQLDBConnector.DropNDatasets;
  358. begin
  359. if assigned(FTransaction) then
  360. begin
  361. try
  362. if Ftransaction.Active then Ftransaction.Rollback;
  363. Ftransaction.StartTransaction;
  364. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  365. Ftransaction.Commit;
  366. Except
  367. if Ftransaction.Active then Ftransaction.Rollback
  368. end;
  369. end;
  370. end;
  371. procedure TSQLDBConnector.DropFieldDataset;
  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_FIELD');
  379. Ftransaction.Commit;
  380. Except
  381. if Ftransaction.Active then Ftransaction.Rollback
  382. end;
  383. end;
  384. end;
  385. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  386. begin
  387. Result := CreateQuery;
  388. with (Result as TSQLQuery) do
  389. begin
  390. sql.clear;
  391. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  392. UniDirectional:=TestUniDirectional;
  393. end;
  394. end;
  395. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  396. begin
  397. Result := CreateQuery;
  398. with (Result as TSQLQuery) do
  399. begin
  400. sql.clear;
  401. sql.add('SELECT * FROM FPDEV_FIELD');
  402. tsqlquery(Result).UniDirectional:=TestUniDirectional;
  403. end;
  404. end;
  405. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  406. begin
  407. // This makes life soo much easier, since it avoids the exception if the table already
  408. // exists. And while this exeption is in a try..except statement, the debugger
  409. // always shows the exception, which is pretty annoying.
  410. try
  411. if SQLConnType = INTERBASE then
  412. begin
  413. // This only works with Firebird 2+
  414. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  415. 'then execute statement ''drop table ' + ATAbleName + ';'';end');
  416. FTransaction.CommitRetaining;
  417. end;
  418. if SQLConnType = mssql then
  419. begin
  420. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  421. // which leads to the rollback not referring to the right transaction=>SQL error
  422. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  423. FConnection.ExecuteDirect(
  424. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  425. 'begin '+
  426. 'drop table ' + ATAbleName + ' '+
  427. 'end');
  428. FTransaction.CommitRetaining;
  429. end;
  430. if SQLConnType = sybase then
  431. begin
  432. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  433. // which leads to the rollback not referring to the right transaction=>SQL error
  434. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  435. FConnection.ExecuteDirect(
  436. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  437. 'begin '+
  438. 'drop table ' + ATAbleName + ' '+
  439. 'end');
  440. end;
  441. except
  442. FTransaction.RollbackRetaining;
  443. end;
  444. end;
  445. destructor TSQLDBConnector.Destroy;
  446. begin
  447. if assigned(FTransaction) then
  448. begin
  449. try
  450. if Ftransaction.Active then Ftransaction.Rollback;
  451. Ftransaction.StartTransaction;
  452. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  453. Ftransaction.Commit;
  454. Except
  455. if Ftransaction.Active then Ftransaction.Rollback
  456. end; // try
  457. end;
  458. inherited Destroy;
  459. FreeAndNil(FQuery);
  460. FreeAndNil(FTransaction);
  461. FreeAndNil(FConnection);
  462. end;
  463. constructor TSQLDBConnector.Create;
  464. begin
  465. FConnection := nil;
  466. CreateFConnection;
  467. CreateFTransaction;
  468. FQuery := CreateQuery;
  469. FConnection.Transaction := FTransaction;
  470. Inherited;
  471. end;
  472. initialization
  473. RegisterClass(TSQLDBConnector);
  474. end.