AbstractDBConnection.cs 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. //
  2. // System.Data.Common.AbstractDBConnection
  3. //
  4. // Authors:
  5. // Konstantin Triger <[email protected]>
  6. // Boris Kirzner <[email protected]>
  7. //
  8. // (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Data;
  31. using System.Data.ProviderBase;
  32. using System.Data.Configuration;
  33. using System.Configuration;
  34. using System.Collections;
  35. using System.Collections.Specialized;
  36. using System.Text;
  37. using System.Text.RegularExpressions;
  38. using System.Data.Common;
  39. using java.sql;
  40. using javax.sql;
  41. using javax.naming;
  42. // can not use java.util here - it manes ArrayList an ambiguous reference
  43. namespace System.Data.ProviderBase
  44. {
  45. public abstract class AbstractDBConnection : DbConnection
  46. {
  47. #region ObjectNamesHelper
  48. private sealed class ObjectNamesHelper
  49. {
  50. //static readonly Regex NameOrder = new Regex(@"^\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  51. static readonly Regex NameOrder = new Regex(@"^((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  52. //static readonly Regex SchemaNameOrder = new Regex(@"^\s*((\[(?<SCHEMA>(\s*[^\[\]\s])+)\s*\])|(?<SCHEMA>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  53. static readonly Regex SchemaNameOrder = new Regex(@"^((\[(?<SCHEMA>[^\]]+)\])|(?<SCHEMA>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  54. //static readonly Regex CatalogSchemaNameOrder = new Regex(@"^\s*((\[\s*(?<CATALOG>(\s*[^\[\]\s])+)\s*\])|(?<CATALOG>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<SCHEMA>(\s*[^\[\]\s])+)\s*\])|(?<SCHEMA>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  55. //static readonly Regex CatalogSchemaNameOrder = new Regex(@"^\s*((\[\s*(?<CATALOG>(\s*[^\]\s])+)\s*\])|(?<CATALOG>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<SCHEMA>(\s*[^\]\s])+)\s*\])|(?<SCHEMA>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<NAME>(\s*[^\]\s])+)\s*\])|(?<NAME>([^\.\s])+(\s*([^\.\s])+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  56. static readonly Regex CatalogSchemaNameOrder = new Regex(@"^((\[(?<CATALOG>[^\]]+)\])|(?<CATALOG>[^\.\[\]]+))\s*\.\s*((\[(?<SCHEMA>[^\]]+)\])|(?<SCHEMA>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  57. //static readonly Regex CatalogNameOrder = new Regex(@"^\s*((\[(?<CATALOG>(\s*[^\[\]\s])+)\s*\])|(?<CATALOG>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  58. //static readonly Regex CatalogNameOrder = new Regex(@"^\s*((\[(?<CATALOG>(\s*[^\]\s])+)\s*\])|(?<CATALOG>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<NAME>(\s*[^\]\s])+)\s*\])|(?<NAME>([^\.\s])+(\s*([^\.\s])+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  59. static readonly Regex CatalogNameOrder = new Regex(@"^((\[(?<CATALOG>[^\]]+)\])|(?<CATALOG>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  60. //static readonly Regex SchemaCatalogNameOrder = new Regex(@"^\s*((\[\s*(?<SCHEMA>(\s*[^\[\]\s])+)\s*\])|(?<SCHEMA>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<CATALOG>(\s*[^\[\]\s])+)\s*\])|(?<CATALOG>(\w|!|\#|\$)*(\s*(\w|!|\#|\$)+)*))\s*\.\s*((\[(?<NAME>(\s*[^\[\]\s])+)\s*\])|(?<NAME>(\w|!|\#|\$)+(\s*(\w|!|\#|\$)+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  61. //static readonly Regex SchemaCatalogNameOrder = new Regex(@"^\s*((\[\s*(?<SCHEMA>(\s*[^\]\s])+)\s*\])|(?<SCHEMA>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<CATALOG>(\s*[^\]\s])+)\s*\])|(?<CATALOG>([^\.\s])*(\s*([^\.\s])+)*))\s*\.\s*((\[(?<NAME>(\s*[^\]\s])+)\s*\])|(?<NAME>([^\.\s])+(\s*([^\.\s])+)*))\s*$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  62. static readonly Regex SchemaCatalogNameOrder = new Regex(@"^((\[(?<SCHEMA>[^\]]+)\])|(?<SCHEMA>[^\.\[\]]+))\s*\.\s*((\[(?<CATALOG>[^\]]+)\])|(?<CATALOG>[^\.\[\]]+))\s*\.\s*((\[(?<NAME>[^\]]+)\])|(?<NAME>[^\.\[\]]+))$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
  63. internal static ObjectNameResolver[] GetSyntaxPatterns(AbstractDBConnection connection)
  64. {
  65. ArrayList collection = new ArrayList();
  66. collection.Add(new ObjectNameResolver(NameOrder));
  67. ObjectNameResolversCollection basic = (ObjectNameResolversCollection)ConfigurationSettings.GetConfig("system.data/objectnameresolution");
  68. DatabaseMetaData metaData = connection.JdbcConnection.getMetaData();
  69. string productName = metaData.getDatabaseProductName();
  70. foreach(ObjectNameResolver nameResolver in basic) {
  71. if (productName.IndexOf(nameResolver.DbName) != -1) {
  72. collection.Add(nameResolver);
  73. }
  74. }
  75. //defaults
  76. if (metaData.isCatalogAtStart()) {
  77. collection.Add(new ObjectNameResolver(SchemaNameOrder));
  78. collection.Add(new ObjectNameResolver(CatalogNameOrder));
  79. collection.Add(new ObjectNameResolver(CatalogSchemaNameOrder));
  80. collection.Add(new ObjectNameResolver(SchemaCatalogNameOrder));
  81. }
  82. else {
  83. collection.Add(new ObjectNameResolver(CatalogNameOrder));
  84. collection.Add(new ObjectNameResolver(SchemaNameOrder));
  85. collection.Add(new ObjectNameResolver(SchemaCatalogNameOrder));
  86. collection.Add(new ObjectNameResolver(CatalogSchemaNameOrder));
  87. }
  88. return (ObjectNameResolver[])collection.ToArray(typeof(ObjectNameResolver));
  89. }
  90. }
  91. #endregion // ObjectNamesHelper
  92. #region ConnectionStringHelper
  93. public sealed class ConnectionStringHelper
  94. {
  95. public static string FindValue(NameValueCollection collection, string[] keys)
  96. {
  97. if (collection == null || keys == null || keys.Length == 0) {
  98. return String.Empty;
  99. }
  100. for(int i=0; i < keys.Length; i++) {
  101. string value = FindValue(collection,keys[i]);
  102. if (!String.Empty.Equals(value)) {
  103. return value;
  104. }
  105. }
  106. return String.Empty;
  107. }
  108. public static string FindValue(NameValueCollection collection, string key)
  109. {
  110. if (collection == null) {
  111. return String.Empty;
  112. }
  113. string value = collection[key];
  114. return (value != null) ? value : String.Empty;
  115. }
  116. public static void UpdateValue(NameValueCollection collection,string[] keys,string value)
  117. {
  118. for(int i=0; i < keys.Length; i++) {
  119. if (collection[keys[i]] != null) {
  120. collection[keys[i]] = value;
  121. }
  122. }
  123. }
  124. public static void AddValue(NameValueCollection collection,string[] keys,string value)
  125. {
  126. for(int i=0; i < keys.Length; i++) {
  127. collection[keys[i]] = value;
  128. }
  129. }
  130. /**
  131. * Parses connection string and builds NameValueCollection
  132. * for all keys.
  133. */
  134. public static NameValueCollection BuildUserParameters (string connectionString)
  135. {
  136. NameValueCollection userParameters = new NameValueCollection();
  137. if (connectionString == null || connectionString.Length == 0) {
  138. return userParameters;
  139. }
  140. connectionString += ";";
  141. bool inQuote = false;
  142. bool inDQuote = false;
  143. bool inName = true;
  144. string name = String.Empty;
  145. string value = String.Empty;
  146. StringBuilder sb = new StringBuilder ();
  147. for (int i = 0; i < connectionString.Length; i += 1) {
  148. char c = connectionString [i];
  149. char peek;
  150. if (i == connectionString.Length - 1)
  151. peek = '\0';
  152. else
  153. peek = connectionString [i + 1];
  154. switch (c) {
  155. case '\'':
  156. if (inDQuote)
  157. sb.Append (c);
  158. else if (peek.Equals(c)) {
  159. sb.Append(c);
  160. i += 1;
  161. }
  162. else
  163. inQuote = !inQuote;
  164. break;
  165. case '"':
  166. if (inQuote)
  167. sb.Append(c);
  168. else if (peek.Equals(c)) {
  169. sb.Append(c);
  170. i += 1;
  171. }
  172. else
  173. inDQuote = !inDQuote;
  174. break;
  175. case ';':
  176. if (inDQuote || inQuote)
  177. sb.Append(c);
  178. else {
  179. if (name != String.Empty && name != null) {
  180. value = sb.ToString();
  181. userParameters [name.Trim()] = value.Trim();
  182. }
  183. inName = true;
  184. name = String.Empty;
  185. value = String.Empty;
  186. sb = new StringBuilder();
  187. }
  188. break;
  189. case '=':
  190. if (inDQuote || inQuote || !inName)
  191. sb.Append (c);
  192. else if (peek.Equals(c)) {
  193. sb.Append (c);
  194. i += 1;
  195. }
  196. else {
  197. name = sb.ToString();
  198. sb = new StringBuilder();
  199. inName = false;
  200. }
  201. break;
  202. case ' ':
  203. if (inQuote || inDQuote)
  204. sb.Append(c);
  205. else if (sb.Length > 0 && !peek.Equals(';'))
  206. sb.Append(c);
  207. break;
  208. default:
  209. sb.Append(c);
  210. break;
  211. }
  212. }
  213. return userParameters;
  214. }
  215. }
  216. #endregion // ConnectionStringHelper
  217. #region DataSourceCache
  218. private sealed class DataSourceCache : AbstractDbMetaDataCache
  219. {
  220. internal DataSource GetDataSource(string dataSourceName,string namingProviderUrl,string namingFactoryInitial)
  221. {
  222. Hashtable cache = Cache;
  223. DataSource ds = cache[dataSourceName] as DataSource;
  224. if (ds != null) {
  225. return ds;
  226. }
  227. Context ctx = null;
  228. java.util.Properties properties = new java.util.Properties();
  229. if ((namingProviderUrl != null) && (namingProviderUrl.Length > 0)) {
  230. properties.put("java.naming.provider.url",namingProviderUrl);
  231. }
  232. if ((namingFactoryInitial != null) && (namingFactoryInitial.Length > 0)) {
  233. properties.put("java.naming.factory.initial",namingFactoryInitial);
  234. }
  235. ctx = new InitialContext(properties);
  236. try {
  237. ds = (DataSource)ctx.lookup(dataSourceName);
  238. }
  239. catch(javax.naming.NameNotFoundException e) {
  240. // possible that is a Tomcat bug,
  241. // so try to lookup for jndi datasource with "java:comp/env/" appended
  242. ds = (DataSource)ctx.lookup("java:comp/env/" + dataSourceName);
  243. }
  244. cache[dataSourceName] = ds;
  245. return ds;
  246. }
  247. }
  248. #endregion // DatasourceCache
  249. #region Declarations
  250. protected internal enum JDBC_MODE { NONE, DATA_SOURCE_MODE, JDBC_DRIVER_MODE, PROVIDER_MODE }
  251. protected internal enum PROVIDER_TYPE { NONE, SQLOLEDB, MSDAORA, IBMDADB2 }
  252. #endregion // Declarations
  253. #region Fields
  254. private static DataSourceCache _dataSourceCache = new DataSourceCache();
  255. private const int DEFAULT_TIMEOUT = 15;
  256. private Connection _jdbcConnnection;
  257. private ConnectionState _internalState;
  258. private object _internalStateSync = new object();
  259. private NameValueCollection _userParameters;
  260. protected string _connectionString = String.Empty;
  261. protected string _jdbcUrl;
  262. private ArrayList _referencedObjects = new ArrayList();
  263. private ObjectNameResolver[] _syntaxPatterns;
  264. #endregion // Fields
  265. #region Constructors
  266. public AbstractDBConnection(string connectionString)
  267. {
  268. _connectionString = connectionString;
  269. InitializeSkippedUserParameters();
  270. }
  271. #endregion // Constructors
  272. #region Properties
  273. public override String ConnectionString
  274. {
  275. get { return _connectionString; }
  276. set {
  277. if (IsOpened) {
  278. throw ExceptionHelper.NotAllowedWhileConnectionOpen("ConnectionString",_internalState);
  279. }
  280. _connectionString = value;
  281. _userParameters = null;
  282. _jdbcUrl = null;
  283. }
  284. }
  285. public override int ConnectionTimeout
  286. {
  287. get {
  288. string timeoutStr = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_TIMEOUT"));
  289. if (!String.Empty.Equals(timeoutStr)) {
  290. try {
  291. return Convert.ToInt32(timeoutStr);
  292. }
  293. catch(FormatException e) {
  294. throw ExceptionHelper.InvalidValueForKey("connect timeout");
  295. }
  296. catch (OverflowException e) {
  297. throw ExceptionHelper.InvalidValueForKey("connect timeout");
  298. }
  299. }
  300. return DEFAULT_TIMEOUT;
  301. }
  302. }
  303. public override String Database
  304. {
  305. get { return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_DATABASE")); }
  306. }
  307. public override ConnectionState State
  308. {
  309. get {
  310. try {
  311. if ((JdbcConnection == null) || JdbcConnection.isClosed()) {
  312. // jdbc connection not initialized or closed
  313. if (_internalState == ConnectionState.Closed ) {
  314. return ConnectionState.Closed;
  315. }
  316. }
  317. else {
  318. // jdbc connection is opened
  319. if ((_internalState & ConnectionState.Open) != 0) {
  320. return ConnectionState.Open;
  321. }
  322. }
  323. return ConnectionState.Broken;
  324. }
  325. catch (SQLException) {
  326. return ConnectionState.Broken;
  327. }
  328. }
  329. }
  330. internal bool IsExecuting
  331. {
  332. get {
  333. return ((_internalState & ConnectionState.Executing) != 0);
  334. }
  335. set {
  336. lock(_internalStateSync) {
  337. // to switch to executing, the connection must be in opened
  338. if (value) {
  339. if (_internalState != ConnectionState.Open) {
  340. if (IsFetching) {
  341. throw ExceptionHelper.OpenedReaderExists();
  342. }
  343. throw ExceptionHelper.OpenConnectionRequired("",_internalState);
  344. }
  345. _internalState |= ConnectionState.Executing;
  346. }
  347. else {
  348. if (!IsExecuting) {
  349. throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Executing.ToString() + " while in state " + _internalState.ToString());
  350. }
  351. _internalState &= ~ConnectionState.Executing;
  352. }
  353. }
  354. }
  355. }
  356. internal bool IsFetching
  357. {
  358. get {
  359. return ((_internalState & ConnectionState.Fetching) != 0);
  360. }
  361. set {
  362. lock(_internalStateSync) {
  363. if (value) {
  364. // to switch to fetching connection must be in opened, executing
  365. if (((_internalState & ConnectionState.Open) == 0) || ((_internalState & ConnectionState.Executing) == 0)) {
  366. throw ExceptionHelper.OpenConnectionRequired("",_internalState);
  367. }
  368. _internalState |= ConnectionState.Fetching;
  369. }
  370. else {
  371. if (!IsFetching) {
  372. throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Fetching.ToString() + " while in state " + _internalState.ToString());
  373. }
  374. _internalState &= ~ConnectionState.Fetching;
  375. }
  376. }
  377. }
  378. }
  379. internal bool IsOpened
  380. {
  381. get {
  382. return ((_internalState & ConnectionState.Open) != 0);
  383. }
  384. set {
  385. lock(_internalStateSync) {
  386. if (value) {
  387. // only connecting connection can be opened
  388. if ((_internalState != ConnectionState.Connecting)) {
  389. throw ExceptionHelper.ConnectionAlreadyOpen(_internalState);
  390. }
  391. _internalState |= ConnectionState.Open;
  392. }
  393. else {
  394. if (!IsOpened) {
  395. throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Open.ToString() + " while in state " + _internalState.ToString());
  396. }
  397. _internalState &= ~ConnectionState.Open;
  398. }
  399. }
  400. }
  401. }
  402. internal bool IsConnecting
  403. {
  404. get {
  405. return ((_internalState & ConnectionState.Connecting) != 0);
  406. }
  407. set {
  408. lock(_internalStateSync) {
  409. if (value) {
  410. // to switch to connecting conection must be in closed or in opened
  411. if ((_internalState != ConnectionState.Closed) && (_internalState != ConnectionState.Open)) {
  412. throw ExceptionHelper.ConnectionAlreadyOpen(_internalState);
  413. }
  414. _internalState |= ConnectionState.Connecting;
  415. }
  416. else {
  417. if (!IsConnecting) {
  418. throw new InvalidOperationException("Connection : Impossible to tear down from state " + ConnectionState.Connecting.ToString() + " while in state " + _internalState.ToString());
  419. }
  420. _internalState &= ~ConnectionState.Connecting;
  421. }
  422. }
  423. }
  424. }
  425. protected virtual PROVIDER_TYPE ProviderType
  426. {
  427. get {
  428. if (JdbcMode != JDBC_MODE.PROVIDER_MODE) {
  429. return PROVIDER_TYPE.NONE;
  430. }
  431. string providerStr = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_PROVIDER")).ToUpper();
  432. if (providerStr.StartsWith("SQLOLEDB")) {
  433. return PROVIDER_TYPE.SQLOLEDB;
  434. }
  435. else if (providerStr.StartsWith("MSDAORA")) {
  436. return PROVIDER_TYPE.MSDAORA;
  437. }
  438. else if (providerStr.StartsWith("IBMDADB2")) {
  439. return PROVIDER_TYPE.IBMDADB2;
  440. }
  441. return PROVIDER_TYPE.NONE;
  442. }
  443. }
  444. protected internal virtual JDBC_MODE JdbcMode
  445. {
  446. get {
  447. string[] conJndiNameStr = StringManager.GetStringArray("CON_JNDI_NAME");
  448. if ( !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,conJndiNameStr))) {
  449. return JDBC_MODE.DATA_SOURCE_MODE;
  450. }
  451. string[] jdbcDriverStr = StringManager.GetStringArray("JDBC_DRIVER");
  452. string[] jdbcUrlStr = StringManager.GetStringArray("JDBC_URL");
  453. bool jdbcDriverSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcDriverStr));
  454. bool jdbcUrlSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcUrlStr));
  455. if (jdbcDriverSpecified && jdbcUrlSpecified) {
  456. return JDBC_MODE.JDBC_DRIVER_MODE;
  457. }
  458. string[] providerStr = StringManager.GetStringArray("CON_PROVIDER");
  459. if (!String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,providerStr))) {
  460. return JDBC_MODE.PROVIDER_MODE;
  461. }
  462. return JDBC_MODE.NONE;
  463. }
  464. }
  465. protected virtual string JdbcDriverName
  466. {
  467. get { return String.Empty; }
  468. }
  469. protected abstract DbStringManager StringManager
  470. {
  471. get;
  472. }
  473. protected virtual string ServerName
  474. {
  475. get { return DataSource; }
  476. }
  477. protected virtual string CatalogName
  478. {
  479. get { return Database; }
  480. }
  481. protected virtual string Port
  482. {
  483. get {
  484. string port = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_PORT"));
  485. switch (ProviderType) {
  486. case PROVIDER_TYPE.SQLOLEDB :
  487. if (String.Empty.Equals(port)) {
  488. try {
  489. port = DbPortResolver.getMSSqlPort(this).ToString();
  490. }
  491. catch (SQLException e) {
  492. throw CreateException(e);
  493. }
  494. }
  495. ConnectionStringHelper.AddValue(UserParameters,StringManager.GetStringArray("CON_PORT"),port);
  496. break;
  497. }
  498. return port;
  499. }
  500. }
  501. public override string DataSource
  502. {
  503. get {
  504. string dataSource = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_DATA_SOURCE"));
  505. if (ProviderType == PROVIDER_TYPE.SQLOLEDB) {
  506. int instanceIdx;
  507. if ((instanceIdx = dataSource.IndexOf("\\")) != -1) {
  508. // throw out named instance name
  509. dataSource = dataSource.Substring(0,instanceIdx);
  510. }
  511. if (dataSource != null && dataSource.StartsWith("(") && dataSource.EndsWith(")")) {
  512. dataSource = dataSource.Substring(1,dataSource.Length - 2);
  513. }
  514. if(String.Empty.Equals(dataSource) || (String.Compare("local",dataSource,true) == 0)) {
  515. dataSource = "localhost";
  516. }
  517. }
  518. return dataSource;
  519. }
  520. }
  521. internal string InstanceName
  522. {
  523. get {
  524. string dataSource = ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_DATA_SOURCE"));
  525. string instanceName = String.Empty;
  526. if (ProviderType == PROVIDER_TYPE.SQLOLEDB) {
  527. int instanceIdx;
  528. if ((instanceIdx = dataSource.IndexOf("\\")) == -1) {
  529. // no named instance specified - use a default name
  530. instanceName = StringManager.GetString("SQL_DEFAULT_INSTANCE_NAME");
  531. }
  532. else {
  533. // get named instance name
  534. instanceName = dataSource.Substring(instanceIdx + 1);
  535. }
  536. }
  537. return instanceName;
  538. }
  539. }
  540. protected virtual string User
  541. {
  542. get { return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_USER_ID")); }
  543. }
  544. protected virtual string Password
  545. {
  546. get { return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("CON_PASSWORD")); }
  547. }
  548. protected NameValueCollection UserParameters
  549. {
  550. get {
  551. if (_userParameters == null) {
  552. _userParameters = ConnectionStringHelper.BuildUserParameters(ConnectionString);
  553. }
  554. return _userParameters;
  555. }
  556. }
  557. internal String JdbcUrl
  558. {
  559. get {
  560. if ( UserParameters == null) {
  561. return String.Empty;
  562. }
  563. if (_jdbcUrl == null) {
  564. _jdbcUrl = BuildJdbcUrl();
  565. }
  566. return _jdbcUrl;
  567. }
  568. }
  569. internal ConnectionState InternalState
  570. {
  571. get { return _internalState; }
  572. }
  573. protected internal Connection JdbcConnection
  574. {
  575. get { return _jdbcConnnection; }
  576. set { _jdbcConnnection = value; }
  577. }
  578. protected virtual string[] ResourceIgnoredKeys
  579. {
  580. get { return new string[0]; }
  581. }
  582. protected virtual Hashtable SkippedUserParameters
  583. {
  584. get { return new Hashtable(new CaseInsensitiveHashCodeProvider(),new CaseInsensitiveComparer()); }
  585. }
  586. internal ObjectNameResolver[] SyntaxPatterns
  587. {
  588. get {
  589. if (_syntaxPatterns == null) {
  590. _syntaxPatterns = ObjectNamesHelper.GetSyntaxPatterns(this);
  591. }
  592. return _syntaxPatterns;
  593. }
  594. }
  595. #endregion // Properties
  596. #region Methods
  597. // since WS also does not permits dynamically change of login timeout and tomcat does no implements - do not do it at all
  598. //ds.setLoginTimeout(ConnectionTimeout);
  599. protected internal abstract void OnSqlWarning(SQLWarning warning);
  600. protected internal abstract void OnStateChanged(ConnectionState orig, ConnectionState current);
  601. protected abstract SystemException CreateException(SQLException e);
  602. protected abstract SystemException CreateException(string message);
  603. public override void Close()
  604. {
  605. try {
  606. ClearReferences();
  607. if (JdbcConnection != null && !JdbcConnection.isClosed()) {
  608. JdbcConnection.close();
  609. }
  610. }
  611. catch (SQLException e) {
  612. // suppress exception
  613. JdbcConnection = null;
  614. #if DEBUG
  615. Console.WriteLine("Exception catched at Conection.Close() : {0}\n{1}\n{2}",e.GetType().FullName,e.Message,e.StackTrace);
  616. #endif
  617. }
  618. catch (Exception e) {
  619. // suppress exception
  620. JdbcConnection = null;
  621. #if DEBUG
  622. Console.WriteLine("Exception catched at Conection.Close() : {0}\n{1}\n{2}",e.GetType().FullName,e.Message,e.StackTrace);
  623. #endif
  624. }
  625. finally {
  626. lock(_internalStateSync) {
  627. _internalState = ConnectionState.Closed;
  628. }
  629. }
  630. }
  631. protected internal virtual void CopyTo(AbstractDBConnection target)
  632. {
  633. target._connectionString = _connectionString;
  634. }
  635. internal protected virtual void OnSqlException(SQLException exp)
  636. {
  637. throw CreateException(exp);
  638. }
  639. internal void AddReference(object referencedObject)
  640. { lock(_referencedObjects.SyncRoot) {
  641. _referencedObjects.Add(new WeakReference(referencedObject));
  642. }
  643. }
  644. internal void RemoveReference(object referencedObject)
  645. {
  646. lock(_referencedObjects.SyncRoot) {
  647. for(int i = 0; i < _referencedObjects.Count; i++) {
  648. WeakReference wr = (WeakReference) _referencedObjects[i];
  649. if (wr.IsAlive && (wr.Target == referencedObject)) {
  650. _referencedObjects.RemoveAt(i);
  651. }
  652. }
  653. }
  654. }
  655. private void ClearReferences()
  656. {
  657. ArrayList oldList = _referencedObjects;
  658. _referencedObjects = new ArrayList();
  659. for(int i = 0; i < oldList.Count; i++) {
  660. WeakReference wr = (WeakReference) oldList[i];
  661. if (wr.IsAlive) {
  662. ClearReference(wr.Target);
  663. }
  664. }
  665. }
  666. private void ClearReference(object referencedObject)
  667. {
  668. try {
  669. if (referencedObject is AbstractDbCommand) {
  670. ((AbstractDbCommand)referencedObject).CloseInternal();
  671. }
  672. else if (referencedObject is AbstractDataReader) {
  673. ((AbstractDataReader)referencedObject).CloseInternal();
  674. }
  675. }
  676. catch (SQLException) {
  677. // suppress exception since it's possible that command or reader are in inconsistent state
  678. }
  679. }
  680. public override void Open()
  681. {
  682. if (_connectionString == null || _connectionString.Length == 0) {
  683. throw ExceptionHelper.ConnectionStringNotInitialized();
  684. }
  685. IsConnecting = true;
  686. try {
  687. if (JdbcConnection != null && !JdbcConnection.isClosed()) {
  688. throw ExceptionHelper.ConnectionAlreadyOpen(_internalState);
  689. }
  690. switch(JdbcMode) {
  691. case JDBC_MODE.DATA_SOURCE_MODE :
  692. JdbcConnection = GetConnectionFromDataSource();
  693. break;
  694. case JDBC_MODE.JDBC_DRIVER_MODE:
  695. JdbcConnection = GetConnectionFromJdbcDriver();
  696. break;
  697. case JDBC_MODE.PROVIDER_MODE :
  698. JdbcConnection = GetConnectionFromProvider();
  699. break;
  700. }
  701. IsOpened = true;
  702. OnStateChanged(ConnectionState.Closed, ConnectionState.Open);
  703. }
  704. catch (SQLWarning warning) {
  705. OnSqlWarning(warning);
  706. }
  707. catch (SQLException exp) {
  708. OnSqlException(exp);
  709. }
  710. finally {
  711. IsConnecting = false;
  712. }
  713. }
  714. public override void ChangeDatabase(String database)
  715. {
  716. IsConnecting = true;
  717. try {
  718. ClearReferences();
  719. Connection con = JdbcConnection;
  720. con.setCatalog(database);
  721. ConnectionStringHelper.UpdateValue(UserParameters,StringManager.GetStringArray("CON_DATABASE"),database);
  722. }
  723. catch (SQLWarning warning) {
  724. OnSqlWarning(warning);
  725. }
  726. catch (SQLException exp) {
  727. throw CreateException(exp);
  728. }
  729. finally {
  730. IsConnecting = false;
  731. }
  732. }
  733. public override string ServerVersion {
  734. get {
  735. // only if the driver support this methods
  736. try {
  737. if (JdbcConnection == null)
  738. return String.Empty;
  739. DatabaseMetaData metaData = JdbcConnection.getMetaData();
  740. return metaData.getDatabaseProductVersion();
  741. }
  742. catch (SQLException exp) {
  743. throw CreateException(exp);
  744. }
  745. }
  746. }
  747. internal string JdbcProvider {
  748. get {
  749. // only if the driver support this methods
  750. try {
  751. if (JdbcConnection == null)
  752. return String.Empty;
  753. DatabaseMetaData metaData = JdbcConnection.getMetaData();
  754. return metaData.getDriverName() + " " + metaData.getDriverVersion();
  755. }
  756. catch (SQLException exp) {
  757. return String.Empty; //suppress
  758. }
  759. }
  760. }
  761. protected override void Dispose(bool disposing)
  762. {
  763. if (disposing) {
  764. try {
  765. if (JdbcConnection != null && !JdbcConnection.isClosed()) {
  766. JdbcConnection.close();
  767. }
  768. JdbcConnection = null;
  769. }
  770. catch (java.sql.SQLException exp) {
  771. throw CreateException(exp);
  772. }
  773. }
  774. base.Dispose(disposing);
  775. }
  776. protected internal virtual void ValidateConnectionString(string connectionString)
  777. {
  778. JDBC_MODE currentJdbcMode = JdbcMode;
  779. if (currentJdbcMode == JDBC_MODE.NONE) {
  780. string[] jdbcDriverStr = StringManager.GetStringArray("JDBC_DRIVER");
  781. string[] jdbcUrlStr = StringManager.GetStringArray("JDBC_URL");
  782. bool jdbcDriverSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcDriverStr));
  783. bool jdbcUrlSpecified = !String.Empty.Equals(ConnectionStringHelper.FindValue(UserParameters,jdbcUrlStr));
  784. if (jdbcDriverSpecified ^ jdbcUrlSpecified) {
  785. throw new ArgumentException("Invalid format of connection string. If you want to use third-party JDBC driver, the format is: \"JdbcDriverClassName=<jdbc driver class name>;JdbcURL=<jdbc url>\"");
  786. }
  787. }
  788. }
  789. protected virtual string BuildJdbcUrl()
  790. {
  791. switch (JdbcMode) {
  792. case JDBC_MODE.JDBC_DRIVER_MODE :
  793. return ConnectionStringHelper.FindValue(UserParameters,StringManager.GetStringArray("JDBC_URL"));
  794. default :
  795. return String.Empty;
  796. }
  797. }
  798. protected java.util.Properties BuildProperties()
  799. {
  800. java.util.Properties properties = new java.util.Properties();
  801. string user = User;
  802. if (user != null && user.Length > 0)
  803. properties.put("user", user);
  804. string password = Password;
  805. if (user != null && user.Length > 0)
  806. properties.put("password", password);
  807. string[] userKeys = UserParameters.AllKeys;
  808. for(int i=0; i < userKeys.Length; i++) {
  809. string userKey = userKeys[i];
  810. string userParameter = UserParameters[userKey];
  811. if (!SkipUserParameter(userKey)) {
  812. properties.put(userKey,userParameter);
  813. }
  814. }
  815. return properties;
  816. }
  817. protected virtual bool SkipUserParameter(string parameterName)
  818. {
  819. if (SkippedUserParameters.Count == 0) {
  820. // skipped parameters not initialized - skip all
  821. return true;
  822. }
  823. return SkippedUserParameters.Contains(parameterName);
  824. }
  825. protected virtual void InitializeSkippedUserParameters()
  826. {
  827. if (SkippedUserParameters.Count > 0) {
  828. return;
  829. }
  830. for(int i=0; i < ResourceIgnoredKeys.Length; i++) {
  831. string[] userKeys = StringManager.GetStringArray(ResourceIgnoredKeys[i]);
  832. for(int j=0; j < userKeys.Length; j++) {
  833. SkippedUserParameters.Add(userKeys[j],userKeys[j]);
  834. }
  835. }
  836. }
  837. internal void ValidateBeginTransaction()
  838. {
  839. if (State != ConnectionState.Open) {
  840. throw new InvalidOperationException(String.Format("{0} requires an open and available Connection. The connection's current state is {1}.", new object[] {"BeginTransaction", State}));
  841. }
  842. if (!JdbcConnection.getAutoCommit()) {
  843. throw new System.InvalidOperationException("Parallel transactions are not supported.");
  844. }
  845. }
  846. protected internal virtual Connection GetConnectionFromProvider()
  847. {
  848. ActivateJdbcDriver(JdbcDriverName);
  849. DriverManager.setLoginTimeout(ConnectionTimeout);
  850. java.util.Properties properties = BuildProperties();
  851. return DriverManager.getConnection (JdbcUrl, properties);
  852. }
  853. internal Connection GetConnectionFromDataSource()
  854. {
  855. string dataSourceJndi = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_JNDI_NAME"));
  856. string namingProviderUrl = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_JNDI_PROVIDER"));
  857. string namingFactoryInitial = ConnectionStringHelper.FindValue(UserParameters, StringManager.GetStringArray("CON_JNDI_FACTORY"));
  858. DataSource ds = _dataSourceCache.GetDataSource(dataSourceJndi,namingProviderUrl,namingFactoryInitial);
  859. try {
  860. ds.setLoginTimeout(ConnectionTimeout);
  861. }
  862. catch (java.lang.Exception) {
  863. // WebSphere does not allows dynamicall change of login timeout
  864. // setLoginTimeout is not supported yet
  865. // in Tomcat data source.
  866. // In this case we work wthout timeout.
  867. }
  868. return ds.getConnection();
  869. }
  870. internal virtual Connection GetConnectionFromJdbcDriver()
  871. {
  872. string[] jdbcDriverStr = StringManager.GetStringArray("JDBC_DRIVER");
  873. string[] jdbcUrlStr = StringManager.GetStringArray("JDBC_URL");
  874. string jdbcDriverName = ConnectionStringHelper.FindValue(UserParameters,jdbcDriverStr);
  875. string jdbcUrl = ConnectionStringHelper.FindValue(UserParameters,jdbcUrlStr);
  876. ActivateJdbcDriver(jdbcDriverName);
  877. DriverManager.setLoginTimeout(ConnectionTimeout);
  878. java.util.Properties properties = BuildProperties();
  879. return DriverManager.getConnection(jdbcUrl,properties);
  880. }
  881. internal ArrayList GetProcedureColumns(String procedureString, AbstractDbCommand command)
  882. {
  883. ArrayList col = new ArrayList();
  884. try {
  885. ObjectNameResolver[] nameResolvers = SyntaxPatterns;
  886. ResultSet res = null;
  887. string catalog = null;
  888. string schema = null;
  889. string spname = null;
  890. DatabaseMetaData metadata = JdbcConnection.getMetaData();
  891. bool storesUpperCaseIdentifiers = false;
  892. bool storesLowerCaseIdentifiers = false;
  893. try {
  894. storesUpperCaseIdentifiers = metadata.storesUpperCaseIdentifiers();
  895. storesLowerCaseIdentifiers = metadata.storesLowerCaseIdentifiers();
  896. }
  897. catch (SQLException e) {
  898. // suppress
  899. }
  900. for(int i=0; i < nameResolvers.Length; i++) {
  901. ObjectNameResolver nameResolver = nameResolvers[i];
  902. Match match = nameResolver.Match(procedureString);
  903. if (match.Success) {
  904. spname = ObjectNameResolver.GetName(match);
  905. schema = ObjectNameResolver.GetSchema(match);
  906. catalog = ObjectNameResolver.GetCatalog(match);
  907. // make all identifiers uppercase or lowercase according to database metadata
  908. if (storesUpperCaseIdentifiers) {
  909. spname = (spname.Length > 0) ? spname.ToUpper() : null;
  910. schema = (schema.Length > 0) ? schema.ToUpper() : null;
  911. catalog = (catalog.Length > 0) ? catalog.ToUpper() : null;
  912. }
  913. else if (storesLowerCaseIdentifiers) {
  914. spname = (spname.Length > 0) ? spname.ToLower() : null;
  915. schema = (schema.Length > 0) ? schema.ToLower() : null;
  916. catalog = (catalog.Length > 0) ? catalog.ToLower() : null;
  917. }
  918. else {
  919. spname = (spname.Length > 0) ? spname : null;
  920. schema = (schema.Length > 0) ? schema : null;
  921. catalog = (catalog.Length > 0) ? catalog : null;
  922. }
  923. // catalog from db is always in correct caps
  924. if (catalog == null) {
  925. catalog = JdbcConnection.getCatalog();
  926. }
  927. try {
  928. // always get the first procedure that db returns
  929. res = metadata.getProcedures(catalog, schema, spname);
  930. if (res.next()) {
  931. catalog = res.getString(1);
  932. schema = res.getString(2);
  933. spname = res.getString(3);
  934. break;
  935. }
  936. spname = null;
  937. }
  938. catch { // suppress exception
  939. return null;
  940. }
  941. finally {
  942. if (res != null) {
  943. res.close();
  944. }
  945. }
  946. }
  947. }
  948. if (spname == null || spname.Length == 0) {
  949. return null;
  950. }
  951. try {
  952. // get procedure columns based o procedure metadata
  953. res = metadata.getProcedureColumns(catalog, schema, spname, null);
  954. while (res.next()) {
  955. // since there is still a possibility that some of the parameters to getProcedureColumn were nulls,
  956. // we need to filter the results with strict matching
  957. if ((res.getString(1) != catalog ) || (res.getString(2) != schema) || (res.getString(3) != spname)) {
  958. continue;
  959. }
  960. AbstractDbParameter parameter = (AbstractDbParameter)command.CreateParameter();
  961. parameter.SetParameterName(res);
  962. parameter.SetParameterDbType(res);
  963. parameter.SetSpecialFeatures(res);
  964. //get parameter direction
  965. short direction = res.getShort("COLUMN_TYPE");
  966. if(direction == 1) //DatabaseMetaData.procedureColumnIn
  967. parameter.Direction = ParameterDirection.Input;
  968. else if(direction == 2) //DatabaseMetaData.procedureColumnInOut
  969. parameter.Direction = ParameterDirection.InputOutput;
  970. else if(direction == 4) //DatabaseMetaData.procedureColumnOut
  971. parameter.Direction = ParameterDirection.Output;
  972. else if(direction == 5) //DatabaseMetaData.procedureColumnReturn
  973. parameter.Direction = ParameterDirection.ReturnValue;
  974. //get parameter precision and scale
  975. parameter.SetParameterPrecisionAndScale(res);
  976. parameter.SetParameterSize(res);
  977. parameter.SetParameterIsNullable(res);
  978. col.Add(parameter);
  979. }
  980. }
  981. finally {
  982. if (res != null) {
  983. res.close();
  984. }
  985. }
  986. }
  987. catch(Exception e) {
  988. //supress
  989. #if DEBUG
  990. Console.WriteLine("Exception catched at AbstractDBConnection.GetProcedureColumns() : {0}\n{1}\n{2}",e.GetType().FullName,e.Message,e.StackTrace);
  991. #endif
  992. }
  993. return col;
  994. }
  995. protected static void ActivateJdbcDriver(string driver)
  996. {
  997. if(driver != null) {
  998. try {
  999. java.lang.Class.forName(driver).newInstance();
  1000. }
  1001. catch (java.lang.ClassNotFoundException e) {
  1002. throw new TypeLoadException(e.Message);
  1003. }
  1004. catch (java.lang.InstantiationException e) {
  1005. throw new MemberAccessException(e.Message);
  1006. }
  1007. catch (java.lang.IllegalAccessException e) {
  1008. throw new MissingMethodException(e.Message);
  1009. }
  1010. }
  1011. }
  1012. protected String BuildMsSqlUrl()
  1013. {
  1014. return StringManager.GetString("SQL_JDBC_URL") //"jdbc:microsoft:sqlserver://"
  1015. + ServerName + ":" + Port + ";DatabaseName=" + CatalogName;
  1016. }
  1017. #endregion // Methods
  1018. }
  1019. }