sqldbtoolsunit.pas 15 KB

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