sqldbtoolsunit.pas 12 KB

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