sqldbpool.pp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293
  1. unit sqldbpool;
  2. {$mode objfpc}
  3. {$H+}
  4. interface
  5. uses
  6. Classes, SysUtils, db, sqldb, pqconnection, syncobjs, contnrs;
  7. const
  8. DefaultDisconnectTimeOut = 10*60; // Number of seconds before connection is considered old and is discarded.
  9. type
  10. TPoolLogEvent = procedure(Sender : TObject; Const Msg : string) of object;
  11. ESQLDBPool = Class(EDatabaseError);
  12. { TSQLConnectionDef }
  13. { TSQLDBConnectionDef }
  14. TSQLDBConnectionDef = Class(TCollectionItem)
  15. private
  16. FConnectionClass: TSQLConnectionClass;
  17. FConnectionType: String;
  18. FDatabaseName: UTF8String;
  19. FEnabled: Boolean;
  20. FHostName: UTF8String;
  21. FName: UTF8String;
  22. FParams: TStrings;
  23. FPassword: UTF8string;
  24. FRole: UTF8String;
  25. FUserName: UTF8String;
  26. FKey : UTF8String;
  27. FCharSet : UTF8String;
  28. procedure DoChange(Sender: TObject);
  29. function GetPort: Word;
  30. procedure SetCharSet(AValue: UTF8String);
  31. procedure SetConnectionType(AValue: String);
  32. procedure SetDatabaseName(AValue: UTF8String);
  33. procedure SetHostName(AValue: UTF8String);
  34. procedure SetParams(AValue: TStrings);
  35. procedure SetPassword(AValue: UTF8string);
  36. procedure SetPort(AValue: Word);
  37. procedure SetRole(AValue: UTF8String);
  38. procedure SetUserName(AValue: UTF8String);
  39. Protected
  40. procedure AssignTo(Dest: TPersistent); override;
  41. procedure ClearKey;
  42. function GetName : UTF8String; virtual;
  43. Function GetDisplayName: string; override;
  44. function CreateKey : String; virtual;
  45. Public
  46. Constructor Create(ACollection: TCollection); override;
  47. Destructor Destroy; override;
  48. Procedure Assign(Source: TPersistent); override;
  49. Property ConnectionClass : TSQLConnectionClass Read FConnectionClass Write FConnectionClass;
  50. function GetDescription(Full: Boolean=False): string;
  51. Function ToString: string; override;
  52. Published
  53. // TSQLConnector type
  54. Property ConnectionType : String read FConnectionType write SetConnectionType;
  55. // Name for this connection
  56. Property Name : UTF8String read GetName write FName;
  57. // Database database name
  58. Property DatabaseName : UTF8String read FDatabaseName write SetDatabaseName;
  59. // Database hostname
  60. Property HostName : UTF8String read FHostName write SetHostName;
  61. // Database username
  62. Property UserName : UTF8String read FUserName write SetUserName;
  63. // Database role
  64. Property Role : UTF8String read FRole write SetRole;
  65. // Database user password
  66. Property Password : UTF8string read FPassword write SetPassword;
  67. // Other parameters
  68. Property Params : TStrings Read FParams Write SetParams;
  69. // Stored in Params.
  70. // Database character set
  71. Property CharSet : UTF8String Read FCharSet Write SetCharSet;
  72. // Port
  73. Property Port : Word Read GetPort Write SetPort;
  74. // Allow this connection to be used ?
  75. Property Enabled : Boolean Read FEnabled Write FEnabled default true;
  76. end;
  77. { TConnectionPoolData }
  78. TConnectionPoolData = Class(TObject)
  79. private
  80. FConnection: TSQLConnection;
  81. FLastUsed: TDateTime;
  82. FLocked: Boolean;
  83. Public
  84. Constructor Create(aConnection : TSQLConnection; aLocked : Boolean = true);
  85. Destructor Destroy; override;
  86. Procedure Lock;
  87. Procedure Unlock;
  88. Procedure FreeConnection;
  89. Property Connection : TSQLConnection Read FConnection;
  90. Property LastUsed : TDateTime Read FLastUsed Write FLastUsed;
  91. Property Locked : Boolean Read FLocked;
  92. end;
  93. { TSQLConnectionHelper }
  94. TSQLConnectionHelper = class helper for TSQLConnection
  95. Function GetDescription(Full : Boolean) : string;
  96. end;
  97. { TConnectionList }
  98. TConnectionList = Class (TFPObjectList)
  99. Private
  100. FonLog: TPoolLogEvent;
  101. FDisconnectTimeout: Integer;
  102. FLock : TCriticalSection;
  103. Protected
  104. Procedure Dolog(Const Msg : String);
  105. Procedure DoLog(Const Fmt : String; Args : Array of const);
  106. Function DoDisconnectOld(aTimeOut : Integer = -1) : Integer; virtual;
  107. function CreatePoolData(aConnection : TSQLConnection; aLocked : Boolean = True) : TConnectionPoolData;
  108. Public
  109. Constructor Create; reintroduce;
  110. Destructor Destroy; override;
  111. Procedure DisconnectAll;
  112. Function DisconnectOld(aTimeOut : Integer = -1) : Integer;
  113. function AddConnection (aConnection : TSQLConnection; aLocked : Boolean = True) : TConnectionPoolData;
  114. Function PopConnection : TSQLConnection;
  115. Function UnlockConnection(aConnection : TSQLConnection) : boolean;
  116. Property DisconnectTimeout : Integer Read FDisconnectTimeout Write FDisconnectTimeout;
  117. Property OnLog : TPoolLogEvent Read FonLog Write FOnLog;
  118. end;
  119. { TSQLDBConnectionPool }
  120. TSQLDBConnectionPool = class(TComponent)
  121. private
  122. FonLog: TPoolLogEvent;
  123. FPool : TFPObjectHashTable;
  124. FLock : TCriticalSection;
  125. procedure DisconnectAll;
  126. function GetCount: longword;
  127. protected
  128. Function CreateList : TConnectionList; virtual;
  129. Procedure Dolog(Const Msg : String);
  130. Procedure DoLog(Const Fmt : String; Args : Array of const);
  131. procedure Lock;
  132. procedure Unlock;
  133. function CreateKey(aDef : TSQLDBConnectionDef) : String; virtual;
  134. function CreateDef: TSQLDBConnectionDef;
  135. function DoFindConnection(const aConnectionDef: TSQLDBConnectionDef): TSQLConnection; virtual;
  136. procedure DoDisconnect(Item: TObject; const Key: string; var Continue: Boolean);
  137. public
  138. Constructor Create(aOwner : TComponent); override;
  139. Destructor Destroy; override;
  140. function CountConnections(aClass : TSQLConnectionClass; const aDatabaseName,aHostName,aUserName,aPassword: string; aParams:TStrings = nil):Integer;
  141. function CountConnections(aInstance : TSQLConnection):Integer;
  142. function CountConnections(aDef : TSQLDBConnectionDef):Integer;
  143. Function CountAllConnections : Integer;
  144. function FindConnection(aClass : TSQLConnectionClass; const aDatabaseName,aHostName,aUserName,aPassword: string; aParams:TStrings = nil):TSQLConnection;
  145. function FindConnection(const aConnectionDef : TSQLDBConnectionDef):TSQLConnection;
  146. procedure AddConnection(aConnection: TSQLConnection; aLocked: Boolean=True);
  147. function ReleaseConnection(aConnection: TSQLConnection) : Boolean;
  148. Property OnLog : TPoolLogEvent Read FonLog Write FOnLog;
  149. end;
  150. { TTypedConnectionPool }
  151. Generic TTypedConnectionPool<T: TSQLConnection> = class(TSQLDBConnectionPool)
  152. public
  153. function FindConnection(const aDatabaseName:string; const aHostName:string; const aUserName:string; const aPassword:string; aParams:TStrings=nil):T; overload;
  154. end;
  155. { TSQLDBConnectionDefList }
  156. TSQLDBConnectionDefList = Class(TOwnedCollection)
  157. private
  158. function GetD(aIndex : Integer): TSQLDBConnectionDef;
  159. procedure SetD(aIndex : Integer; AValue: TSQLDBConnectionDef);
  160. Public
  161. Function IndexOf(const aName : UTF8String) : Integer;
  162. Function Find(const aName : UTF8String) : TSQLDBConnectionDef;
  163. Function Get(const aName : UTF8String) : TSQLDBConnectionDef;
  164. Property Definitions[aIndex : Integer] : TSQLDBConnectionDef Read GetD Write SetD; default;
  165. end;
  166. { TSQLDBConnectionmanager }
  167. TSQLDBConnectionmanager = Class(TComponent)
  168. private
  169. FConnectionOwner: TComponent;
  170. FDefinitions: TSQLDBConnectionDefList;
  171. FMaxDBConnections: Word;
  172. FMaxTotalConnections: Cardinal;
  173. FOnLog: TPoolLogEvent;
  174. FPool : TSQLDBConnectionPool;
  175. FMyPool : TSQLDBConnectionPool;
  176. FLogEvents : TDBEventTypes;
  177. procedure SetConnectionOwner(AValue: TComponent);
  178. procedure SetDefinitions(AValue: TSQLDBConnectionDefList);
  179. procedure SetOnLog(AValue: TPoolLogEvent);
  180. procedure SetPool(AValue: TSQLDBConnectionPool);
  181. Protected
  182. Procedure DoLog(const Msg : String);
  183. Procedure DoLog(const Fmt : String; const aArgs : Array of const);
  184. function NewConnectionAllowed(aDef: TSQLDBConnectionDef; out aReason: string): Boolean; virtual;
  185. Procedure Notification(AComponent: TComponent; Operation: TOperation); override;
  186. Function CreatePool : TSQLDBConnectionPool; virtual;
  187. Function CreateDefinitionList : TSQLDBConnectionDefList; virtual;
  188. Public
  189. Constructor Create(aOwner : TComponent); override;
  190. Destructor Destroy; override;
  191. Function CreateConnection(const aDef : TSQLDBConnectionDef; addToPool : Boolean) : TSQLConnection;
  192. Function CreateConnection(const aName : string; addToPool : Boolean) : TSQLConnection;
  193. Function GetConnection(const aDef : TSQLDBConnectionDef) : TSQLConnection;
  194. Function GetConnection(const aName : string) : TSQLConnection;
  195. Function ReleaseConnection(aConnection : TSQLConnection) : Boolean;
  196. Published
  197. Property Pool : TSQLDBConnectionPool Read FPool Write SetPool;
  198. Property Definitions : TSQLDBConnectionDefList Read FDefinitions Write SetDefinitions;
  199. Property MaxDBConnections : Word Read FMaxDBConnections Write FMaxDBConnections;
  200. Property MaxTotalConnections : Cardinal Read FMaxTotalConnections Write FMaxTotalConnections;
  201. Property ConnectionOwner : TComponent Read FConnectionOwner Write SetConnectionOwner;
  202. Property OnLog : TPoolLogEvent Read FOnLog Write SetOnLog;
  203. Property LogEvents : TDBEventTypes Read FLogEvents Write FLogEvents;
  204. end;
  205. implementation
  206. uses typinfo, dateutils;
  207. Resourcestring
  208. SFindingConnection = 'Finding Connection (%s)';
  209. SFoundConnection = 'Found Connection (%s) : %x';
  210. SNoSuchConnection = 'No such Connection (%s)';
  211. SErrorDisconnecting = 'Error %s disconnecting connections : %s';
  212. SCreatingNewConnection = 'Creating new connection for connection definition (%s)';
  213. STimeoutReached = 'Timeout (%d>%d) reached, freeing connection (%s)';
  214. SReleasingConnections = 'Releasing connections (%s) (Current count: %d)';
  215. SErrCannotCreateNewConnection = 'Cannot create new connection for (%s): %s';
  216. SErrMaxNumberOfDefConnections = 'Max number of connections (%d) for this connection (%s) is reached';
  217. SErrMaxTotalConnectionReached = 'Max total number of connections (%d) is reached';
  218. SErrFreeingConnection = 'Error %s freeing connection %d : %s';
  219. { TSQLConnectionHelper }
  220. function TSQLConnectionHelper.GetDescription(Full: Boolean): string;
  221. Procedure AddTo(const aName,aValue : String);
  222. begin
  223. if aValue='' then
  224. exit;
  225. if Result<>'' then
  226. Result:=Result+', ';
  227. Result:=Result+aName+': '+aValue;
  228. end;
  229. var
  230. aPort : integer;
  231. begin
  232. Result:='';
  233. AddTo('Name',Name);
  234. AddTo('Host',HostName);
  235. AddTo('Database',DatabaseName);
  236. AddTo('User',Username);
  237. AddTo('Charset',CharSet);
  238. if IsPublishedProp(Self,'Port') then
  239. if PropIsType(Self,'Port',tkInteger) then
  240. begin
  241. aPort:=GetOrdProp(Self,'Port');
  242. if aPort>0 then
  243. AddTo('Port',IntToStr(aPort));
  244. end;
  245. if Full then
  246. begin
  247. AddTo('Password',Password);
  248. if Params.Count>0 then
  249. AddTo('Params',Params.CommaText);
  250. end;
  251. end;
  252. { TSQLDBConnectionDefList }
  253. function TSQLDBConnectionDefList.GetD(aIndex : Integer): TSQLDBConnectionDef;
  254. begin
  255. Result:=TSQLDBConnectionDef(Items[aIndex])
  256. end;
  257. procedure TSQLDBConnectionDefList.SetD(aIndex : Integer; AValue: TSQLDBConnectionDef
  258. );
  259. begin
  260. Items[aIndex]:=aValue;
  261. end;
  262. function TSQLDBConnectionDefList.IndexOf(const aName: UTF8String): Integer;
  263. begin
  264. Result:=Count-1;
  265. While (Result>=0) and not SameText(aName,GetD(Result).Name) do
  266. Dec(Result);
  267. end;
  268. function TSQLDBConnectionDefList.Find(const aName: UTF8String): TSQLDBConnectionDef;
  269. Var
  270. Idx : Integer;
  271. begin
  272. Result:=Nil;
  273. Idx:=IndexOf(aName);
  274. if Idx<>-1 then
  275. Result:=GetD(Idx);
  276. end;
  277. function TSQLDBConnectionDefList.Get(const aName: UTF8String): TSQLDBConnectionDef;
  278. begin
  279. Result:=Find(aName);
  280. if Result=Nil then
  281. end;
  282. { TSQLDBConnectionDef }
  283. procedure TSQLDBConnectionDef.DoChange(Sender: TObject);
  284. begin
  285. ClearKey;
  286. end;
  287. procedure TSQLDBConnectionDef.ClearKey;
  288. begin
  289. FKey:='';
  290. end;
  291. function TSQLDBConnectionDef.GetName: UTF8String;
  292. begin
  293. Result:=FName;
  294. end;
  295. function TSQLDBConnectionDef.GetPort: Word;
  296. begin
  297. Result:=StrToIntDef(FParams.Values['port'],0);
  298. end;
  299. procedure TSQLDBConnectionDef.SetCharSet(AValue: UTF8String);
  300. begin
  301. FCharSet :=aValue;
  302. ClearKey;
  303. end;
  304. procedure TSQLDBConnectionDef.SetConnectionType(AValue: String);
  305. Var
  306. Def : TConnectionDef;
  307. begin
  308. if FConnectionType=AValue then Exit;
  309. FConnectionType:=AValue;
  310. if FConnectionType<>'' then
  311. begin
  312. Def:=GetConnectionDef(aValue);
  313. if Def<>Nil then
  314. ConnectionClass:=Def.ConnectionClass
  315. else
  316. ConnectionClass:=TSQLConnector;
  317. end
  318. else
  319. ConnectionClass:=Nil;
  320. end;
  321. procedure TSQLDBConnectionDef.SetDatabaseName(AValue: UTF8String);
  322. begin
  323. if FDatabaseName=AValue then Exit;
  324. FDatabaseName:=AValue;
  325. ClearKey;
  326. end;
  327. procedure TSQLDBConnectionDef.SetHostName(AValue: UTF8String);
  328. begin
  329. if FHostName=AValue then Exit;
  330. FHostName:=AValue;
  331. ClearKey;
  332. end;
  333. procedure TSQLDBConnectionDef.SetParams(AValue: TStrings);
  334. begin
  335. FParams.Assign(aValue);
  336. ClearKey;
  337. end;
  338. procedure TSQLDBConnectionDef.SetPassword(AValue: UTF8string);
  339. begin
  340. if FPassword=AValue then Exit;
  341. FPassword:=AValue;
  342. ClearKey;
  343. end;
  344. procedure TSQLDBConnectionDef.SetPort(AValue: Word);
  345. begin
  346. if aValue=0 then
  347. FParams.Values['port']:=''
  348. else
  349. FParams.Values['port']:=IntToStr(aValue)
  350. end;
  351. procedure TSQLDBConnectionDef.SetRole(AValue: UTF8String);
  352. begin
  353. if FRole=AValue then Exit;
  354. FRole:=AValue;
  355. ClearKey;
  356. end;
  357. procedure TSQLDBConnectionDef.SetUserName(AValue: UTF8String);
  358. begin
  359. if FUserName=AValue then Exit;
  360. FUserName:=AValue;
  361. ClearKey;
  362. end;
  363. procedure TSQLDBConnectionDef.AssignTo(Dest: TPersistent);
  364. var
  365. Conn : TSQLConnection absolute Dest;
  366. begin
  367. if Dest is TSQLDBConnectionDef then
  368. Dest.Assign(Self)
  369. else if Dest is TSQLConnection then
  370. begin
  371. Conn.DatabaseName := FDatabaseName;
  372. Conn.HostName := FHostName;
  373. Conn.Password := FPassword;
  374. Conn.UserName := FUserName;
  375. Conn.Role:=FRole;
  376. Conn.CharSet:=FCharSet;
  377. Conn.Params.Assign(Self.Params);
  378. if Conn is TSQLConnector then
  379. TSQLConnector(Conn).ConnectorType:=Self.ConnectionType;
  380. end
  381. else
  382. inherited AssignTo(Dest);
  383. end;
  384. function TSQLDBConnectionDef.GetDisplayName: string;
  385. begin
  386. Result:=Name;
  387. end;
  388. function TSQLDBConnectionDef.CreateKey: String;
  389. Var
  390. S : TStringList;
  391. N : String;
  392. begin
  393. if FKey<>'' then
  394. Exit(FKey);
  395. if Assigned(ConnectionClass) then
  396. N:=ConnectionClass.ClassName
  397. else
  398. N:=TSQLConnector.ClassName+'.'+ConnectionType;
  399. Result:=N
  400. +'#@'+HostName
  401. +'#@'+DatabaseName
  402. +'#@'+UserName
  403. +'#@'+Password
  404. +'#@'+Role
  405. +'#@'+CharSet;
  406. If Assigned(Params) then
  407. begin
  408. // Canonicalize
  409. S:=TStringList.Create;
  410. try
  411. S.Sorted:=true;
  412. S.AddStrings(Params);
  413. Result:=Result+'#@'+S.Text;
  414. finally
  415. S.Free;
  416. end;
  417. end;
  418. FKey:=Result;
  419. end;
  420. constructor TSQLDBConnectionDef.Create(ACollection: TCollection);
  421. begin
  422. inherited Create(ACollection);
  423. FParams:=TStringList.Create;
  424. TStringList(FParams).OnChange:=@DoChange;
  425. FEnabled:=True;
  426. end;
  427. destructor TSQLDBConnectionDef.Destroy;
  428. begin
  429. FParams.Free;
  430. inherited Destroy;
  431. end;
  432. procedure TSQLDBConnectionDef.Assign(Source: TPersistent);
  433. Var
  434. Def : TSQLDBConnectionDef absolute source;
  435. Conn : TSQLConnection absolute source;
  436. begin
  437. if Source is TSQLDBConnectionDef then
  438. begin
  439. FConnectionType:=Def.ConnectionType;
  440. FDatabaseName:=Def.DatabaseName;
  441. FHostName:=Def.HostName;
  442. FPassword:=Def.Password;
  443. FUserName:=Def.UserName;
  444. FName:=Def.Name;
  445. FCharSet:=Def.CharSet;
  446. FParams.Assign(Def.Params);
  447. FEnabled:=Def.Enabled;
  448. ClearKey;
  449. end
  450. else if Source is TSQLConnection then
  451. begin
  452. if Conn is TSQLConnector then
  453. FConnectionType:=TSQLConnector(Conn).ConnectorType
  454. else
  455. FConnectionClass:=TSQLConnectionClass(Conn.ClassType);
  456. FDatabaseName:=Conn.DatabaseName;
  457. FHostName:=Conn.HostName;
  458. FPassword:=Conn.Password;
  459. FUserName:=Conn.UserName;
  460. FName:='';
  461. FCharSet:=Conn.CharSet;
  462. FParams.Assign(Conn.Params);
  463. FEnabled:=Def.Enabled;
  464. ClearKey;
  465. end
  466. else
  467. inherited Assign(Source);
  468. end;
  469. function TSQLDBConnectionDef.GetDescription(Full : Boolean = False) : string;
  470. Procedure AddTo(const aName,aValue : String);
  471. begin
  472. if aValue='' then
  473. exit;
  474. if Result<>'' then
  475. Result:=Result+', ';
  476. Result:=Result+aName+': '+aValue;
  477. end;
  478. begin
  479. Result:='';
  480. AddTo('Name',Name);
  481. AddTo('Host',HostName);
  482. AddTo('Database',DatabaseName);
  483. AddTo('User',Username);
  484. AddTo('Charset',CharSet);
  485. if Port>0 then
  486. AddTo('Port',IntToStr(Port));
  487. if Full then
  488. begin
  489. AddTo('Password',Password);
  490. if Params.Count>0 then
  491. AddTo('Params',Params.CommaText);
  492. end;
  493. end;
  494. function TSQLDBConnectionDef.ToString: string;
  495. begin
  496. Result:=GetDescription;
  497. end;
  498. { TSQLDBConnectionmanager }
  499. procedure TSQLDBConnectionmanager.SetConnectionOwner(AValue: TComponent);
  500. begin
  501. if FConnectionOwner=AValue then Exit;
  502. if Assigned(FConnectionOwner) then
  503. FConnectionOwner.RemoveFreeNotification(Self);
  504. FConnectionOwner:=AValue;
  505. if Assigned(FConnectionOwner) then
  506. FConnectionOwner.FreeNotification(Self);
  507. end;
  508. procedure TSQLDBConnectionmanager.SetDefinitions(AValue: TSQLDBConnectionDefList);
  509. begin
  510. if FDefinitions=AValue then
  511. Exit;
  512. FDefinitions.Assign(AValue);
  513. end;
  514. procedure TSQLDBConnectionmanager.SetOnLog(AValue: TPoolLogEvent);
  515. begin
  516. if FOnLog=AValue then Exit;
  517. FOnLog:=AValue;
  518. if Assigned(FMyPool) then
  519. FMyPool.OnLog:=aValue;
  520. end;
  521. procedure TSQLDBConnectionmanager.SetPool(AValue: TSQLDBConnectionPool);
  522. begin
  523. if FPool=AValue then Exit;
  524. FPool:=AValue;
  525. if (FPool=Nil) then
  526. FPool:=FMyPool;
  527. end;
  528. procedure TSQLDBConnectionmanager.DoLog(const Msg: String);
  529. begin
  530. if Assigned(OnLog) then
  531. OnLog(Self,Msg);
  532. end;
  533. procedure TSQLDBConnectionmanager.DoLog(const Fmt: String;
  534. const aArgs: array of const);
  535. begin
  536. DoLog(Format(Fmt,aArgs));
  537. end;
  538. procedure TSQLDBConnectionmanager.Notification(AComponent: TComponent;
  539. Operation: TOperation);
  540. begin
  541. if (Operation=opRemove) then
  542. if (aComponent=FConnectionOwner) then
  543. FConnectionOwner:=Nil
  544. else
  545. begin
  546. if (aComponent=FMyPool) then
  547. FMyPool:=Nil;
  548. if (aComponent=FPool) then
  549. FPool:=Nil;
  550. end;
  551. inherited Notification(AComponent, Operation);
  552. end;
  553. constructor TSQLDBConnectionmanager.Create(aOwner: TComponent);
  554. begin
  555. inherited Create(aOwner);
  556. FMyPool:=CreatePool;
  557. FMyPool.SetSubComponent(True);
  558. FDefinitions:=CreateDefinitionList;
  559. FPool:=FMyPool;
  560. FLogEvents:=LogAllEvents;
  561. end;
  562. destructor TSQLDBConnectionmanager.Destroy;
  563. begin
  564. FreeAndNil(FPool);
  565. FreeAndNil(FDefinitions);
  566. inherited Destroy;
  567. end;
  568. function TSQLDBConnectionmanager.CreateConnection(const aDef: TSQLDBConnectionDef; addToPool: Boolean): TSQLConnection;
  569. var
  570. C : TSQLConnectionClass;
  571. begin
  572. C:=aDef.ConnectionClass;
  573. if (C=Nil) and (aDef.ConnectionType<>'') then
  574. C:=TSQLConnector;
  575. With aDef do
  576. DoLog(SCreatingNewConnection, [GetDescription]);
  577. Result:=C.Create(Self.ConnectionOwner);
  578. try
  579. aDef.AssignTo(Result);
  580. Result.LogEvents:=Self.LogEvents;
  581. Result.Transaction:=TSQLTransaction.Create(Result);
  582. except
  583. Result.Free;
  584. Raise;
  585. end;
  586. if AddToPool then
  587. Pool.AddConnection(Result);
  588. end;
  589. function TSQLDBConnectionmanager.CreatePool : TSQLDBConnectionPool;
  590. begin
  591. Result:=TSQLDBConnectionPool.Create(Self);
  592. end;
  593. function TSQLDBConnectionmanager.CreateDefinitionList: TSQLDBConnectionDefList;
  594. begin
  595. Result:=TSQLDBConnectionDefList.Create(Self,TSQLDBConnectionDef);
  596. end;
  597. function TSQLDBConnectionmanager.CreateConnection(const aName: string;
  598. addToPool: Boolean): TSQLConnection;
  599. begin
  600. Result:=CreateConnection(Definitions.Get(aName),addToPool);
  601. end;
  602. function TSQLDBConnectionmanager.NewConnectionAllowed(aDef: TSQLDBConnectionDef; out aReason: string): Boolean;
  603. Var
  604. N: Integer;
  605. begin
  606. Result:=True;
  607. if (MaxDBConnections>0) then
  608. begin
  609. N:=FPool.CountConnections(aDef);
  610. if (N>MaxDBConnections) then
  611. AReason:=Format(SErrMaxNumberOfDefConnections, [MaxDBConnections, aDef.GetDescription(False)]);
  612. end;
  613. if (MaxTotalConnections>0) then
  614. begin
  615. N:=FPool.CountAllConnections;
  616. if (N>MaxDBConnections) then
  617. aReason:=Format(SErrMaxTotalConnectionReached, [MaxDBConnections]);
  618. end;
  619. Result:=aReason='';
  620. end;
  621. function TSQLDBConnectionmanager.GetConnection(const aDef: TSQLDBConnectionDef ): TSQLConnection;
  622. Var
  623. aReason,aErr : String;
  624. begin
  625. Result:=FPool.FindConnection(aDef);
  626. if Result=Nil then
  627. begin
  628. if Not NewConnectionAllowed(aDef,aReason) then
  629. begin
  630. aErr:=Format(SErrCannotCreateNewConnection, [aDef.GetDescription, aReason]);
  631. DoLog(aErr);
  632. Raise ESQLDBPool.Create(aErr);
  633. end;
  634. Result:=CreateConnection(aDef,True);
  635. end;
  636. end;
  637. function TSQLDBConnectionmanager.GetConnection(const aName: string
  638. ): TSQLConnection;
  639. begin
  640. Result:=GetConnection(Definitions.Get(aName));
  641. end;
  642. function TSQLDBConnectionmanager.ReleaseConnection(aConnection: TSQLConnection
  643. ): Boolean;
  644. begin
  645. Result:=FPool.ReleaseConnection(aConnection);
  646. end;
  647. { TConnectionPoolData }
  648. constructor TConnectionPoolData.Create(aConnection: TSQLConnection; aLocked : Boolean = true);
  649. begin
  650. FConnection:=aConnection;
  651. LastUsed:=Now;
  652. Flocked:=aLocked;
  653. end;
  654. destructor TConnectionPoolData.Destroy;
  655. begin
  656. inherited Destroy;
  657. end;
  658. procedure TConnectionPoolData.Lock;
  659. begin
  660. FLocked:=True;
  661. FLastUsed:=Now;
  662. end;
  663. procedure TConnectionPoolData.Unlock;
  664. begin
  665. FLocked:=False;
  666. FLastUsed:=Now;
  667. end;
  668. procedure TConnectionPoolData.FreeConnection;
  669. Var
  670. TR : TSQLTransaction;
  671. begin
  672. try
  673. TR:=Connection.Transaction;
  674. Connection.Transaction:=Nil;
  675. TR.Free;
  676. Connection.Connected:=False;
  677. finally
  678. FreeAndNil(FConnection);
  679. end;
  680. end;
  681. { TTypedConnectionPool }
  682. function TTypedConnectionPool.FindConnection(const aDatabaseName: string;
  683. const aHostName: string; const aUserName: string; const aPassword: string;
  684. aParams: TStrings): T;
  685. begin
  686. Result:=T(Inherited FindConnection(T,aDatabaseName,aHostName,aUserName,aPassword,aParams));
  687. end;
  688. { TPQConnPool }
  689. (*
  690. generic function TTypedConnectionPool<T : TSQLConnection>.FindConnection(const aDatabaseName: string; const aHostName: string;
  691. const aUserName: string; const aPassword: string; aParams: TStrings = Nil): T;
  692. begin
  693. result:=T(FindConnection(T,aDatabaseName,aHostName,aPassword,aUserName,aParams));
  694. end;
  695. *)
  696. { TConnectionList }
  697. constructor TConnectionList.Create;
  698. begin
  699. Inherited Create;
  700. FLock:=TCriticalSection.Create;
  701. FDisconnectTimeout:=DefaultDisconnectTimeout;
  702. end;
  703. destructor TConnectionList.Destroy;
  704. begin
  705. FreeAndNil(FLock);
  706. inherited Destroy;
  707. end;
  708. procedure TConnectionList.DisconnectAll;
  709. Var
  710. I : integer;
  711. CD : TConnectionPoolData;
  712. begin
  713. FLock.Enter;
  714. try
  715. For I:=Count-1 downto 0 do
  716. begin
  717. CD:=TConnectionPoolData(Items[i]);
  718. if (not CD.Locked) then
  719. begin
  720. CD.FreeConnection;
  721. Delete(I);
  722. end;
  723. end;
  724. finally
  725. FLock.Leave;
  726. end;
  727. end;
  728. procedure TConnectionList.Dolog(const Msg: String);
  729. begin
  730. If Assigned(OnLog) then
  731. OnLog(Self,Msg);
  732. end;
  733. procedure TConnectionList.DoLog(const Fmt: String; Args: array of const);
  734. begin
  735. DoLog(Format(Fmt,args));
  736. end;
  737. function TConnectionList.DoDisconnectOld(aTimeOut: Integer = -1): Integer;
  738. Var
  739. secs,I : integer;
  740. CD : TConnectionPoolData;
  741. N : TDateTime;
  742. begin
  743. Result:=0;
  744. N:=Now;
  745. if aTimeout<0 then
  746. aTimeout:=FDisconnectTimeout;
  747. for I:=Count-1 downto 0 do
  748. begin
  749. CD:=TConnectionPoolData(Items[i]);
  750. Secs:=SecondsBetween(N,CD.LastUsed);
  751. if (not CD.Locked) and (Secs>aTimeout) then
  752. begin
  753. With CD.Connection do
  754. DoLog(STimeoutReached, [Secs, aTimeout, GetDescription(False)]);
  755. try
  756. CD.FreeConnection;
  757. except
  758. on E : Exception do
  759. DoLog(SErrFreeingConnection, [E.ClassName, I, E.Message]);
  760. end;
  761. Delete(I);
  762. Inc(Result);
  763. end;
  764. end;
  765. end;
  766. function TConnectionList.CreatePoolData(aConnection: TSQLConnection;
  767. aLocked: Boolean): TConnectionPoolData;
  768. begin
  769. Result:=TConnectionPoolData.Create(aConnection,aLocked);
  770. end;
  771. function TConnectionList.DisconnectOld(aTimeOut: Integer): Integer;
  772. begin
  773. FLock.Enter;
  774. try
  775. Result:=DoDisconnectOld(aTimeout);
  776. finally
  777. FLock.Leave;
  778. end;
  779. end;
  780. function TConnectionList.AddConnection(aConnection: TSQLConnection; aLocked: Boolean
  781. ): TConnectionPoolData;
  782. begin
  783. FLock.Enter;
  784. try
  785. Result:=CreatePoolData(aConnection,aLocked);
  786. Add(Result);
  787. finally
  788. FLock.Leave;
  789. end;
  790. end;
  791. function TConnectionList.PopConnection: TSQLConnection;
  792. Var
  793. i : integer;
  794. CD : TConnectionPoolData;
  795. begin
  796. Result:=nil;
  797. FLock.Enter;
  798. try
  799. DoDisconnectOld;
  800. I:=0;
  801. While (Result=Nil) and (I<Count) do
  802. begin
  803. CD:=TConnectionPoolData(Items[i]);
  804. if not CD.Locked then
  805. begin
  806. CD.Lock;
  807. Result:=CD.Connection;
  808. end;
  809. Inc(I);
  810. end;
  811. finally
  812. Flock.Leave;
  813. end;
  814. end;
  815. function TConnectionList.UnlockConnection(aConnection: TSQLConnection): boolean;
  816. Var
  817. I : Integer;
  818. Data : TConnectionPoolData;
  819. begin
  820. Result:=False;
  821. FLock.Enter;
  822. try
  823. I:=Count-1;
  824. Data:=Nil;
  825. While (Data=Nil) and (I>=0) do
  826. begin
  827. Data:=TConnectionPoolData(Items[i]);
  828. if Data.Connection<>aConnection then
  829. Data:=Nil;
  830. Dec(i);
  831. end;
  832. if Assigned(Data) then
  833. begin
  834. Data.Unlock;
  835. Result:=True;
  836. end;
  837. finally
  838. FLock.Leave;
  839. end;
  840. IndexOf(aConnection)
  841. end;
  842. { TSQLDBConnectionPool }
  843. function TSQLDBConnectionPool.GetCount: longword;
  844. begin
  845. Result:=FPool.Count;
  846. end;
  847. function TSQLDBConnectionPool.CreateList: TConnectionList;
  848. begin
  849. Result:=TConnectionList.Create;
  850. end;
  851. procedure TSQLDBConnectionPool.Dolog(const Msg: String);
  852. begin
  853. If Assigned(OnLog) then
  854. OnLog(Self,Msg);
  855. end;
  856. procedure TSQLDBConnectionPool.DoLog(const Fmt: String; Args: array of const);
  857. begin
  858. DoLog(Format(Fmt,args));
  859. end;
  860. procedure TSQLDBConnectionPool.Lock;
  861. begin
  862. Flock.Enter;
  863. end;
  864. procedure TSQLDBConnectionPool.Unlock;
  865. begin
  866. Flock.Leave;
  867. end;
  868. function TSQLDBConnectionPool.CreateKey(aDef: TSQLDBConnectionDef): String;
  869. begin
  870. Result:=aDef.CreateKey;
  871. end;
  872. function TSQLDBConnectionPool.CreateDef : TSQLDBConnectionDef;
  873. begin
  874. Result:=TSQLDBConnectionDef.Create(Nil);
  875. end;
  876. function TSQLDBConnectionPool.FindConnection(aClass : TSQLConnectionClass; const aDatabaseName, aHostName,
  877. aUserName, aPassword: string; aParams: TStrings): TSQLConnection;
  878. Var
  879. Def : TSQLDBConnectionDef;
  880. begin
  881. Result:=nil;
  882. Def:=CreateDef;
  883. try
  884. Def.ConnectionClass:=aClass;
  885. Def.DatabaseName:=aDatabaseName;
  886. Def.HostName:=aHostName;
  887. Def.UserName:=aUserName;
  888. Def.Password:=aPassword;
  889. if Assigned(aParams) then
  890. Def.Params:=aParams;
  891. Result:=FindConnection(Def);
  892. finally
  893. Def.Free;
  894. end;
  895. end;
  896. function TSQLDBConnectionPool.FindConnection(const aConnectionDef: TSQLDBConnectionDef): TSQLConnection;
  897. Var
  898. N : String;
  899. begin
  900. Result:=nil;
  901. with aConnectionDef do
  902. begin
  903. N:=ConnectionType;
  904. if (N='') and Assigned(ConnectionClass) then
  905. N:=ConnectionClass.ClassName;
  906. DoLog(SFindingConnection,[GetDescription]);
  907. Result:=DoFindConnection(aConnectionDef);
  908. If (Result=Nil) then
  909. DoLog(SNoSuchConnection,[GetDescription])
  910. else
  911. DoLog(SFoundConnection,[GetDescription, PtrInt(Result)])
  912. end;
  913. end;
  914. function TSQLDBConnectionPool.DoFindConnection(const aConnectionDef: TSQLDBConnectionDef): TSQLConnection;
  915. Var
  916. Key : String;
  917. L : TConnectionList;
  918. begin
  919. Result:=Nil;
  920. Key:=CreateKey(aConnectionDef);
  921. Lock;
  922. try
  923. L:=TConnectionList(FPool.Items[Key]);
  924. if L=Nil then
  925. Exit;
  926. Result:=L.PopConnection;
  927. finally
  928. Unlock;
  929. end;
  930. end;
  931. (*
  932. result:=TSQLConnection(FPool[key]);
  933. if result=nil then
  934. begin
  935. result:=CreateConn(AOwner);
  936. result.HostName:=GetFirstNonNull(sHostName,FHostName);
  937. // Force local connection
  938. if result.HostName=MyServerName then
  939. Result.HostName:='';
  940. result.DatabaseName:=GetFirstNonNull(sDatabaseName,FDatabaseName);
  941. result.UserName:=GetFirstNonNull(sUserName,FUserName);
  942. result.Password:=GetFirstNonNull(sPassword,FPassword);
  943. result.Params:=GetFirstNonNull(ssParams,FParams);
  944. result.CharSet:='UTF8';
  945. if not CreateDisconnected then
  946. Result.Open;
  947. FPool.Add(key,result);
  948. end;
  949. end;
  950. *)
  951. procedure TSQLDBConnectionPool.DoDisconnect(Item: TObject; const Key: string;
  952. var Continue: Boolean);
  953. Var
  954. L : TConnectionList absolute item;
  955. begin
  956. Continue:=True;
  957. try
  958. L.DisconnectOld();
  959. except
  960. on E : Exception do
  961. DoLog(SErrorDisconnecting,[E.ClassName,E.Message]);
  962. end;
  963. end;
  964. procedure TSQLDBConnectionPool.DisconnectAll;
  965. begin
  966. Lock;
  967. try
  968. FPool.Iterate(@DoDisconnect);
  969. finally
  970. UnLock;
  971. end;
  972. end;
  973. destructor TSQLDBConnectionPool.Destroy;
  974. begin
  975. FLock.Free;
  976. FPool.Destroy;
  977. inherited Destroy;
  978. end;
  979. function TSQLDBConnectionPool.CountConnections(aClass: TSQLConnectionClass;
  980. const aDatabaseName, aHostName, aUserName, aPassword: string;
  981. aParams: TStrings): Integer;
  982. Var
  983. Def : TSQLDBConnectionDef;
  984. begin
  985. Result:=0;
  986. Def:=CreateDef;
  987. try
  988. Def.ConnectionClass:=aClass;
  989. Def.DatabaseName:=aDatabaseName;
  990. Def.HostName:=aHostName;
  991. Def.UserName:=aUserName;
  992. Def.Password:=aPassword;
  993. if Assigned(aParams) then
  994. Def.Params:=aParams;
  995. Result:=CountConnections(Def);
  996. finally
  997. Def.Free;
  998. end;
  999. end;
  1000. function TSQLDBConnectionPool.CountConnections(aInstance: TSQLConnection): Integer;
  1001. begin
  1002. With aInstance do
  1003. Result:=CountConnections(TSQLConnectionClass(ClassType),DatabaseName,HostName,UserName,Password,Params);
  1004. end;
  1005. function TSQLDBConnectionPool.CountConnections(aDef: TSQLDBConnectionDef): Integer;
  1006. Var
  1007. Key : String;
  1008. L : TConnectionList;
  1009. begin
  1010. Key:=CreateKey(aDef);
  1011. Lock;
  1012. try
  1013. L:=TConnectionList(FPool.Items[Key]);
  1014. if L<>Nil then
  1015. Result:=L.Count;
  1016. finally
  1017. UnLock;
  1018. end;
  1019. end;
  1020. Type
  1021. { TConnectionCounter }
  1022. TConnectionCounter = Class(TObject)
  1023. private
  1024. FCount : Integer;
  1025. Public
  1026. Procedure DoCount(Item: TObject; const Key: string; var Continue: Boolean);
  1027. Property Count : Integer Read FCount;
  1028. end;
  1029. { TConnectionCounter }
  1030. procedure TConnectionCounter.DoCount(Item: TObject; const Key: string; var Continue: Boolean);
  1031. begin
  1032. FCount:=FCount+(Item as TConnectionList).Count;
  1033. Continue:=True;
  1034. end;
  1035. function TSQLDBConnectionPool.CountAllConnections: Integer;
  1036. var
  1037. Counter : TConnectionCounter;
  1038. begin
  1039. Counter:=Nil;
  1040. Lock;
  1041. try
  1042. Counter:=TConnectionCounter.Create;
  1043. FPool.Iterate(@Counter.DoCount);
  1044. Result:=Counter.Count;
  1045. finally
  1046. Unlock;
  1047. Counter.Free;
  1048. end;
  1049. end;
  1050. procedure TSQLDBConnectionPool.AddConnection(aConnection: TSQLConnection; aLocked : Boolean = True);
  1051. Var
  1052. Key : String;
  1053. L : TConnectionList;
  1054. aDef: TSQLDBConnectionDef;
  1055. begin
  1056. aDef:=Nil;
  1057. Lock;
  1058. try
  1059. aDef:=CreateDef;
  1060. aDef.Assign(aConnection);
  1061. Key:=CreateKey(aDef);
  1062. L:=TConnectionList(FPool.Items[Key]);
  1063. if L=Nil then
  1064. begin
  1065. L:=CreateList;
  1066. L.FonLog:=Self.OnLog;
  1067. FPool.Add(Key,L);
  1068. end;
  1069. L.AddConnection(aConnection,aLocked);
  1070. finally
  1071. Unlock;
  1072. aDef.Free;
  1073. end;
  1074. end;
  1075. function TSQLDBConnectionPool.ReleaseConnection(aConnection: TSQLConnection): Boolean;
  1076. Var
  1077. Key : String;
  1078. L : TConnectionList;
  1079. aDef: TSQLDBConnectionDef;
  1080. begin
  1081. Result:=False;
  1082. aDef:=Nil;
  1083. Lock;
  1084. try
  1085. aDef:=CreateDef;
  1086. aDef.Assign(aConnection);
  1087. Key:=CreateKey(aDef);
  1088. L:=TConnectionList(FPool.Items[Key]);
  1089. if Assigned(L) then
  1090. begin
  1091. With aConnection do
  1092. DoLog(SReleasingConnections, [GetDescription(False), L.Count]);
  1093. Result:=L.UnlockConnection(aConnection);
  1094. end;
  1095. finally
  1096. Unlock;
  1097. aDef.Free;
  1098. end;
  1099. end;
  1100. constructor TSQLDBConnectionPool.Create(aOwner: TComponent);
  1101. begin
  1102. FPool:=TFPObjectHashTable.Create(True);
  1103. FLock:=TCriticalSection.Create;
  1104. end;
  1105. end.