sqldbtoolsunit.pas 14 KB

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