sqldbtoolsunit.pas 18 KB

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