public static Lucene.Net.Search.Query FilterQueryByClasses(Iesi.Collections.Generic.ISet<System.Type> classesAndSubclasses, Lucene.Net.Search.Query luceneQuery) { // A query filter is more practical than a manual class filtering post query (esp on scrollable resultsets) // it also probably minimise the memory footprint if (classesAndSubclasses == null) { return luceneQuery; } BooleanQuery classFilter = new BooleanQuery(); // annihilate the scoring impact of DocumentBuilder.CLASS_FIELDNAME classFilter.SetBoost(0); foreach (System.Type clazz in classesAndSubclasses) { Term t = new Term(DocumentBuilder.CLASS_FIELDNAME, TypeHelper.LuceneTypeName(clazz)); TermQuery termQuery = new TermQuery(t); classFilter.Add(termQuery, BooleanClause.Occur.SHOULD); } BooleanQuery filteredQuery = new BooleanQuery(); filteredQuery.Add(luceneQuery, BooleanClause.Occur.MUST); filteredQuery.Add(classFilter, BooleanClause.Occur.MUST); return filteredQuery; }
public bool IsUpToDate(Iesi.Collections.Generic.ISet<string> spaces, long timestamp /* H2.1 has Long here */) { foreach (string space in spaces) { object lastUpdate = updateTimestamps.Get(space); if (lastUpdate == null) { //the last update timestamp was lost from the cache //(or there were no updates since startup!) //NOTE: commented out, since users found the "safe" behavior // counter-intuitive when testing, and we couldn't deal // with all the forum posts :-( //updateTimestamps.put( space, new Long( updateTimestamps.nextTimestamp() ) ); //result = false; // safer //OR: put a timestamp there, to avoid subsequent expensive // lookups to a distributed cache - this is no good, since // it is non-threadsafe (could hammer effect of an actual // invalidation), and because this is not the way our // preferred distributed caches work (they work by // replication) //updateTimestamps.put( space, new Long(Long.MIN_VALUE) ); } else { if ((long) lastUpdate >= timestamp) { return false; } } } return true; }
/// <summary> /// Create an action that will evict collection and entity regions based on queryspaces (table names). /// </summary> public BulkOperationCleanupAction(ISessionImplementor session, Iesi.Collections.Generic.ISet<string> querySpaces) { //from H3.2 TODO: cache the autodetected information and pass it in instead. this.session = session; Iesi.Collections.Generic.ISet<string> tmpSpaces = new HashedSet<string>(querySpaces); ISessionFactoryImplementor factory = session.Factory; IDictionary acmd = factory.GetAllClassMetadata(); foreach (DictionaryEntry entry in acmd) { string entityName = ((System.Type) entry.Key).FullName; IEntityPersister persister = factory.GetEntityPersister(entityName); string[] entitySpaces = persister.QuerySpaces; if (AffectedEntity(querySpaces, entitySpaces)) { if (persister.HasCache) { affectedEntityNames.Add(persister.EntityName); } ISet roles = session.Factory.GetCollectionRolesByEntityParticipant(persister.EntityName); if (roles != null) { affectedCollectionRoles.AddAll(roles); } for (int y = 0; y < entitySpaces.Length; y++) { tmpSpaces.Add(entitySpaces[y]); } } } spaces = new List<string>(tmpSpaces); }
public IList Get(QueryKey key, ICacheAssembler[] returnTypes, Iesi.Collections.Generic.ISet<string> spaces, ISessionImplementor session) { if (log.IsDebugEnabled) { log.Debug("checking cached query results in region: " + regionName); } IList cacheable = (IList) queryCache.Get(key); if (cacheable == null) { log.Debug("query results were not found in cache"); return null; } IList result = new ArrayList(cacheable.Count - 1); long timestamp = (long) cacheable[0]; log.Debug("Checking query spaces for up-to-dateness [" + spaces + "]"); if (! IsUpToDate(spaces, timestamp)) { log.Debug("cached query results were not up to date"); return null; } log.Debug("returning cached query results"); for (int i = 1; i < cacheable.Count; i++) { if (returnTypes.Length == 1) { result.Add(returnTypes[0].Assemble(cacheable[i], session, null)); } else { result.Add(TypeFactory.Assemble((object[]) cacheable[i], returnTypes, session, null)); } } return result; }
internal static void AreEqual(Iesi.Collections.ISet expected, Iesi.Collections.ISet actual) { Assert.AreEqual( expected.Count, actual.Count, "two sets are diff size" ); foreach( object obj in expected ) { Assert.IsTrue( actual.Contains( obj ), obj.ToString() + " is not contained in actual" ); } }
public static IndexSearcher BuildSearcher(ISearchFactoryImplementor searchFactory, out Iesi.Collections.Generic.ISet<System.Type> classesAndSubclasses, params System.Type[] classes) { IDictionary<System.Type, DocumentBuilder> builders = searchFactory.DocumentBuilders; Iesi.Collections.Generic.ISet<IDirectoryProvider> directories = new HashedSet<IDirectoryProvider>(); if (classes == null || classes.Length == 0) { // no class means all classes foreach (DocumentBuilder builder in builders.Values) { foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards()) { directories.Add(provider); } } // Give them back an empty set classesAndSubclasses = null; } else { Iesi.Collections.Generic.ISet<System.Type> involvedClasses = new HashedSet<System.Type>(); involvedClasses.AddAll(classes); foreach (System.Type clazz in classes) { DocumentBuilder builder; builders.TryGetValue(clazz, out builder); if (builder != null) { involvedClasses.AddAll(builder.MappedSubclasses); } } foreach (System.Type clazz in involvedClasses) { DocumentBuilder builder; builders.TryGetValue(clazz, out builder); // TODO should we rather choose a polymorphic path and allow non mapped entities if (builder == null) { throw new HibernateException("Not a mapped entity: " + clazz); } foreach (IDirectoryProvider provider in builder.DirectoryProvidersSelectionStrategy.GetDirectoryProvidersForAllShards()) { directories.Add(provider); } } classesAndSubclasses = involvedClasses; } IDirectoryProvider[] directoryProviders = new List<IDirectoryProvider>(directories).ToArray(); return new IndexSearcher(searchFactory.ReaderProvider.OpenReader(directoryProviders)); }
protected override void DeleteEntity(global::NHibernate.Event.IEventSource session, object entity, global::NHibernate.Engine.EntityEntry entityEntry, bool isCascadeDeleteEnabled, global::NHibernate.Persister.Entity.IEntityPersister persister, Iesi.Collections.ISet transientEntities) { ILogicalDelete logicalDelete = entity as ILogicalDelete; if (logicalDelete != null) { logicalDelete.IsDeleted = true; this.CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities); this.CascadeAfterDelete(session, persister, entity, transientEntities); } else { base.DeleteEntity(session, entity, entityEntry, isCascadeDeleteEnabled, persister, transientEntities); } }
private bool AffectedEntity(Iesi.Collections.Generic.ISet<string> querySpaces, string[] entitySpaces) { if (querySpaces == null || (querySpaces.Count == 0)) { return true; } for (int i = 0; i < entitySpaces.Length; i++) { if (querySpaces.Contains(entitySpaces[i])) { return true; } } return false; }
/// <summary> /// Creates a new user with the specified initial password. /// </summary> /// <param name="userInfo"></param> /// <param name="initialPassword"></param> /// <param name="authorityGroups"></param> /// <returns></returns> public static User CreateNewUser(UserInfo userInfo, Password initialPassword, Iesi.Collections.Generic.ISet<AuthorityGroup> authorityGroups) { Platform.CheckForNullReference(userInfo, "userInfo"); Platform.CheckForNullReference(initialPassword, "initialPassword"); Platform.CheckForEmptyString(userInfo.UserName, "UserName"); return new User( userInfo.UserName, initialPassword, userInfo.DisplayName, userInfo.ValidFrom, userInfo.ValidUntil, true, // initially enabled Platform.Time, // creation time null, // last login time userInfo.EmailAddress, authorityGroups, new HashedSet<UserSession>() // empty session collection ); }
protected override void ChangeSet(Iesi.Collections.Generic.ISet<EntityBase> iSet) { if (iSet == null) { return; } if (this._SetItemChangedHandler == null) { this._SetItemChangedHandler = this.OnPersonSetItemChanged; } if (this._persons != null) { this._persons.ItemChanged -= this._personSetItemChangedHandler; } //foreach (var person in iSet) //{ // this._persons.Add(person); //} this._persons.ItemChanged += this._personSetItemChangedHandler; }
protected internal void CheckPropertyColumnDuplication(Iesi.Collections.Generic.ISet<string> distinctColumns, IEnumerable<Property> properties) { foreach (Property prop in properties) { Component component = prop.Value as Component; if (component != null) { CheckPropertyColumnDuplication(distinctColumns, component.PropertyIterator); } else { if (prop.IsUpdateable || prop.IsInsertable) CheckColumnDuplication(distinctColumns, prop.ColumnIterator); } } }
protected internal void CheckColumnDuplication(Iesi.Collections.Generic.ISet<string> distinctColumns, IEnumerable<ISelectable> columns) { foreach (ISelectable columnOrFormula in columns) { if (!columnOrFormula.IsFormula) { Column col = (Column)columnOrFormula; if (!distinctColumns.Add(col.Name)) { // TODO: Check for column duplication //throw new MappingException("Repeated column in mapping for entity: " + EntityName + " column: " + col.Name + // "(should be mapped with insert=\"false\" update=\"false\")"); } } } }
public Record(RecordData data, Iesi.Collections.Generic.ISet<Citation> citations) : this(data) { Citations = new Iesi.Collections.Generic.SortedSet<Citation>(citations); }
private static void ImportItems(OleDbConnection dbConnection, Iesi.Collections.Generic.ISet<Item> items, IDictionary<string, Account> accounts, IDictionary<int, Transaction> transactions) { OleDbDataAdapter dataAdapter; DataSet dataSet = new DataSet(); dataAdapter = new OleDbDataAdapter("SELECT * FROM [Items$]", dbConnection); dataAdapter.Fill(dataSet); foreach (DataRow row in dataSet.Tables[0].Rows) { Account source = accounts[row["Source"].ToString()]; Account destination = accounts[row["Destination"].ToString()]; int tranKey = Int32.Parse(row["TransactionKey"].ToString()); Decimal value = Decimal.Parse(row["Value"].ToString()); Transaction transaction = transactions[tranKey]; Item item = new Item { Description = row["Description"].ToString(), Value = value, IsVerified = bool.Parse(row["IsVerified"].ToString()), }; item.SetTransaction(transaction); item.SetSource(source); item.SetDestination(destination); items.Add(item); } }
private IList GetResultFromQueryCache(ISessionImplementor session, QueryParameters queryParameters, Iesi.Collections.Generic.ISet<string> querySpaces, IType[] resultTypes, IQueryCache queryCache, QueryKey key) { IList result = null; if ((!queryParameters.ForceCacheRefresh) && (session.CacheMode & CacheMode.Get) == CacheMode.Get) { IPersistenceContext persistenceContext = session.PersistenceContext; bool defaultReadOnlyOrig = persistenceContext.DefaultReadOnly; if (queryParameters.IsReadOnlyInitialized) persistenceContext.DefaultReadOnly = queryParameters.ReadOnly; else queryParameters.ReadOnly = persistenceContext.DefaultReadOnly; try { result = queryCache.Get(key, resultTypes, queryParameters.NaturalKeyLookup, querySpaces, session); if (_factory.Statistics.IsStatisticsEnabled) { if (result == null) { _factory.StatisticsImplementor.QueryCacheMiss(QueryIdentifier, queryCache.RegionName); } else { _factory.StatisticsImplementor.QueryCacheHit(QueryIdentifier, queryCache.RegionName); } } } finally { persistenceContext.DefaultReadOnly = defaultReadOnlyOrig; } } return result; }
protected bool IsUpToDate(Iesi.Collections.Generic.ISet<string> spaces, long timestamp) { return updateTimestampsCache.IsUpToDate(spaces, timestamp); }
public IList Get(QueryKey key, ICacheAssembler[] returnTypes, bool isNaturalKeyLookup, Iesi.Collections.Generic.ISet<string> spaces, ISessionImplementor session) { if (Log.IsDebugEnabled) Log.DebugFormat("checking cached query results in region: '{0}'; {1}", _regionName, key); var cacheable = (IList)_queryCache.Get(key); if (cacheable == null) { Log.DebugFormat("query results were not found in cache: {0}", key); return null; } var timestamp = (long)cacheable[0]; if (Log.IsDebugEnabled) Log.DebugFormat("Checking query spaces for up-to-dateness [{0}]", StringHelper.CollectionToString((ICollection)spaces)); if (!isNaturalKeyLookup && !IsUpToDate(spaces, timestamp)) { Log.DebugFormat("cached query results were not up to date for: {0}", key); return null; } Log.DebugFormat("returning cached query results for: {0}", key); for (int i = 1; i < cacheable.Count; i++) { if (returnTypes.Length == 1 && !key.HasResultTransformer) { returnTypes[0].BeforeAssemble(cacheable[i], session); } else { TypeHelper.BeforeAssemble((object[])cacheable[i], returnTypes, session); } } IList result = new List<object>(cacheable.Count - 1); for (int i = 1; i < cacheable.Count; i++) { try { if (returnTypes.Length == 1 && !key.HasResultTransformer) { result.Add(returnTypes[0].Assemble(cacheable[i], session, null)); } else { result.Add(TypeHelper.Assemble((object[])cacheable[i], returnTypes, session, null)); } } catch (UnresolvableObjectException) { if (isNaturalKeyLookup) { //TODO: not really completely correct, since // the UnresolvableObjectException could occur while resolving // associations, leaving the PC in an inconsistent state Log.Debug("could not reassemble cached result set"); _queryCache.Remove(key); return null; } throw; } } return result; }
private void setClanovi(Iesi.Collections.Generic.ISet<GimnasticarUcesnik> gimnasticari) { dgwUserControlClanovi.setItems<GimnasticarUcesnik>(gimnasticari); if (!clanoviSorted) { dgwUserControlClanovi.sort<GimnasticarUcesnik>( new string[] { "Prezime", "Ime" }, new ListSortDirection[] { ListSortDirection.Ascending, ListSortDirection.Ascending }); clanoviSorted = true; } }
/// <summary> /// Should we join this association? /// </summary> protected bool IsJoinable(JoinType joinType, Iesi.Collections.Generic.ISet<AssociationKey> visitedAssociationKeys, string lhsTable, string[] lhsColumnNames, IAssociationType type, int depth) { if (joinType < JoinType.InnerJoin) return false; if (joinType == JoinType.InnerJoin) return true; int maxFetchDepth = Factory.Settings.MaximumFetchDepth; bool tooDeep = maxFetchDepth >= 0 && depth >= maxFetchDepth; return !tooDeep && !IsDuplicateAssociation(lhsTable, lhsColumnNames, type); }
public void PostInstantiate(string entityName, System.Type persistentClass, Iesi.Collections.Generic.ISet<System.Type> interfaces, MethodInfo getIdentifierMethod, MethodInfo setIdentifierMethod, IAbstractComponentType componentIdType) { this.entityName = entityName; }
protected override void DeleteEntity(IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled, NHibernate.Persister.Entity.IEntityPersister persister, Iesi.Collections.ISet transientEntities) { var entityBase = entity as EntityBase; if (entityBase != null) entityBase.IsDeleted = true; }
private void CollectAnalyzers( DocumentMapping @class, Analyzer parentAnalyzer, bool isRoot, string prefix, Iesi.Collections.Generic.ISet<System.Type> processedClasses ) { foreach (var bridge in @class.ClassBridges) { var bridgeAnalyzer = bridge.Analyzer ?? parentAnalyzer; if (bridgeAnalyzer == null) { throw new NotSupportedException("Analyzer should not be undefined"); } analyzer.AddScopedAnalyzer(prefix + bridge.Name, bridgeAnalyzer); } if (isRoot && @class.DocumentId != null) { idMapping = @class.DocumentId; } foreach (var field in @class.Fields) { CollectAnalyzer(field, parentAnalyzer, prefix); } foreach (var embedded in @class.Embedded) { CollectAnalyzers( embedded.Class, parentAnalyzer, false, prefix + embedded.Prefix, processedClasses ); } }
public void PostInitialize(Iesi.Collections.Generic.ISet<System.Type> indexedClasses) { // this method does not requires synchronization Type plainClass = rootClassMapping.MappedClass; Iesi.Collections.Generic.ISet<Type> tempMappedSubclasses = new HashedSet<System.Type>(); // together with the caller this creates a o(2), but I think it's still faster than create the up hierarchy for each class foreach (Type currentClass in indexedClasses) { if (plainClass.IsAssignableFrom(currentClass)) { tempMappedSubclasses.Add(currentClass); } } mappedSubclasses = tempMappedSubclasses; }
/// <summary> /// Check whether the given tables/query-spaces are to be executed against /// given the currently queued actions. /// </summary> /// <param name="tables">The table/query-spaces to check. </param> /// <returns> True if we contain pending actions against any of the given tables; false otherwise.</returns> public virtual bool AreTablesToBeUpdated(Iesi.Collections.Generic.ISet<string> tables) { return AreTablesToUpdated(updates, tables) || AreTablesToUpdated(insertions, tables) || AreTablesToUpdated(deletions, tables) || AreTablesToUpdated(collectionUpdates, tables) || AreTablesToUpdated(collectionCreations, tables) || AreTablesToUpdated(collectionRemovals, tables); }
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, Iesi.Collections.Generic.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; }
private UserRole RoleIsInList(Iesi.Collections.ISet set, string rolestring) { foreach (UserRole role in set) { if (rolestring.Equals(role.Role.ToString())) { return role; } } return null; }
private void CheckColumnDuplication(Iesi.Collections.Generic.ISet<string> distinctColumns, IEnumerable<ISelectable> columns) { foreach (ISelectable s in columns) { if(!s.IsFormula) { Column col = (Column)s; if (!distinctColumns.Add(col.Name)) { throw new MappingException(string.Format("Repeated column in mapping for collection: {0} column: {1}", Role, col.Name)); } } } }
/// <summary> /// Return the query results, using the query cache, called /// by subclasses that implement cacheable queries /// </summary> /// <param name="session"></param> /// <param name="queryParameters"></param> /// <param name="querySpaces"></param> /// <param name="resultTypes"></param> /// <returns></returns> protected IList List(ISessionImplementor session, QueryParameters queryParameters, Iesi.Collections.Generic.ISet<string> querySpaces, IType[] resultTypes) { bool cacheable = _factory.Settings.IsQueryCacheEnabled && queryParameters.Cacheable; if (cacheable) { return ListUsingQueryCache(session, queryParameters, querySpaces, resultTypes); } return ListIgnoreQueryCache(session, queryParameters); }
private static bool AreTablesToUpdated(IList executables, Iesi.Collections.Generic.ISet<string> tablespaces) { foreach (IExecutable exec in executables) { object[] spaces = exec.PropertySpaces; foreach (string o in spaces) { if(tablespaces.Contains(o)) { if(log.IsDebugEnabled) log.Debug("changes must be flushed to space: " + o); return true; } } } return false; }
private IList ListUsingQueryCache(ISessionImplementor session, QueryParameters queryParameters, Iesi.Collections.Generic.ISet<string> querySpaces, IType[] resultTypes) { IQueryCache queryCache = _factory.GetQueryCache(queryParameters.CacheRegion); ISet filterKeys = FilterKey.CreateFilterKeys(session.EnabledFilters, session.EntityMode); QueryKey key = new QueryKey(Factory, SqlString, queryParameters, filterKeys); IList result = GetResultFromQueryCache(session, queryParameters, querySpaces, resultTypes, queryCache, key); if (result == null) { result = DoList(session, queryParameters); PutResultInQueryCache(session, queryParameters, resultTypes, queryCache, key, result); } return GetResultList(result, queryParameters.ResultTransformer); }