sqldbtoolsunit.pas 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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, pqconnection, odbcconn, oracleconnection, sqlite3conn, mssqlconn;
  9. type TSQLDBTypes = (mysql40,mysql41,mysql50,mysql51,mysql55,postgresql,interbase,odbc,oracle,sqlite3,mssql);
  10. const MySQLdbTypes = [mysql40,mysql41,mysql50,mysql51,mysql55];
  11. DBTypesNames : Array [TSQLDBTypes] of String[19] =
  12. ('MYSQL40','MYSQL41','MYSQL50','MYSQL51','MYSQL55','POSTGRESQL','INTERBASE','ODBC','ORACLE','SQLITE3','MSSQL');
  13. FieldtypeDefinitionsConst : Array [TFieldType] of String[20] =
  14. (
  15. '',
  16. 'VARCHAR(10)',
  17. 'SMALLINT',
  18. 'INTEGER',
  19. '',
  20. 'BOOLEAN',
  21. 'FLOAT',
  22. '', // ftCurrency
  23. 'DECIMAL(18,4)',// ftBCD
  24. 'DATE',
  25. 'TIME',
  26. 'TIMESTAMP', // ftDateTime
  27. '',
  28. '',
  29. '',
  30. 'BLOB', // ftBlob
  31. 'BLOB', // ftMemo
  32. 'BLOB', // ftGraphic
  33. '',
  34. '',
  35. '',
  36. '',
  37. '',
  38. 'CHAR(10)', // ftFixedChar
  39. '',
  40. 'BIGINT', // ftLargeInt
  41. '',
  42. '',
  43. '',
  44. '',
  45. '',
  46. '',
  47. '',
  48. '',
  49. '',
  50. '', // ftGuid
  51. 'TIMESTAMP', // ftTimestamp
  52. 'NUMERIC(18,6)',// ftFmtBCD
  53. '',
  54. ''
  55. );
  56. type
  57. { TSQLDBConnector }
  58. TSQLDBConnector = class(TDBConnector)
  59. private
  60. FConnection : TSQLConnection;
  61. FTransaction : TSQLTransaction;
  62. FQuery : TSQLQuery;
  63. FUniDirectional: boolean;
  64. procedure CreateFConnection;
  65. procedure CreateFTransaction;
  66. Function CreateQuery : TSQLQuery;
  67. protected
  68. procedure SetTestUniDirectional(const AValue: boolean); override;
  69. function GetTestUniDirectional: boolean; override;
  70. procedure CreateNDatasets; override;
  71. procedure CreateFieldDataset; override;
  72. procedure DropNDatasets; override;
  73. procedure DropFieldDataset; override;
  74. Function InternalGetNDataset(n : integer) : TDataset; override;
  75. Function InternalGetFieldDataset : TDataSet; override;
  76. procedure TryDropIfExist(ATableName : String);
  77. public
  78. destructor Destroy; override;
  79. constructor Create; override;
  80. property Connection : TSQLConnection read FConnection;
  81. property Transaction : TSQLTransaction read FTransaction;
  82. property Query : TSQLQuery read FQuery;
  83. end;
  84. var SQLDbType : TSQLDBTypes;
  85. FieldtypeDefinitions : Array [TFieldType] of String[20];
  86. implementation
  87. uses StrUtils;
  88. { TSQLDBConnector }
  89. procedure TSQLDBConnector.CreateFConnection;
  90. var i : TSQLDBTypes;
  91. t : integer;
  92. begin
  93. for i := low(DBTypesNames) to high(DBTypesNames) do
  94. if UpperCase(dbconnectorparams) = DBTypesNames[i] then sqldbtype := i;
  95. FieldtypeDefinitions := FieldtypeDefinitionsConst;
  96. if SQLDbType = MYSQL40 then Fconnection := tMySQL40Connection.Create(nil);
  97. if SQLDbType = MYSQL41 then Fconnection := tMySQL41Connection.Create(nil);
  98. if SQLDbType = MYSQL50 then Fconnection := tMySQL50Connection.Create(nil);
  99. if SQLDbType = MYSQL51 then Fconnection := tMySQL51Connection.Create(nil);
  100. if SQLDbType = MYSQL55 then Fconnection := tMySQL55Connection.Create(nil);
  101. if SQLDbType in [mysql40,mysql41] then
  102. begin
  103. // Mysql versions prior to 5.0.3 removes the trailing spaces on varchar
  104. // fields on insertion. So to test properly, we have to do the same
  105. for t := 0 to testValuesCount-1 do
  106. testStringValues[t] := TrimRight(testStringValues[t]);
  107. end;
  108. if SQLDbType in MySQLdbTypes then
  109. begin
  110. //MySQL recognizes BOOLEAN, but as synonym for TINYINT, not true sql boolean datatype
  111. FieldtypeDefinitions[ftBoolean] := '';
  112. FieldtypeDefinitions[ftFloat] := 'DOUBLE';
  113. // Use 'DATETIME' for datetime-fields instead of timestamp, because
  114. // mysql's timestamps are only valid in the range 1970-2038.
  115. // Downside is that fields defined as 'TIMESTAMP' aren't tested
  116. FieldtypeDefinitions[ftDateTime] := 'DATETIME';
  117. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  118. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  119. FieldtypeDefinitions[ftMemo] := 'TEXT';
  120. end;
  121. if SQLDbType = sqlite3 then
  122. begin
  123. Fconnection := TSQLite3Connection.Create(nil);
  124. FieldtypeDefinitions[ftCurrency] := 'CURRENCY';
  125. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  126. FieldtypeDefinitions[ftVarBytes] := 'VARBINARY(10)';
  127. FieldtypeDefinitions[ftMemo] := 'CLOB'; //or TEXT SQLite supports both, but CLOB is sql standard (TEXT not)
  128. end;
  129. if SQLDbType = POSTGRESQL then
  130. begin
  131. Fconnection := tPQConnection.Create(nil);
  132. FieldtypeDefinitions[ftCurrency] := 'MONEY';
  133. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  134. FieldtypeDefinitions[ftMemo] := 'TEXT';
  135. FieldtypeDefinitions[ftGraphic] := '';
  136. end;
  137. if SQLDbType = INTERBASE then
  138. begin
  139. Fconnection := tIBConnection.Create(nil);
  140. FieldtypeDefinitions[ftBoolean] := '';
  141. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  142. end;
  143. if SQLDbType = ODBC then Fconnection := tODBCConnection.Create(nil);
  144. if SQLDbType = ORACLE then Fconnection := TOracleConnection.Create(nil);
  145. if SQLDbType = MSSQL then
  146. begin
  147. Fconnection := TMSSQLConnection.Create(nil);
  148. FieldtypeDefinitions[ftBoolean] := 'BIT';
  149. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  150. FieldtypeDefinitions[ftDate] := 'DATETIME';
  151. FieldtypeDefinitions[ftTime] := '';
  152. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  153. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  154. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  155. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  156. FieldtypeDefinitions[ftMemo] := 'TEXT';
  157. FieldtypeDefinitions[ftGraphic] := '';
  158. end;
  159. if SQLDbType in [mysql40,mysql41,mysql50,mysql51,mysql55,odbc,interbase] then
  160. begin
  161. // Some DB's do not support milliseconds in datetime and time fields.
  162. // Firebird support miliseconds, see BUG 17199 (when resolved, then interbase can be excluded)
  163. for t := 0 to testValuesCount-1 do
  164. begin
  165. testTimeValues[t] := copy(testTimeValues[t],1,8)+'.000';
  166. testValues[ftTime,t] := copy(testTimeValues[t],1,8)+'.000';
  167. if length(testValues[ftDateTime,t]) > 19 then
  168. testValues[ftDateTime,t] := copy(testValues[ftDateTime,t],1,19)+'.000';
  169. end;
  170. end;
  171. if SQLDbType in [postgresql,interbase,mssql] then
  172. begin
  173. // Some db's do not support times > 24:00:00
  174. testTimeValues[3]:='13:25:15.000';
  175. testValues[ftTime,3]:='13:25:15.000';
  176. if SQLDbType = interbase then
  177. begin
  178. // Firebird does not support time = 24:00:00
  179. testTimeValues[2]:='23:00:00.000';
  180. testValues[ftTime,2]:='23:00:00.000';
  181. end;
  182. end;
  183. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  184. // Here we assume, that locale on client side is same as locale on server
  185. if SQLDbType in [postgresql] then
  186. for t := 0 to testValuesCount-1 do
  187. testValues[ftCurrency,t] := QuotedStr(CurrToStr(testCurrencyValues[t]));
  188. // SQLite does not support fixed length CHAR datatype
  189. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  190. // MSSQL set SET ANSI_PADDING ON
  191. if SQLDbType in [sqlite3] then
  192. for t := 0 to testValuesCount-1 do
  193. testValues[ftFixedChar,t] := PadRight(testValues[ftFixedChar,t], 10);
  194. if not assigned(Fconnection) then writeln('Invalid database-type, check if a valid database-type was provided in the file ''database.ini''');
  195. with Fconnection do
  196. begin
  197. DatabaseName := dbname;
  198. UserName := dbuser;
  199. Password := dbpassword;
  200. HostName := dbhostname;
  201. if length(dbQuoteChars)>1 then
  202. begin
  203. FieldNameQuoteChars:=dbquotechars;
  204. end;
  205. Open;
  206. end;
  207. end;
  208. procedure TSQLDBConnector.CreateFTransaction;
  209. begin
  210. Ftransaction := tsqltransaction.create(nil);
  211. with Ftransaction do
  212. database := Fconnection;
  213. end;
  214. Function TSQLDBConnector.CreateQuery : TSQLQuery;
  215. begin
  216. Result := TSQLQuery.create(nil);
  217. with Result do
  218. begin
  219. database := Fconnection;
  220. transaction := Ftransaction;
  221. end;
  222. end;
  223. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  224. begin
  225. FUniDirectional:=avalue;
  226. FQuery.UniDirectional:=AValue;
  227. end;
  228. function TSQLDBConnector.GetTestUniDirectional: boolean;
  229. begin
  230. result := FUniDirectional;
  231. end;
  232. procedure TSQLDBConnector.CreateNDatasets;
  233. var CountID : Integer;
  234. begin
  235. try
  236. Ftransaction.StartTransaction;
  237. TryDropIfExist('FPDEV');
  238. Fconnection.ExecuteDirect('create table FPDEV ( ' +
  239. ' ID INT NOT NULL, ' +
  240. ' NAME VARCHAR(50), ' +
  241. ' PRIMARY KEY (ID) ' +
  242. ') ');
  243. FTransaction.CommitRetaining;
  244. for countID := 1 to MaxDataSet do
  245. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  246. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  247. Ftransaction.Commit;
  248. except
  249. if Ftransaction.Active then Ftransaction.Rollback
  250. end;
  251. end;
  252. procedure TSQLDBConnector.CreateFieldDataset;
  253. var CountID : Integer;
  254. FType : TFieldType;
  255. Sql,sql1: String;
  256. begin
  257. try
  258. Ftransaction.StartTransaction;
  259. TryDropIfExist('FPDEV_FIELD');
  260. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  261. for FType := low(TFieldType)to high(TFieldType) do
  262. if FieldtypeDefinitions[FType]<>'' then
  263. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +FieldtypeDefinitions[FType]+ ',';
  264. Sql := Sql + 'PRIMARY KEY (ID))';
  265. FConnection.ExecuteDirect(Sql);
  266. FTransaction.CommitRetaining;
  267. for countID := 0 to testValuesCount-1 do
  268. begin
  269. Sql := 'insert into FPDEV_FIELD (ID';
  270. Sql1 := 'values ('+IntToStr(countID);
  271. for FType := low(TFieldType)to high(TFieldType) do
  272. if FieldtypeDefinitions[FType]<>'' then
  273. begin
  274. sql := sql + ',F' + Fieldtypenames[FType];
  275. if testValues[FType,CountID] <> '' then
  276. if FType in [ftCurrency] then
  277. sql1 := sql1 + ',' + testValues[FType,CountID]
  278. else
  279. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  280. else
  281. sql1 := sql1 + ',NULL';
  282. end;
  283. Sql := sql + ')';
  284. Sql1 := sql1+ ')';
  285. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  286. end;
  287. Ftransaction.Commit;
  288. except
  289. on E: Exception do begin
  290. //writeln(E.Message);
  291. if Ftransaction.Active then Ftransaction.Rollback;
  292. end;
  293. end;
  294. end;
  295. procedure TSQLDBConnector.DropNDatasets;
  296. begin
  297. if assigned(FTransaction) then
  298. begin
  299. try
  300. if Ftransaction.Active then Ftransaction.Rollback;
  301. Ftransaction.StartTransaction;
  302. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  303. Ftransaction.Commit;
  304. Except
  305. if Ftransaction.Active then Ftransaction.Rollback
  306. end;
  307. end;
  308. end;
  309. procedure TSQLDBConnector.DropFieldDataset;
  310. begin
  311. if assigned(FTransaction) then
  312. begin
  313. try
  314. if Ftransaction.Active then Ftransaction.Rollback;
  315. Ftransaction.StartTransaction;
  316. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  317. Ftransaction.Commit;
  318. Except
  319. if Ftransaction.Active then Ftransaction.Rollback
  320. end;
  321. end;
  322. end;
  323. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  324. begin
  325. Result := CreateQuery;
  326. with (Result as TSQLQuery) do
  327. begin
  328. sql.clear;
  329. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  330. UniDirectional:=TestUniDirectional;
  331. end;
  332. end;
  333. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  334. begin
  335. Result := CreateQuery;
  336. with (Result as TSQLQuery) do
  337. begin
  338. sql.clear;
  339. sql.add('SELECT * FROM FPDEV_FIELD');
  340. tsqlquery(Result).UniDirectional:=TestUniDirectional;
  341. end;
  342. end;
  343. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  344. begin
  345. // This makes live soo much easier, since it avoids the exception if the table already
  346. // exists. And while this exeption is in a try..except statement, the debugger
  347. // always shows the exception. Which is pretty annoying
  348. // It only works with Firebird 2, though.
  349. try
  350. if SQLDbType = INTERBASE then
  351. begin
  352. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  353. 'then execute statement ''drop table ' + ATAbleName + ';'';end');
  354. FTransaction.CommitRetaining;
  355. end;
  356. except
  357. FTransaction.RollbackRetaining;
  358. end;
  359. end;
  360. destructor TSQLDBConnector.Destroy;
  361. begin
  362. if assigned(FTransaction) then
  363. begin
  364. try
  365. if Ftransaction.Active then Ftransaction.Rollback;
  366. Ftransaction.StartTransaction;
  367. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  368. Ftransaction.Commit;
  369. Except
  370. if Ftransaction.Active then Ftransaction.Rollback
  371. end; // try
  372. end;
  373. inherited Destroy;
  374. FreeAndNil(FQuery);
  375. FreeAndNil(FTransaction);
  376. FreeAndNil(FConnection);
  377. end;
  378. constructor TSQLDBConnector.Create;
  379. begin
  380. FConnection := nil;
  381. CreateFConnection;
  382. CreateFTransaction;
  383. FQuery := CreateQuery;
  384. FConnection.Transaction := FTransaction;
  385. Inherited;
  386. end;
  387. initialization
  388. RegisterClass(TSQLDBConnector);
  389. end.