2
0

sqldbtoolsunit.pas 14 KB

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