sqldbtoolsunit.pas 12 KB

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