sqldbtoolsunit.pas 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. {$IFNDEF win64}
  139. if SQLDbType = POSTGRESQL then
  140. begin
  141. Fconnection := tPQConnection.Create(nil);
  142. FieldtypeDefinitions[ftCurrency] := 'MONEY';
  143. FieldtypeDefinitions[ftBlob] := 'BYTEA';
  144. FieldtypeDefinitions[ftMemo] := 'TEXT';
  145. FieldtypeDefinitions[ftGraphic] := '';
  146. end;
  147. if SQLDbType = INTERBASE then
  148. begin
  149. Fconnection := tIBConnection.Create(nil);
  150. FieldtypeDefinitions[ftBoolean] := '';
  151. FieldtypeDefinitions[ftMemo] := 'BLOB SUB_TYPE TEXT';
  152. end;
  153. if SQLDbType = ODBC then Fconnection := tODBCConnection.Create(nil);
  154. {$IFNDEF Win64}
  155. if SQLDbType = ORACLE then Fconnection := TOracleConnection.Create(nil);
  156. {$ENDIF Win64}
  157. if SQLDbType in [MSSQL,Sybase] then
  158. // todo: Sybase: copied over MSSQL; verify correctness
  159. begin
  160. Fconnection := TMSSQLConnection.Create(nil);
  161. FieldtypeDefinitions[ftBoolean] := 'BIT';
  162. FieldtypeDefinitions[ftCurrency]:= 'MONEY';
  163. FieldtypeDefinitions[ftDate] := 'DATETIME';
  164. FieldtypeDefinitions[ftTime] := '';
  165. FieldtypeDefinitions[ftDateTime]:= 'DATETIME';
  166. FieldtypeDefinitions[ftBytes] := 'BINARY(5)';
  167. FieldtypeDefinitions[ftVarBytes]:= 'VARBINARY(10)';
  168. FieldtypeDefinitions[ftBlob] := 'IMAGE';
  169. FieldtypeDefinitions[ftMemo] := 'TEXT';
  170. FieldtypeDefinitions[ftGraphic] := '';
  171. end;
  172. if SQLDbType in [mysql40,mysql41,mysql50,mysql51,mysql55,odbc] then
  173. begin
  174. // Some DB's do not support milliseconds in datetime and time fields.
  175. for t := 0 to testValuesCount-1 do
  176. begin
  177. testTimeValues[t] := copy(testTimeValues[t],1,8)+'.000';
  178. testValues[ftTime,t] := copy(testTimeValues[t],1,8)+'.000';
  179. if length(testValues[ftDateTime,t]) > 19 then
  180. testValues[ftDateTime,t] := copy(testValues[ftDateTime,t],1,19)+'.000';
  181. end;
  182. end;
  183. if SQLDbType in [postgresql,interbase,mssql,sybase] then
  184. begin
  185. // Some db's do not support times > 24:00:00
  186. testTimeValues[3]:='13:25:15.000';
  187. testValues[ftTime,3]:='13:25:15.000';
  188. if SQLDbType = interbase then
  189. begin
  190. // Firebird does not support time = 24:00:00
  191. testTimeValues[2]:='23:00:00.000';
  192. testValues[ftTime,2]:='23:00:00.000';
  193. end;
  194. end;
  195. // DecimalSeparator must correspond to monetary locale (lc_monetary) set on PostgreSQL server
  196. // Here we assume, that locale on client side is same as locale on server
  197. if SQLDbType in [postgresql] then
  198. for t := 0 to testValuesCount-1 do
  199. testValues[ftCurrency,t] := QuotedStr(CurrToStr(testCurrencyValues[t]));
  200. // SQLite does not support fixed length CHAR datatype
  201. // MySQL by default trimms trailing spaces on retrieval; so set sql-mode="PAD_CHAR_TO_FULL_LENGTH" - supported from MySQL 5.1.20
  202. // MSSQL set SET ANSI_PADDING ON
  203. // todo: verify Sybase behaviour
  204. if SQLDbType in [sqlite3] then
  205. for t := 0 to testValuesCount-1 do
  206. testValues[ftFixedChar,t] := PadRight(testValues[ftFixedChar,t], 10);
  207. if not assigned(Fconnection) then writeln('Invalid database-type, check if a valid database-type was provided in the file ''database.ini''');
  208. with Fconnection do
  209. begin
  210. DatabaseName := dbname;
  211. UserName := dbuser;
  212. Password := dbpassword;
  213. HostName := dbhostname;
  214. if (dbhostname='') and (SQLDbType=interbase) then
  215. begin
  216. // Firebird embedded: create database file if it doesn't yet exist
  217. // Note: pagesize parameter has influence on behavior. We're using
  218. // Firebird default here.
  219. if not(fileexists(dbname)) then
  220. FConnection.CreateDB; //Create testdb
  221. end;
  222. if length(dbQuoteChars)>1 then
  223. begin
  224. FieldNameQuoteChars:=dbquotechars;
  225. end;
  226. Open;
  227. end;
  228. end;
  229. procedure TSQLDBConnector.CreateFTransaction;
  230. begin
  231. Ftransaction := tsqltransaction.create(nil);
  232. with Ftransaction do
  233. database := Fconnection;
  234. end;
  235. Function TSQLDBConnector.CreateQuery : TSQLQuery;
  236. begin
  237. Result := TSQLQuery.create(nil);
  238. with Result do
  239. begin
  240. database := Fconnection;
  241. transaction := Ftransaction;
  242. PacketRecords := -1; // To avoid: "Connection is busy with results for another hstmt" (ODBC,MSSQL)
  243. end;
  244. end;
  245. procedure TSQLDBConnector.SetTestUniDirectional(const AValue: boolean);
  246. begin
  247. FUniDirectional:=avalue;
  248. FQuery.UniDirectional:=AValue;
  249. end;
  250. function TSQLDBConnector.GetTestUniDirectional: boolean;
  251. begin
  252. result := FUniDirectional;
  253. end;
  254. procedure TSQLDBConnector.CreateNDatasets;
  255. var CountID : Integer;
  256. begin
  257. try
  258. Ftransaction.StartTransaction;
  259. TryDropIfExist('FPDEV');
  260. Fconnection.ExecuteDirect('create table FPDEV ( ' +
  261. ' ID INT NOT NULL, ' +
  262. ' NAME VARCHAR(50), ' +
  263. ' PRIMARY KEY (ID) ' +
  264. ') ');
  265. FTransaction.CommitRetaining;
  266. for countID := 1 to MaxDataSet do
  267. Fconnection.ExecuteDirect('insert into FPDEV (ID,NAME)' +
  268. 'values ('+inttostr(countID)+',''TestName'+inttostr(countID)+''')');
  269. Ftransaction.Commit;
  270. except
  271. if Ftransaction.Active then Ftransaction.Rollback
  272. end;
  273. end;
  274. procedure TSQLDBConnector.CreateFieldDataset;
  275. var CountID : Integer;
  276. FType : TFieldType;
  277. Sql,sql1: String;
  278. begin
  279. try
  280. Ftransaction.StartTransaction;
  281. TryDropIfExist('FPDEV_FIELD');
  282. Sql := 'create table FPDEV_FIELD (ID INT NOT NULL,';
  283. for FType := low(TFieldType)to high(TFieldType) do
  284. if FieldtypeDefinitions[FType]<>'' then
  285. sql := sql + 'F' + Fieldtypenames[FType] + ' ' +FieldtypeDefinitions[FType]+ ',';
  286. Sql := Sql + 'PRIMARY KEY (ID))';
  287. FConnection.ExecuteDirect(Sql);
  288. FTransaction.CommitRetaining;
  289. for countID := 0 to testValuesCount-1 do
  290. begin
  291. Sql := 'insert into FPDEV_FIELD (ID';
  292. Sql1 := 'values ('+IntToStr(countID);
  293. for FType := low(TFieldType)to high(TFieldType) do
  294. if FieldtypeDefinitions[FType]<>'' then
  295. begin
  296. sql := sql + ',F' + Fieldtypenames[FType];
  297. if testValues[FType,CountID] <> '' then
  298. if FType in [ftCurrency] then
  299. sql1 := sql1 + ',' + testValues[FType,CountID]
  300. else
  301. sql1 := sql1 + ',' + QuotedStr(testValues[FType,CountID])
  302. else
  303. sql1 := sql1 + ',NULL';
  304. end;
  305. Sql := sql + ')';
  306. Sql1 := sql1+ ')';
  307. Fconnection.ExecuteDirect(sql + ' ' + sql1);
  308. end;
  309. Ftransaction.Commit;
  310. except
  311. on E: Exception do begin
  312. //writeln(E.Message);
  313. if Ftransaction.Active then Ftransaction.Rollback;
  314. end;
  315. end;
  316. end;
  317. procedure TSQLDBConnector.DropNDatasets;
  318. begin
  319. if assigned(FTransaction) then
  320. begin
  321. try
  322. if Ftransaction.Active then Ftransaction.Rollback;
  323. Ftransaction.StartTransaction;
  324. Fconnection.ExecuteDirect('DROP TABLE FPDEV');
  325. Ftransaction.Commit;
  326. Except
  327. if Ftransaction.Active then Ftransaction.Rollback
  328. end;
  329. end;
  330. end;
  331. procedure TSQLDBConnector.DropFieldDataset;
  332. begin
  333. if assigned(FTransaction) then
  334. begin
  335. try
  336. if Ftransaction.Active then Ftransaction.Rollback;
  337. Ftransaction.StartTransaction;
  338. Fconnection.ExecuteDirect('DROP TABLE FPDEV_FIELD');
  339. Ftransaction.Commit;
  340. Except
  341. if Ftransaction.Active then Ftransaction.Rollback
  342. end;
  343. end;
  344. end;
  345. function TSQLDBConnector.InternalGetNDataset(n: integer): TDataset;
  346. begin
  347. Result := CreateQuery;
  348. with (Result as TSQLQuery) do
  349. begin
  350. sql.clear;
  351. sql.add('SELECT * FROM FPDEV WHERE ID < '+inttostr(n+1));
  352. UniDirectional:=TestUniDirectional;
  353. end;
  354. end;
  355. function TSQLDBConnector.InternalGetFieldDataset: TDataSet;
  356. begin
  357. Result := CreateQuery;
  358. with (Result as TSQLQuery) do
  359. begin
  360. sql.clear;
  361. sql.add('SELECT * FROM FPDEV_FIELD');
  362. tsqlquery(Result).UniDirectional:=TestUniDirectional;
  363. end;
  364. end;
  365. procedure TSQLDBConnector.TryDropIfExist(ATableName: String);
  366. begin
  367. // This makes life soo much easier, since it avoids the exception if the table already
  368. // exists. And while this exeption is in a try..except statement, the debugger
  369. // always shows the exception, which is pretty annoying.
  370. try
  371. if SQLDbType = INTERBASE then
  372. begin
  373. // This only works with Firebird 2+
  374. FConnection.ExecuteDirect('execute block as begin if (exists (select 1 from rdb$relations where rdb$relation_name=''' + ATableName + ''')) '+
  375. 'then execute statement ''drop table ' + ATAbleName + ';'';end');
  376. FTransaction.CommitRetaining;
  377. end;
  378. if SQLDBType = mssql then
  379. begin
  380. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  381. // which leads to the rollback not referring to the right transaction=>SQL error
  382. // Use SQL92 ISO standard INFORMATION_SCHEMA:
  383. FConnection.ExecuteDirect(
  384. 'if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE=''BASE TABLE'' AND TABLE_NAME=''' + ATableName + ''') '+
  385. 'begin '+
  386. 'drop table ' + ATAbleName + ' '+
  387. 'end');
  388. FTransaction.CommitRetaining;
  389. end;
  390. if SQLDbType = sybase then
  391. begin
  392. // Checking is needed here to avoid getting "auto rollback" of a subsequent CREATE TABLE statement
  393. // which leads to the rollback not referring to the right transaction=>SQL error
  394. // Can't use SQL standard information_schema; instead query sysobjects for User tables
  395. FConnection.ExecuteDirect(
  396. 'if exists (select * from sysobjects where type = ''U'' and name=''' + ATableName + ''') '+
  397. 'begin '+
  398. 'drop table ' + ATAbleName + ' '+
  399. 'end');
  400. end;
  401. except
  402. FTransaction.RollbackRetaining;
  403. end;
  404. end;
  405. destructor TSQLDBConnector.Destroy;
  406. begin
  407. if assigned(FTransaction) then
  408. begin
  409. try
  410. if Ftransaction.Active then Ftransaction.Rollback;
  411. Ftransaction.StartTransaction;
  412. Fconnection.ExecuteDirect('DROP TABLE FPDEV2');
  413. Ftransaction.Commit;
  414. Except
  415. if Ftransaction.Active then Ftransaction.Rollback
  416. end; // try
  417. end;
  418. inherited Destroy;
  419. FreeAndNil(FQuery);
  420. FreeAndNil(FTransaction);
  421. FreeAndNil(FConnection);
  422. end;
  423. constructor TSQLDBConnector.Create;
  424. begin
  425. FConnection := nil;
  426. CreateFConnection;
  427. CreateFTransaction;
  428. FQuery := CreateQuery;
  429. FConnection.Transaction := FTransaction;
  430. Inherited;
  431. end;
  432. initialization
  433. RegisterClass(TSQLDBConnector);
  434. end.