Source

BsonSql / BsonSql.Driver / BsonSqlDomain.cs

Full commit
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using BsonSql.Driver.Configuration;
using BsonSql.Common.Events;
using BsonSql.Driver.Events;
using MongoDB.Bson;


namespace BsonSql.Driver
{
	public class BsonSqlDomain
	{
		private ConcurrentDictionary<string, BsonSqlCollection> _collections = new ConcurrentDictionary<string, BsonSqlCollection>();

		private BsonSqlServer _server;
		private DomainConfiguration _configuration;
		private string _domainId;
		private BsonSqlEventDispatcher _dispatcher = new BsonSqlEventDispatcher();

		internal BsonSqlDomain(BsonSqlServer server, DomainConfiguration configuration, string domainId)
		{
			_server = server;
			_domainId = domainId;
			_configuration = configuration;

			server.Dispatcher.Add("configuration.changed", new BsonSqlEventHandler<ConfigurationEvent>(ConfigurationChanged));
		}

		public virtual BsonSqlServer Server { get { return _server; } }

		private void ConfigurationChanged(ConfigurationEvent configEvent)
		{
			_configuration = configEvent.Configuration;
		}

		private DomainInstance GetConfiguration()
		{
			DomainInstance instance = _configuration.GetDomain(_domainId);
			if (instance == null)
				throw new InvalidOperationException("the " + _domainId + " no longer exists");
			return instance;
		}

        public Configuration.ServerConnection[] GetConnections()
        {
            return _configuration.Servers;
        }

		public BsonSqlCollection GetCollection(string name)
		{
			DomainInstance configuration = GetConfiguration();

			BsonSqlCollection sqlCollection = null;

			//do I already have this domain
			if (!_collections.TryGetValue(name, out sqlCollection))
			{
				//do I have this domain in 
				CollectionInstance instance = configuration.GetCollection(name);
				if (instance == null)
				{
					//ask server to create an instance
					BsonDocument request = new BsonDocument() { { "DomainId", _domainId }, {"CollectionName", name} };
					bool updated = false;
					BsonDocument response = _server.SubmitRequest("collection/create", request, out updated);

					configuration = GetConfiguration();
					instance = configuration.GetCollection(name);
					if (instance == null)
						throw new ApplicationException("server could not create the collection requested...check server");
				}

				//by this point, instance is not null
				sqlCollection = new BsonSqlCollection(_domainId, name, _server, _configuration);
				_collections.TryAdd(name, sqlCollection);
			}

			return sqlCollection;
		}
	}
}