sqldbtoolsunit.pas 15 KB

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