sqldbtoolsunit.pas 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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] then
  176. begin
  177. // Some DB's do not support milliseconds in datetime and time fields.
  178. for t := 0 to testValuesCount-1 do
  179. begin
  180. testTimeValues[t] := copy(testTimeValues[t],1,8)+'.000';
  181. testValues[ftTime,t] := copy(testTimeValues[t],1,8)+'.000';
  182. if length(testValues[ftDateTime,t]) > 19 then
  183. testValues[ftDateTime,t] := copy(testValues[ftDateTime,t],1,19)+'.000';
  184. end;
  185. end;
  186. if SQLDbType in [postgresql,interbase,mssql] then
  187. begin
  188. // Some db's do not support times > 24:00:00
  189. testTimeValues[3]:='13:25:15.000';
  190. testValues[ftTime,3]:='13:25:15.000';
  191. if SQLDbType = interbase then
  192. begin
  193. // Firebird does not support time = 24:00:00
  194. testTimeValues[2]:='23:00:00.000';
  195. testValues[ftTime,2]:='23:00:00.000';
  196. end;
  197. end;
  198. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  199. // Here we assume, that locale on client side is same as locale on server
  200. if SQLDbType in [postgresql] then
  201. for t := 0 to testValuesCount-1 do
  202. testValues[ftCurrency,t] := QuotedStr(CurrToStr(testCurrencyValues[t]));
  203. // SQLite does not support fixed length CHAR datatype
  204. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  205. // MSSQL set SET ANSI_PADDING ON
  206. if SQLDbType in [sqlite3] then
  207. for t := 0 to testValuesCount-1 do
  208. testValues[ftFixedChar,t] := PadRight(testValues[ftFixedChar,t], 10);
  209. 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''');
  210. with Fconnection do
  211. begin
  212. DatabaseName := dbname;
  213. UserName := dbuser;
  214. Password := dbpassword;
  215. HostName := dbhostname;
  216. if length(dbQuoteChars)>1 then
  217. begin
  218. FieldNameQuoteChars:=dbquotechars;
  219. end;
  220. Open;
  221. end;
  222. end;
  223. procedure TSQLDBConnector.CreateFTransaction;
  224. begin
  225. Ftransaction := tsqltransaction.create(nil);
  226. with Ftransaction do
  227. database := Fconnection;
  228. end;
  229. Function TSQLDBConnector.CreateQuery : TSQLQuery;
  230. begin
  231. Result := TSQLQuery.create(nil);
  232. with Result do
  233. begin
  234. database := Fconnection;
  235. transaction := Ftransaction;
  236. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  237. end;
  238. end;
  239. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  240. begin
  241. FUniDirectional:=avalue;
  242. FQuery.UniDirectional:=AValue;
  243. end;
  244. function TSQLDBConnector.GetTestUniDirectional: boolean;
  245. begin
  246. result := FUniDirectional;
  247. end;
  248. procedure TSQLDBConnector.CreateNDatasets;
  249. var CountID : Integer;
  250. begin
  251. try
  252. Ftransaction.StartTransaction;
  253. TryDropIfExist('FPDEV');
  254. Fconnection.ExecuteDirect('create table FPDEV ( ' +
  255. ' ID INT NOT NULL, ' +
  256. ' NAME VARCHAR(50), ' +
  257. ' PRIMARY KEY (ID) ' +
  258. ') ');
  259. FTransaction.CommitRetaining;
  260. for countID := 1 to MaxDataSet do
  261. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  262. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  263. Ftransaction.Commit;
  264. except
  265. if Ftransaction.Active then Ftransaction.Rollback
  266. end;
  267. end;
  268. procedure TSQLDBConnector.CreateFieldDataset;
  269. var CountID : Integer;
  270. FType : TFieldType;
  271. Sql,sql1: String;
  272. begin
  273. try
  274. Ftransaction.StartTransaction;
  275. TryDropIfExist('FPDEV_FIELD');
  276. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  277. for FType := low(TFieldType)to high(TFieldType) do
  278. if FieldtypeDefinitions[FType]<>'' then
  279. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +FieldtypeDefinitions[FType]+ ',';
  280. Sql := Sql + 'PRIMARY KEY (ID))';
  281. FConnection.ExecuteDirect(Sql);
  282. FTransaction.CommitRetaining;
  283. for countID := 0 to testValuesCount-1 do
  284. begin
  285. Sql := 'insert into FPDEV_FIELD (ID';
  286. Sql1 := 'values ('+IntToStr(countID);
  287. for FType := low(TFieldType)to high(TFieldType) do
  288. if FieldtypeDefinitions[FType]<>'' then
  289. begin
  290. sql := sql + ',F' + Fieldtypenames[FType];
  291. if testValues[FType,CountID] <> '' then
  292. if FType in [ftCurrency] then
  293. sql1 := sql1 + ',' + testValues[FType,CountID]
  294. else
  295. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  296. else
  297. sql1 := sql1 + ',NULL';
  298. end;
  299. Sql := sql + ')';
  300. Sql1 := sql1+ ')';
  301. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  302. end;
  303. Ftransaction.Commit;
  304. except
  305. on E: Exception do begin
  306. //writeln(E.Message);
  307. if Ftransaction.Active then Ftransaction.Rollback;
  308. end;
  309. end;
  310. end;
  311. procedure TSQLDBConnector.DropNDatasets;
  312. begin
  313. if assigned(FTransaction) then
  314. begin
  315. try
  316. if Ftransaction.Active then Ftransaction.Rollback;
  317. Ftransaction.StartTransaction;
  318. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  319. Ftransaction.Commit;
  320. Except
  321. if Ftransaction.Active then Ftransaction.Rollback
  322. end;
  323. end;
  324. end;
  325. procedure TSQLDBConnector.DropFieldDataset;
  326. begin
  327. if assigned(FTransaction) then
  328. begin
  329. try
  330. if Ftransaction.Active then Ftransaction.Rollback;
  331. Ftransaction.StartTransaction;
  332. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  333. Ftransaction.Commit;
  334. Except
  335. if Ftransaction.Active then Ftransaction.Rollback
  336. end;
  337. end;
  338. end;
  339. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  340. begin
  341. Result := CreateQuery;
  342. with (Result as TSQLQuery) do
  343. begin
  344. sql.clear;
  345. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  346. UniDirectional:=TestUniDirectional;
  347. end;
  348. end;
  349. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  350. begin
  351. Result := CreateQuery;
  352. with (Result as TSQLQuery) do
  353. begin
  354. sql.clear;
  355. sql.add('SELECT * FROM FPDEV_FIELD');
  356. tsqlquery(Result).UniDirectional:=TestUniDirectional;
  357. end;
  358. end;
  359. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  360. begin
  361. // This makes live soo much easier, since it avoids the exception if the table already
  362. // exists. And while this exeption is in a try..except statement, the debugger
  363. // always shows the exception. Which is pretty annoying
  364. // It only works with Firebird 2, though.
  365. try
  366. if SQLDbType = INTERBASE then
  367. begin
  368. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  369. 'then execute statement ''drop table ' + ATAbleName + ';'';end');
  370. FTransaction.CommitRetaining;
  371. end;
  372. except
  373. FTransaction.RollbackRetaining;
  374. end;
  375. end;
  376. destructor TSQLDBConnector.Destroy;
  377. begin
  378. if assigned(FTransaction) then
  379. begin
  380. try
  381. if Ftransaction.Active then Ftransaction.Rollback;
  382. Ftransaction.StartTransaction;
  383. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  384. Ftransaction.Commit;
  385. Except
  386. if Ftransaction.Active then Ftransaction.Rollback
  387. end; // try
  388. end;
  389. inherited Destroy;
  390. FreeAndNil(FQuery);
  391. FreeAndNil(FTransaction);
  392. FreeAndNil(FConnection);
  393. end;
  394. constructor TSQLDBConnector.Create;
  395. begin
  396. FConnection := nil;
  397. CreateFConnection;
  398. CreateFTransaction;
  399. FQuery := CreateQuery;
  400. FConnection.Transaction := FTransaction;
  401. Inherited;
  402. end;
  403. initialization
  404. RegisterClass(TSQLDBConnector);
  405. end.