Пример #1
0
 public MappingRootBinder(Mappings mappings, XmlNamespaceManager namespaceManager,
     Dialect.Dialect dialect)
     : base(mappings)
 {
     this.namespaceManager = namespaceManager;
     this.dialect = dialect;
 }
Пример #2
0
 /// <summary>
 /// Create a schema exporter for the given Configuration, with the given
 /// database connection properties
 /// </summary>
 /// <param name="cfg">The NHibernate Configuration to generate the schema from.</param>
 /// <param name="connectionProperties">The Properties to use when connecting to the Database.</param>
 public SchemaExport(Configuration cfg, IDictionary<string, string> connectionProperties)
 {
     this.connectionProperties = connectionProperties;
     dialect = Dialect.Dialect.GetDialect(connectionProperties);
     dropSQL = cfg.GenerateDropSchemaScript(dialect);
     createSQL = cfg.GenerateSchemaCreationScript(dialect);
 }
		public DatabaseMetadata(DbConnection connection, Dialect.Dialect dialect, bool extras)
		{
			meta = dialect.GetDataBaseSchema(connection);
		    this.dialect = dialect;
		    this.extras = extras;
			InitSequences(connection, dialect);
			sqlExceptionConverter = dialect.BuildSQLExceptionConverter();
		}
Пример #4
0
		/// <summary>
		/// Create a schema exporter for the given Configuration, with the given
		/// database connection properties
		/// </summary>
		/// <param name="cfg">The NHibernate Configuration to generate the schema from.</param>
		/// <param name="configProperties">The Properties to use when connecting to the Database.</param>
		public SchemaExport(Configuration cfg, IDictionary<string, string> configProperties)
		{
			this.configProperties = configProperties;
			dialect = Dialect.Dialect.GetDialect(configProperties);
			dropSQL = cfg.GenerateDropSchemaScript(dialect);
			createSQL = cfg.GenerateSchemaCreationScript(dialect);
			formatter = (PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
		}
		public SchemaUpdate(Configuration cfg, Settings settings)
		{
			configuration = cfg;
			dialect = settings.Dialect;
			connectionHelper = new SuppliedConnectionProviderConnectionHelper(settings.ConnectionProvider);
			exceptions = new List<Exception>();
			formatter = (settings.SqlStatementLogger.FormatSql ? FormatStyle.Ddl : FormatStyle.None).Formatter;
		}
		public virtual void SetUp()
		{
			Configuration cfg = new Configuration();

			factory = cfg.BuildSessionFactory();
			factoryImpl = (ISessionFactoryImplementor) factory;
			dialect = factoryImpl.Dialect;
		}
		public virtual void SetUp() 
		{
			// Generic Dialect inherits all of the Quoting functions from
			// Dialect (which is abstract)
			d = new Dialect.GenericDialect();
			tableWithNothingToBeQuoted = new string[] {"plainname", "\"plainname\""};
			tableAlreadyQuoted = new string[] {"\"Quote\"\"d[Na$`\"", "\"Quote\"\"d[Na$`\"","Quote\"d[Na$`" };
			tableThatNeedsToBeQuoted = new string[] {"Quote\"d[Na$`", "\"Quote\"\"d[Na$`\"", "Quote\"d[Na$`"};
		}
Пример #8
0
		public SchemaUpdate(Configuration cfg, Settings settings)
		{
			configuration = cfg;
			dialect = settings.Dialect;
			connectionHelper = new SuppliedConnectionProviderConnectionHelper(
				settings.ConnectionProvider
				);
			exceptions = new ArrayList();
		}
Пример #9
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MultiCriteriaImpl"/> class.
		/// </summary>
		/// <param name="session">The session.</param>
		/// <param name="factory">The factory.</param>
		internal MultiCriteriaImpl(SessionImpl session, SessionFactoryImpl factory)
		{
			dialect = session.Factory.Dialect;
			if (!session.Factory.ConnectionProvider.Driver.SupportsMultipleQueries)
			{
				throw new NotSupportedException(
					string.Format("The dialect {0} does not support multiple queries.", dialect.GetType().FullName));
			}
			this.session = session;
			this.factory = factory;
		}
Пример #10
0
		public SchemaValidator(Configuration cfg, IDictionary<string, string> connectionProperties)
		{
			configuration = cfg;
			dialect = Dialect.Dialect.GetDialect(connectionProperties);
			IDictionary<string, string> props = new Dictionary<string, string>(dialect.DefaultProperties);
			foreach (var prop in connectionProperties)
			{
				props[prop.Key] = prop.Value;
			}
			connectionHelper = new ManagedProviderConnectionHelper(props);
		}
Пример #11
0
		public MultiQueryImpl(ISessionImplementor session)
		{
			IDriver driver = session.Factory.ConnectionProvider.Driver;
			if (!driver.SupportsMultipleQueries)
			{
				throw new NotSupportedException(
					string.Format("The driver {0} does not support multiple queries.", driver.GetType().FullName));
			}
			this.dialect = session.Factory.Dialect;
			this.session = session;
		}
		public virtual void SetUp()
		{
			Configuration cfg = new Configuration();
			Assembly dm = Assembly.GetAssembly(typeof(Simple));
			cfg.AddResource("NHibernate.DomainModel.Simple.hbm.xml", dm);
			cfg.AddResource("NHibernate.DomainModel.NHSpecific.SimpleComponent.hbm.xml", dm);
			cfg.AddResource("NHibernate.DomainModel.Multi.hbm.xml", dm);

			factory = cfg.BuildSessionFactory();
			factoryImpl = (ISessionFactoryImplementor) factory;
			dialect = factoryImpl.Dialect;
		}
Пример #13
0
		public SchemaUpdate(Configuration cfg, IDictionary<string, string> connectionProperties)
		{
			configuration = cfg;
			dialect = NHibernate.Dialect.Dialect.GetDialect(connectionProperties);
			Dictionary<string, string> props = new Dictionary<string, string>(dialect.DefaultProperties);
			foreach (KeyValuePair<string, string> prop in connectionProperties)
			{
				props[prop.Key] = prop.Value;
			}
			connectionHelper = new ManagedProviderConnectionHelper(props);
			exceptions = new ArrayList();
		}
		public SchemaUpdate(Configuration cfg, IDictionary<string, string> configProperties)
		{
			configuration = cfg;
			dialect = Dialect.Dialect.GetDialect(configProperties);
			var props = new Dictionary<string, string>(dialect.DefaultProperties);
			foreach (var prop in configProperties)
			{
				props[prop.Key] = prop.Value;
			}
			connectionHelper = new ManagedProviderConnectionHelper(props);
			exceptions = new List<Exception>();
			formatter = (PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
		}
Пример #15
0
		public void ExportSchema(string[] files, bool exportSchema) 
		{
			cfg = new Configuration();
			
			for (int i=0; i<files.Length; i++) 
			{
				cfg.AddResource("NHibernate.Examples.ForumQuestions." + files[i], Assembly.Load(AssemblyName));
			}

			if(exportSchema) new SchemaExport(cfg).Create(true, true);
		
			sessions = cfg.BuildSessionFactory( );
			dialect = Dialect.Dialect.GetDialect( cfg.Properties );
		}
		private void Initialize()
		{
			if(wasInitialized)
			{
				return;
			}
			string autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, configProperties, "not-defined");
			autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
			if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
			{
				SchemaMetadataUpdater.QuoteTableAndColumns(cfg);
			}

			dialect = Dialect.Dialect.GetDialect(configProperties);
			dropSQL = cfg.GenerateDropSchemaScript(dialect);
			createSQL = cfg.GenerateSchemaCreationScript(dialect);
			formatter = (PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
			wasInitialized = true;
		}
Пример #17
0
 public override string ObjectToSQLString(object value, Dialect.Dialect dialect)
 {
     return("'" + value + "'");
 }
Пример #18
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(dialect is Oracle8iDialect);
 }
Пример #19
0
 public TestDialect(Dialect.Dialect dialect)
 {
     this.dialect = dialect;
 }
Пример #20
0
 public RootClassBinder(Mappings mappings, Dialect.Dialect dialect)
     : base(mappings, dialect)
 {
 }
		protected ClassBinder(Mappings mappings, Dialect.Dialect dialect)
			: base(mappings)
		{
			this.dialect = dialect;
		}
Пример #22
0
 /// <summary>
 /// Gets the name of this Table in quoted form if it is necessary.
 /// </summary>
 /// <param name="dialect">
 /// The <see cref="Dialect.Dialect"/> that knows how to quote the Table name.
 /// </param>
 /// <returns>
 /// The Table name in a form that is safe to use inside of a SQL statement.
 /// Quoted if it needs to be, not quoted if it does not need to be.
 /// </returns>
 public string GetQuotedName(Dialect.Dialect dialect)
 {
     return(IsQuoted ?
            dialect.QuoteForTableName(name) :
            name);
 }
Пример #23
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(dialect is PostgreSQLDialect);
 }
Пример #24
0
 public string GetText(Dialect.Dialect dialect)
 {
     return(GetQuotedName(dialect));
 }
Пример #25
0
 /// <summary>
 /// Generates the SQL string to drop this Index in the database.
 /// </summary>
 /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
 /// <param name="defaultCatalog"></param>
 /// <param name="defaultSchema"></param>
 /// <returns>
 /// A string that contains the SQL to drop this Index.
 /// </returns>
 public string SqlDropString(Dialect.Dialect dialect, string defaultCatalog, string defaultSchema)
 {
     return(BuildSqlDropIndexString(dialect, Table, Name, defaultCatalog, defaultSchema));
 }
Пример #26
0
 /// <summary>
 /// For any column name, generate an alias that is unique to that
 /// column name, and also take Dialect.MaxAliasLength into account.
 /// It keeps four characters left for accommodating additional suffixes.
 /// </summary>
 public string GetAlias(Dialect.Dialect dialect)
 {
     return(GetAlias(dialect.MaxAliasLength));
 }
Пример #27
0
 /// <summary>
 /// Gets the name of the data type for the column.
 /// </summary>
 /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use to get the valid data types.</param>
 /// <param name="mapping"></param>
 /// <returns>
 /// The name of the data type for the column.
 /// </returns>
 /// <remarks>
 /// If the mapping file contains a value of the attribute <c>sql-type</c> this will
 /// return the string contained in that attribute.  Otherwise it will use the
 /// typename from the <see cref="Dialect.Dialect"/> of the <see cref="SqlType"/> object.
 /// </remarks>
 public string GetSqlType(Dialect.Dialect dialect, IMapping mapping)
 {
     return(_sqlType ?? GetDialectTypeName(dialect, mapping));
 }
Пример #28
0
 /// <summary>
 /// Gets the name of this Column in quoted form if it is necessary.
 /// </summary>
 /// <param name="d">
 /// The <see cref="Dialect.Dialect"/> that knows how to quote
 /// the column name.
 /// </param>
 /// <returns>
 /// The column name in a form that is safe to use inside of a SQL statement.
 /// Quoted if it needs to be, not quoted if it does not need to be.
 /// </returns>
 public string GetQuotedName(Dialect.Dialect d)
 {
     return(IsQuoted ? d.QuoteForColumnName(_name) : _name);
 }
Пример #29
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(TestDialect.SupportsEmptyInsertsOrHasNonIdentityNativeGenerator);
 }
Пример #30
0
 public BasicResultSetsCommand(ISessionImplementor session)
 {
     this.session = session;
     dialect      = session.Factory.Dialect;
     batcher      = session.Batcher;
 }
		/// <summary>
		/// 
		/// </summary>
		/// <param name="dialect"></param>
		public ANSICaseFragment(Dialect.Dialect dialect)
		{
			this.dialect = dialect;
		}
Пример #32
0
 /// <summary>
 /// Generates the SQL string to create this Index in the database.
 /// </summary>
 /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
 /// <param name="p"></param>
 /// <param name="defaultCatalog"></param>
 /// <param name="defaultSchema"></param>
 /// <returns>
 /// A string that contains the SQL to create this Index.
 /// </returns>
 public string SqlCreateString(Dialect.Dialect dialect, IMapping p, string defaultCatalog, string defaultSchema)
 {
     return(BuildSqlCreateIndexString(dialect, Name, Table, ColumnIterator, false, defaultCatalog, defaultSchema));
 }
Пример #33
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(!(dialect is HanaDialectBase));            // The WHERE clause "isactive = '1'" doesn't work on HANA because idactive is a boolean
 }
Пример #34
0
 public ClassBinder(ClassBinder parent)
     : base(parent)
 {
     dialect = parent.dialect;
     namespaceManager = parent.namespaceManager;
 }
Пример #35
0
 public string GetTemplate(Dialect.Dialect dialect, SQLFunctionRegistry functionRegistry)
 {
     return(GetQuotedName(dialect));
 }
Пример #36
0
 public void CreatePrimaryKey(Dialect.Dialect dialect)
 {
     CreatePrimaryKey();
 }
Пример #37
0
		/// <summary>
		/// Drops the schema that was built with the TestCase's Configuration.
		/// </summary>
		private void DropSchema()
		{
			sessions.Close();
			sessions = null;
			dialect = null;
			connectionProvider = null;
			lastOpenedSession = null;

			new SchemaExport( cfg ).Drop( OutputDdl, true );
			cfg = null;
		}
Пример #38
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(dialect is MsSql2000Dialect);
 }
Пример #39
0
 public ClassBinder(Binder parent, XmlNamespaceManager namespaceManager, Dialect.Dialect dialect)
     : base(parent)
 {
     this.dialect = dialect;
     this.namespaceManager = namespaceManager;
 }
Пример #40
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     // Some classes are mapped with table joins, which requires temporary tables for DML to work,
     // and DML is used for the cleanup.
     return(Dialect.SupportsTemporaryTables);
 }
		public QueryJoinFragment(Dialect.Dialect dialect, bool useThetaStyleInnerJoins)
		{
			this.dialect = dialect;
			this.useThetaStyleInnerJoins = useThetaStyleInnerJoins;
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="dialect"></param>
		public DecodeCaseFragment( Dialect.Dialect dialect )
		{
			this.dialect = dialect;
		}
Пример #43
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(true);
 }
Пример #44
0
		public SelectFragment(Dialect.Dialect d)
		{
			this.dialect = d;
		}
		protected ClassBinder(ClassBinder parent)
			: base(parent.Mappings)
		{
			dialect = parent.dialect;
		}
Пример #46
0
 /// <summary>
 /// Generates the SQL string to create this Constraint in the database.
 /// </summary>
 /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
 /// <param name="p"></param>
 /// <param name="defaultSchema"></param>
 /// <returns>
 /// A string that contains the SQL to create this Constraint.
 /// </returns>
 public string SqlCreateString(Dialect.Dialect dialect, IMapping p, string defaultSchema)
 {
     // TODO: NH-421
     return(string.Format("alter table {0} {1} ", Table.GetQualifiedName(dialect, defaultSchema), SqlConstraintString(dialect, Name, defaultSchema)));
 }
Пример #47
0
 public UnionSubclassBinder(Mappings mappings, Dialect.Dialect dialect)
     : base(mappings, dialect)
 {
 }
Пример #48
0
        private SqlString ExpandDynamicFilterParameters(SqlString sqlString, ICollection <IParameterSpecification> parameterSpecs, ISessionImplementor session)
        {
            var enabledFilters = session.EnabledFilters;

            if (enabledFilters.Count == 0 || !ParserHelper.HasHqlVariable(sqlString))
            {
                return(sqlString);
            }

            Dialect.Dialect dialect = session.Factory.Dialect;
            string          symbols = ParserHelper.HqlSeparators + dialect.OpenQuote + dialect.CloseQuote;

            var result = new SqlStringBuilder();

            foreach (var sqlPart in sqlString)
            {
                var parameter = sqlPart as Parameter;
                if (parameter != null)
                {
                    result.Add(parameter);
                    continue;
                }

                var sqlFragment = sqlPart.ToString();
                var tokens      = new StringTokenizer(sqlFragment, symbols, true);

                foreach (string token in tokens)
                {
                    if (ParserHelper.IsHqlVariable(token))
                    {
                        string   filterParameterName = token.Substring(1);
                        string[] parts         = StringHelper.ParseFilterParameterName(filterParameterName);
                        string   filterName    = parts[0];
                        string   parameterName = parts[1];
                        var      filter        = (FilterImpl)enabledFilters[filterName];

                        var   collectionSpan      = filter.GetParameterSpan(parameterName);
                        IType type                = filter.FilterDefinition.GetParameterType(parameterName);
                        int   parameterColumnSpan = type.GetColumnSpan(session.Factory);

                        // Add query chunk
                        string typeBindFragment = string.Join(", ", Enumerable.Repeat("?", parameterColumnSpan));
                        string bindFragment;
                        if (collectionSpan.HasValue && !type.ReturnedClass.IsArray)
                        {
                            bindFragment = string.Join(", ", Enumerable.Repeat(typeBindFragment, collectionSpan.Value));
                        }
                        else
                        {
                            bindFragment = typeBindFragment;
                        }

                        // dynamic-filter parameter tracking
                        var filterParameterFragment             = SqlString.Parse(bindFragment);
                        var dynamicFilterParameterSpecification = new DynamicFilterParameterSpecification(filterName, parameterName, type, collectionSpan);
                        var parameters      = filterParameterFragment.GetParameters().ToArray();
                        var sqlParameterPos = 0;
                        var paramTrackers   = dynamicFilterParameterSpecification.GetIdsForBackTrack(session.Factory);
                        foreach (var paramTracker in paramTrackers)
                        {
                            parameters[sqlParameterPos++].BackTrack = paramTracker;
                        }

                        parameterSpecs.Add(dynamicFilterParameterSpecification);
                        result.Add(filterParameterFragment);
                    }
                    else
                    {
                        result.Add(token);
                    }
                }
            }
            return(result.ToSqlString());
        }
		public AbstractCollectionPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg,
		                                   ISessionFactoryImplementor factory)
		{
			this.factory = factory;
			this.cache = cache;
			if (factory.Settings.IsStructuredCacheEntriesEnabled)
			{
				cacheEntryStructure = collection.IsMap
				                      	? (ICacheEntryStructure) new StructuredMapCacheEntry()
				                      	: (ICacheEntryStructure) new StructuredCollectionCacheEntry();
			}
			else
			{
				cacheEntryStructure = new UnstructuredCacheEntry();
			}

			dialect = factory.Dialect;
			sqlExceptionConverter = factory.SQLExceptionConverter;
			collectionType = collection.CollectionType;
			role = collection.Role;
			entityName = collection.OwnerEntityName;
			ownerPersister = factory.GetEntityPersister(entityName);
			queryLoaderName = collection.LoaderName;
			nodeName = collection.NodeName;
			isMutable = collection.IsMutable;

			Table table = collection.CollectionTable;
			fetchMode = collection.Element.FetchMode;
			elementType = collection.Element.Type;
			isPrimitiveArray = collection.IsPrimitiveArray;
			isArray = collection.IsArray;
			subselectLoadable = collection.IsSubselectLoadable;
			qualifiedTableName = table.GetQualifiedName(dialect, factory.Settings.DefaultCatalogName, factory.Settings.DefaultSchemaName);

			int spacesSize = 1 + collection.SynchronizedTables.Count;
			spaces = new string[spacesSize];
			int ispa = 0;
			spaces[ispa++] = qualifiedTableName;
			foreach (string s in collection.SynchronizedTables)
			{
				spaces[ispa++] = s;
			}

			sqlOrderByString = collection.OrderBy;
			hasOrder = sqlOrderByString != null;
			sqlOrderByStringTemplate = hasOrder
			                           	? Template.RenderOrderByStringTemplate(sqlOrderByString, dialect,
			                           	                                       factory.SQLFunctionRegistry)
			                           	: null;
			sqlWhereString = !string.IsNullOrEmpty(collection.Where) ? '(' + collection.Where + ')' : null;
			hasWhere = sqlWhereString != null;
			sqlWhereStringTemplate = hasWhere
			                         	? Template.RenderWhereStringTemplate(sqlWhereString, dialect, factory.SQLFunctionRegistry)
			                         	: null;
			hasOrphanDelete = collection.HasOrphanDelete;
			int batch = collection.BatchSize;
			if (batch == -1)
			{
				batch = factory.Settings.DefaultBatchFetchSize;
			}
			batchSize = batch;

			isVersioned = collection.IsOptimisticLocked;

			keyType = collection.Key.Type;
			int keySpan = collection.Key.ColumnSpan;
			keyColumnNames = new string[keySpan];
			keyColumnAliases = new string[keySpan];
			int k = 0;
			foreach (Column col in collection.Key.ColumnIterator)
			{
				keyColumnNames[k] = col.GetQuotedName(dialect);
				keyColumnAliases[k] = col.GetAlias(dialect);
				k++;
			}
			ISet distinctColumns = new HashedSet();
			CheckColumnDuplication(distinctColumns, collection.Key.ColumnIterator);

			#region Element

			IValue element = collection.Element;
			if (!collection.IsOneToMany)
			{
				CheckColumnDuplication(distinctColumns, element.ColumnIterator);
			}

			string elemNode = collection.ElementNodeName;
			if (elementType.IsEntityType)
			{
				string _entityName = ((EntityType) elementType).GetAssociatedEntityName();
				elementPersister = factory.GetEntityPersister(_entityName);
				if (elemNode == null)
				{
					elemNode = cfg.GetClassMapping(_entityName).NodeName;
				}
				// NativeSQL: collect element column and auto-aliases
			}
			else
			{
				elementPersister = null;
			}
			elementNodeName = elemNode;

			int elementSpan = element.ColumnSpan;
			elementColumnAliases = new string[elementSpan];
			elementColumnNames = new string[elementSpan];
			elementFormulaTemplates = new string[elementSpan];
			elementFormulas = new string[elementSpan];
			elementColumnIsSettable = new bool[elementSpan];
			elementColumnIsInPrimaryKey = new bool[elementSpan];
			bool isPureFormula = true;
			bool hasNotNullableColumns = false;
			int j = 0;
			foreach (ISelectable selectable in element.ColumnIterator)
			{
				elementColumnAliases[j] = selectable.GetAlias(dialect);
				if (selectable.IsFormula)
				{
					Formula form = (Formula) selectable;
					elementFormulaTemplates[j] = form.GetTemplate(dialect, factory.SQLFunctionRegistry);
					elementFormulas[j] = form.FormulaString;
				}
				else
				{
					Column col = (Column) selectable;
					elementColumnNames[j] = col.GetQuotedName(dialect);
					elementColumnIsSettable[j] = true;
					elementColumnIsInPrimaryKey[j] = !col.IsNullable;
					if (!col.IsNullable)
					{
						hasNotNullableColumns = true;
					}

					isPureFormula = false;
				}
				j++;
			}
			elementIsPureFormula = isPureFormula;

			//workaround, for backward compatibility of sets with no
			//not-null columns, assume all columns are used in the
			//row locator SQL
			if (!hasNotNullableColumns)
			{
				ArrayHelper.Fill(elementColumnIsInPrimaryKey, true);
			}

			#endregion

			#region INDEX AND ROW SELECT

			hasIndex = collection.IsIndexed;
			if (hasIndex)
			{
				// NativeSQL: collect index column and auto-aliases
				IndexedCollection indexedCollection = (IndexedCollection) collection;
				indexType = indexedCollection.Index.Type;
				int indexSpan = indexedCollection.Index.ColumnSpan;
				indexColumnNames = new string[indexSpan];
				indexFormulaTemplates = new string[indexSpan];
				indexFormulas = new string[indexSpan];
				indexColumnIsSettable = new bool[indexSpan];
				indexColumnAliases = new string[indexSpan];
				bool hasFormula = false;
				int i = 0;
				foreach (ISelectable selectable in indexedCollection.Index.ColumnIterator)
				{
					indexColumnAliases[i] = selectable.GetAlias(dialect);
					if (selectable.IsFormula)
					{
						Formula indexForm = (Formula) selectable;
						indexFormulaTemplates[i] = indexForm.GetTemplate(dialect, factory.SQLFunctionRegistry);
						indexFormulas[i] = indexForm.FormulaString;
						hasFormula = true;
					}
					else
					{
						Column indexCol = (Column) selectable;
						indexColumnNames[i] = indexCol.GetQuotedName(dialect);
						indexColumnIsSettable[i] = true;
					}
					i++;
				}
				indexContainsFormula = hasFormula;
				baseIndex = indexedCollection.IsList ? ((List) indexedCollection).BaseIndex : 0;

				indexNodeName = indexedCollection.IndexNodeName;
				CheckColumnDuplication(distinctColumns, indexedCollection.Index.ColumnIterator);
			}
			else
			{
				indexContainsFormula = false;
				indexColumnIsSettable = null;
				indexFormulaTemplates = null;
				indexFormulas = null;
				indexType = null;
				indexColumnNames = null;
				indexColumnAliases = null;
				baseIndex = 0;
				indexNodeName = null;
			}

			hasIdentifier = collection.IsIdentified;
			if (hasIdentifier)
			{
				if (collection.IsOneToMany)
				{
					throw new MappingException("one-to-many collections with identifiers are not supported.");
				}
				IdentifierCollection idColl = (IdentifierCollection) collection;
				identifierType = idColl.Identifier.Type;

				Column col = null;
				foreach (Column column in idColl.Identifier.ColumnIterator)
				{
					col = column;
					break;
				}

				identifierColumnName = col.GetQuotedName(dialect);
				identifierColumnAlias = col.GetAlias(dialect);
				identifierGenerator =
					idColl.Identifier.CreateIdentifierGenerator(factory.Dialect, factory.Settings.DefaultCatalogName,
					                                            factory.Settings.DefaultSchemaName, null);
				// NH see : identityDelegate declaration
				IPostInsertIdentifierGenerator pig = (identifierGenerator as IPostInsertIdentifierGenerator);
				if (pig != null)
				{
					identityDelegate = pig.GetInsertGeneratedIdentifierDelegate(this, Factory, UseGetGeneratedKeys());
				}
				else
				{
					identityDelegate = null;
				}

				CheckColumnDuplication(distinctColumns, idColl.Identifier.ColumnIterator);
			}
			else
			{
				identifierType = null;
				identifierColumnName = null;
				identifierColumnAlias = null;
				identifierGenerator = null;
				identityDelegate = null;
			}

			#endregion

			#region GENERATE THE SQL

			// NH Different behavior : for the Insert SQL we are managing isPostInsertIdentifier (not supported in H3.2.5) 
			if (collection.CustomSQLInsert == null)
			{
				if (!IsIdentifierAssignedByInsert)
				{
					sqlInsertRowString = GenerateInsertRowString();
				}
				else
				{
					sqlInsertRowString = GenerateIdentityInsertRowString();
				}
				insertCallable = false;
				insertCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				SqlType[] parmsTypes = GenerateInsertRowString().ParameterTypes;
				sqlInsertRowString = new SqlCommandInfo(collection.CustomSQLInsert, parmsTypes);
				insertCallable = collection.IsCustomInsertCallable;
				insertCheckStyle = collection.CustomSQLInsertCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLInsert, insertCallable);
			}

			sqlUpdateRowString = GenerateUpdateRowString();
			if (collection.CustomSQLUpdate == null)
			{
				updateCallable = false;
				updateCheckStyle = ExecuteUpdateResultCheckStyle.Count;
			}
			else
			{
				sqlUpdateRowString = new SqlCommandInfo(collection.CustomSQLUpdate, sqlUpdateRowString.ParameterTypes);
				updateCallable = collection.IsCustomUpdateCallable;
				updateCheckStyle = collection.CustomSQLUpdateCheckStyle
				                   ?? ExecuteUpdateResultCheckStyle.DetermineDefault(collection.CustomSQLUpdate, updateCallable);
			}

			sqlDeleteRowString = GenerateDeleteRowString();
			if (collection.CustomSQLDelete == null)
			{
				deleteCallable = false;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteRowString = new SqlCommandInfo(collection.CustomSQLDelete, sqlDeleteRowString.ParameterTypes);
				deleteCallable = collection.IsCustomDeleteCallable;
				deleteCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

			sqlDeleteString = GenerateDeleteString();
			if (collection.CustomSQLDeleteAll == null)
			{
				deleteAllCallable = false;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}
			else
			{
				sqlDeleteString = new SqlCommandInfo(collection.CustomSQLDeleteAll, sqlDeleteString.ParameterTypes);
				deleteAllCallable = collection.IsCustomDeleteAllCallable;
				deleteAllCheckStyle = ExecuteUpdateResultCheckStyle.None;
			}

		    isCollectionIntegerIndex = collection.IsIndexed && !collection.IsMap;
			sqlDetectRowByIndexString = GenerateDetectRowByIndexString();
			sqlDetectRowByElementString = GenerateDetectRowByElementString();
			sqlSelectRowByIndexString = GenerateSelectRowByIndexString();

			LogStaticSQL();

			#endregion

			isLazy = collection.IsLazy;
			isExtraLazy = collection.ExtraLazy;
			isInverse = collection.IsInverse;

			if (collection.IsArray)
			{
				elementClass = ((Array) collection).ElementClass;
			}
			else
			{
				// for non-arrays, we don't need to know the element class
				elementClass = null;
			}

			if (elementType.IsComponentType)
			{
				elementPropertyMapping =
					new CompositeElementPropertyMapping(elementColumnNames, elementFormulaTemplates,
					                                    (IAbstractComponentType) elementType, factory);
			}
			else if (!elementType.IsEntityType)
			{
				elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
			}
			else
			{
				elementPropertyMapping = elementPersister as IPropertyMapping;
				if (elementPropertyMapping == null)
				{
					elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType);
				}
			}

			// Handle any filters applied to this collection
			filterHelper = new FilterHelper(collection.FilterMap, dialect, factory.SQLFunctionRegistry);

			// Handle any filters applied to this collection for many-to-many
			manyToManyFilterHelper = new FilterHelper(collection.ManyToManyFilterMap, dialect, factory.SQLFunctionRegistry);
			manyToManyWhereString = !string.IsNullOrEmpty(collection.ManyToManyWhere)
			                        	? "( " + collection.ManyToManyWhere + " )"
			                        	: null;
			manyToManyWhereTemplate = manyToManyWhereString == null
			                          	? null
			                          	: Template.RenderWhereStringTemplate(manyToManyWhereString, factory.Dialect,
			                          	                                     factory.SQLFunctionRegistry);
			manyToManyOrderByString = collection.ManyToManyOrdering;
			manyToManyOrderByTemplate = manyToManyOrderByString == null
			                            	? null
			                            	: Template.RenderOrderByStringTemplate(manyToManyOrderByString, factory.Dialect,
			                            	                                       factory.SQLFunctionRegistry);
			InitCollectionPropertyMap();
		}
Пример #50
0
 /// <summary>
 /// Generates the SQL string to drop this Table in the database.
 /// </summary>
 /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
 /// <param name="defaultSchema"></param>
 /// <returns>
 /// A string that contains the SQL to drop this Table and to cascade the drop to
 /// the constraints if the database supports it.
 /// </returns>
 public string SqlDropString(Dialect.Dialect dialect, string defaultSchema)
 {
     return(dialect.GetDropTableString(GetQualifiedName(dialect, defaultSchema)));
 }
Пример #51
0
 public override string ObjectToSQLString(object value, Dialect.Dialect dialect)
 {
     return("'" + ToCharacter(value) + "'");
 }
Пример #52
0
        /// <summary>
        /// Generates the SQL string to create this Table in the database.
        /// </summary>
        /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
        /// <param name="p"></param>
        /// <param name="defaultSchema"></param>
        /// <returns>
        /// A string that contains the SQL to create this Table, Primary Key Constraints
        /// , and Unique Key Constraints.
        /// </returns>
        public string SqlCreateString(Dialect.Dialect dialect, IMapping p, string defaultSchema)
        {
            StringBuilder buf = new StringBuilder("create table ")
                                .Append(GetQualifiedName(dialect, defaultSchema))
                                .Append(" (");

            bool identityColumn = idValue != null && idValue.CreateIdentifierGenerator(dialect) is IdentityGenerator;

            // try to find out the name of the pk to create it as identity if the
            // identitygenerator is used
            string pkname = null;

            if (primaryKey != null && identityColumn)
            {
                foreach (Column col in primaryKey.ColumnCollection)
                {
                    pkname = col.GetQuotedName(dialect);                       //should only go through this loop once
                }
            }

            int i = 0;

            foreach (Column col in ColumnCollection)
            {
                i++;
                buf.Append(col.GetQuotedName(dialect))
                .Append(' ')
                .Append(col.GetSqlType(dialect, p));

                if (identityColumn && col.GetQuotedName(dialect).Equals(pkname))
                {
                    buf.Append(' ')
                    .Append(dialect.IdentityColumnString);
                }
                else
                {
                    if (col.IsNullable)
                    {
                        buf.Append(dialect.NullColumnString);
                    }
                    else
                    {
                        buf.Append(" not null");
                    }
                }

                if (col.IsUnique)
                {
                    if (dialect.SupportsUnique)
                    {
                        buf.Append(" unique");
                    }
                    else
                    {
                        UniqueKey uk = GetUniqueKey(col.GetQuotedName(dialect) + "_");
                        uk.AddColumn(col);
                    }
                }
                if (i < ColumnCollection.Count)
                {
                    buf.Append(StringHelper.CommaSpace);
                }
            }

            if (primaryKey != null)
            {
                //if ( dialect is HSQLDialect && identityColumn ) {
                // // skip the primary key definition
                // //ugly hack...
                //} else {
                buf.Append(',').Append(primaryKey.SqlConstraintString(dialect, defaultSchema));
                //}
            }

            foreach (UniqueKey uk in UniqueKeyCollection)
            {
                buf.Append(',').Append(uk.SqlConstraintString(dialect));
            }

            buf.Append(StringHelper.ClosedParen);

            return(buf.ToString());
        }
Пример #53
0
        public static string RenderOrderByStringTemplate(string sqlOrderByString, Dialect.Dialect dialect,
                                                         SQLFunctionRegistry functionRegistry)
        {
            //TODO: make this a bit nicer
            string symbols = new StringBuilder()
                             .Append("=><!+-*/()',|&`")
                             .Append(ParserHelper.Whitespace)
                             .Append(dialect.OpenQuote)
                             .Append(dialect.CloseQuote)
                             .ToString();
            StringTokenizer tokens = new StringTokenizer(sqlOrderByString, symbols, true);

            StringBuilder result           = new StringBuilder();
            bool          quoted           = false;
            bool          quotedIdentifier = false;

            using (var tokensEnum = tokens.GetEnumerator())
            {
                var hasMore   = tokensEnum.MoveNext();
                var nextToken = hasMore ? tokensEnum.Current : null;
                while (hasMore)
                {
                    var token   = nextToken;
                    var lcToken = token.ToLowerInvariant();
                    hasMore   = tokensEnum.MoveNext();
                    nextToken = hasMore ? tokensEnum.Current : null;

                    var isQuoteCharacter = false;

                    if (!quotedIdentifier && "'".Equals(token))
                    {
                        quoted           = !quoted;
                        isQuoteCharacter = true;
                    }

                    if (!quoted)
                    {
                        bool isOpenQuote;
                        if ("`".Equals(token))
                        {
                            isOpenQuote      = !quotedIdentifier;
                            token            = lcToken = isOpenQuote ? dialect.OpenQuote.ToString() : dialect.CloseQuote.ToString();
                            quotedIdentifier = isOpenQuote;
                            isQuoteCharacter = true;
                        }
                        else if (!quotedIdentifier && (dialect.OpenQuote == token[0]))
                        {
                            isOpenQuote      = true;
                            quotedIdentifier = true;
                            isQuoteCharacter = true;
                        }
                        else if (quotedIdentifier && (dialect.CloseQuote == token[0]))
                        {
                            quotedIdentifier = false;
                            isQuoteCharacter = true;
                            isOpenQuote      = false;
                        }
                        else
                        {
                            isOpenQuote = false;
                        }

                        if (isOpenQuote)
                        {
                            result.Append(Placeholder).Append('.');
                        }
                    }

                    var quotedOrWhitespace = quoted ||
                                             quotedIdentifier ||
                                             isQuoteCharacter ||
                                             char.IsWhiteSpace(token[0]);

                    if (quotedOrWhitespace)
                    {
                        result.Append(token);
                    }
                    else if (
                        IsIdentifier(token, dialect) &&
                        !IsFunctionOrKeyword(lcToken, nextToken, dialect, functionRegistry)
                        )
                    {
                        result.Append(Placeholder)
                        .Append('.')
                        .Append(token);
                    }
                    else
                    {
                        result.Append(token);
                    }
                }
            }
            return(result.ToString());
        }
Пример #54
0
 public DatabaseMetadata(DbConnection connection, Dialect.Dialect dialect)
     : this(connection, dialect, true)
 {
 }
Пример #55
0
 public EntityMapper(Mappings mappings, Dialect.Dialect dialect)
 {
     this.mappings = mappings;
     this.dialect = dialect;
 }
Пример #56
0
 public static string RenderWhereStringTemplate(string sqlWhereString, Dialect.Dialect dialect,
                                                SQLFunctionRegistry functionRegistry)
 {
     return(RenderWhereStringTemplate(sqlWhereString, Placeholder, dialect, functionRegistry));
 }
		protected internal Mappings(
			IDictionary<string, PersistentClass> classes,
			IDictionary<string, Mapping.Collection> collections,
			IDictionary<string, Table> tables,
			IDictionary<string, NamedQueryDefinition> queries,
			IDictionary<string, NamedSQLQueryDefinition> sqlqueries,
			IDictionary<string, ResultSetMappingDefinition> resultSetMappings,
			IDictionary<string, string> imports,
			IList<SecondPassCommand> secondPasses,
			Queue<FilterSecondPassArgs> filtersSecondPasses,
			IList<PropertyReference> propertyReferences,
			INamingStrategy namingStrategy,
			IDictionary<string, TypeDef> typeDefs,
			IDictionary<string, FilterDefinition> filterDefinitions,
			ISet<ExtendsQueueEntry> extendsQueue,
			IList<IAuxiliaryDatabaseObject> auxiliaryDatabaseObjects,
			IDictionary<string, TableDescription> tableNameBinding,
			IDictionary<Table, ColumnNames> columnNameBindingPerTable,
			string defaultAssembly,
			string defaultNamespace,
			string defaultCatalog,
			string defaultSchema,
			string preferPooledValuesLo,
			Dialect.Dialect dialect)
		{
			this.classes = classes;
			this.collections = collections;
			this.queries = queries;
			this.sqlqueries = sqlqueries;
			this.resultSetMappings = resultSetMappings;
			this.tables = tables;
			this.imports = imports;
			this.secondPasses = secondPasses;
			this.propertyReferences = propertyReferences;
			this.namingStrategy = namingStrategy;
			this.typeDefs = typeDefs;
			this.filterDefinitions = filterDefinitions;
			this.extendsQueue = extendsQueue;
			this.auxiliaryDatabaseObjects = auxiliaryDatabaseObjects;
			this.tableNameBinding = tableNameBinding;
			this.columnNameBindingPerTable = columnNameBindingPerTable;
			this.defaultAssembly = defaultAssembly;
			this.defaultNamespace = defaultNamespace;
			DefaultCatalog = defaultCatalog;
			DefaultSchema = defaultSchema;
			PreferPooledValuesLo = preferPooledValuesLo;
			this.dialect = dialect;
			this.filtersSecondPasses = filtersSecondPasses;
		}
Пример #58
0
        public static string RenderWhereStringTemplate(string sqlWhereString, string placeholder, Dialect.Dialect dialect,
                                                       SQLFunctionRegistry functionRegistry)
        {
            //TODO: make this a bit nicer
            string symbols = new StringBuilder()
                             .Append("=><!+-*/()',|&`")
                             .Append(ParserHelper.Whitespace)
                             .Append(dialect.OpenQuote)
                             .Append(dialect.CloseQuote)
                             .ToString();
            StringTokenizer tokens = new StringTokenizer(sqlWhereString, symbols, true);

            StringBuilder result           = new StringBuilder();
            bool          quoted           = false;
            bool          quotedIdentifier = false;
            bool          beforeTable      = false;
            bool          inFromClause     = false;
            bool          afterFromTable   = false;

            using (var tokensEnum = tokens.GetEnumerator())
            {
                var hasMore   = tokensEnum.MoveNext();
                var nextToken = hasMore ? tokensEnum.Current : null;
                var lastToken = string.Empty;
                while (hasMore)
                {
                    var token   = nextToken;
                    var lcToken = token.ToLowerInvariant();
                    hasMore   = tokensEnum.MoveNext();
                    nextToken = hasMore ? tokensEnum.Current : null;

                    var isQuoteCharacter = false;

                    if (!quotedIdentifier && "'".Equals(token))
                    {
                        quoted           = !quoted;
                        isQuoteCharacter = true;
                    }

                    if (!quoted)
                    {
                        bool isOpenQuote;
                        if ("`".Equals(token))
                        {
                            isOpenQuote      = !quotedIdentifier;
                            token            = lcToken = isOpenQuote ? dialect.OpenQuote.ToString() : dialect.CloseQuote.ToString();
                            quotedIdentifier = isOpenQuote;
                            isQuoteCharacter = true;
                        }
                        else if (!quotedIdentifier && (dialect.OpenQuote == token[0]))
                        {
                            isOpenQuote      = true;
                            quotedIdentifier = true;
                            isQuoteCharacter = true;
                        }
                        else if (quotedIdentifier && (dialect.CloseQuote == token[0]))
                        {
                            quotedIdentifier = false;
                            isQuoteCharacter = true;
                            isOpenQuote      = false;
                        }
                        else
                        {
                            isOpenQuote = false;
                        }

                        if (isOpenQuote && !inFromClause && !lastToken.EndsWith("."))
                        {
                            result.Append(placeholder).Append('.');
                        }
                    }

                    var quotedOrWhitespace = quoted ||
                                             quotedIdentifier ||
                                             isQuoteCharacter ||
                                             char.IsWhiteSpace(token[0]);

                    if (quotedOrWhitespace)
                    {
                        result.Append(token);
                    }
                    else if (beforeTable)
                    {
                        result.Append(token);
                        beforeTable    = false;
                        afterFromTable = true;
                    }
                    else if (afterFromTable)
                    {
                        if (!"as".Equals(lcToken))
                        {
                            afterFromTable = false;
                        }
                        result.Append(token);
                    }
                    else if (IsNamedParameter(token))
                    {
                        result.Append(token);
                    }
                    else if (
                        IsIdentifier(token, dialect) &&
                        !IsFunctionOrKeyword(lcToken, nextToken, dialect, functionRegistry)
                        )
                    {
                        result.Append(placeholder)
                        .Append('.')
                        .Append(token);
                    }
                    else
                    {
                        if (BeforeTableKeywords.Contains(lcToken))
                        {
                            beforeTable  = true;
                            inFromClause = true;
                        }
                        else if (inFromClause && ",".Equals(lcToken))
                        {
                            beforeTable = true;
                        }
                        result.Append(token);
                    }

                    if (                              //Yuck:
                        inFromClause &&
                        Keywords.Contains(lcToken) && //"as" is not in Keywords
                        !BeforeTableKeywords.Contains(lcToken)
                        )
                    {
                        inFromClause = false;
                    }
                    lastToken = token;
                }
            }
            return(result.ToString());
        }
Пример #59
0
		protected CaseFragment(Dialect.Dialect dialect)
		{
			this.dialect = dialect;
		}
Пример #60
0
 /// <summary>
 /// Generates the SQL string to drop this Constraint in the database.
 /// </summary>
 /// <param name="dialect">The <see cref="Dialect.Dialect"/> to use for SQL rules.</param>
 /// <param name="defaultSchema"></param>
 /// <returns>
 /// A string that contains the SQL to drop this Constraint.
 /// </returns>
 public virtual string SqlDropString(Dialect.Dialect dialect, string defaultSchema)
 {
     // TODO: NH-421
     return(string.Format("alter table {0} drop constraint {1}", Table.GetQualifiedName(dialect, defaultSchema), Name));
 }