public static void CreateRelation <TPrimary, TPrimaryKey, TForeign, TForeignKey>( Database database, UniqueIndex <TPrimary, TPrimaryKey> primaryIndex, IIndex <TForeign, TForeignKey> foreignIndex, Func <TForeignKey, TPrimaryKey> foreignToPrimary, Func <TPrimaryKey, TForeignKey> primaryToForeign, RelationOptions options) where TPrimary : class where TForeign : class { try { database.Tables.CreateRelation( primaryIndex, foreignIndex, foreignToPrimary, primaryToForeign, options); } catch (NMemory.Exceptions.NMemoryException ex) { var message = string.Format("An exception has occurred during table initialization while relating " + "key '{0}' to '{1}'.", primaryIndex, foreignIndex); throw new InvalidOperationException(message, ex); } }
public TutorialDbContext OpenDatabase() { // データベースを作成したり、データベースに接続したりするには、DbConfig を使用します。 // 以下にその手順を説明します。 // To connect or create a database, use DbConfig. Like this: var dbConfig = new DbConfig <TutorialDbContext>(); // 一意性制約が使用できます。 // メモ: 実際にはハッシュ表の索引が作られますが、それを使用する手段は未実装です。 // Unique constraints are available. // Note: Actually a hashtable index is created for each unique contraints, you can't use it yet. dbConfig.Add <Person>(UniqueIndex.Of <Person>(p => p.Name)); // そして、OpenMemory メソッドを呼び出して、インメモリーのデータベースを生成します。 // Then invoke OpenMemory to create an in-memory database. return(dbConfig.OpenMemory("sample_db")); // ディスクベースのデータベースに対しては、代わりに OpenDirectory メソッドを使用してください。 // これは OpenMemory とは異なり、既存のデータベースを開くことができます。 // 重要: データベースのディレクトリーがすでに存在し、しかしモデルクラスが異なっている場合、 // すべてのテーブルが Drop され、改めて新しいテーブルが作られます。 // Use OpenDirectory for disk-based one instead. // Unlike OpenMemory, OpenDirectory can open an exsiting database. // Note: If the database directory exists but model classes have changed, // all tables are dropped and new tables are created again. //return dbConfig.OpenDirectory(new System.IO.DirectoryInfo(@"path/to/directory")); }
public override void Modify(DocumentMapping mapping, MemberInfo member) { var membersGroupedByIndexName = member.DeclaringType.GetMembers() .Where(mi => mi.GetCustomAttributes <UniqueIndexAttribute>().Any()) .Select(mi => new { Member = mi, IndexInformation = mi.GetCustomAttributes <UniqueIndexAttribute>().First() }) .GroupBy(m => m.IndexInformation.IndexName ?? m.Member.Name) .Where(mg => mg.Any(m => m.Member == member)) .Single(); //var indexDefinition = new ComputedIndex(mapping, new[] { member }) var indexDefinition = new UniqueIndex(mapping, membersGroupedByIndexName.Select(m => new[] { m.Member }).ToArray()) { Method = IndexMethod }; if (IndexName.IsNotEmpty()) { indexDefinition.IndexName = IndexName; } indexDefinition.IsUnique = true; if (!mapping.Indexes.Any(ind => ind.IndexName == indexDefinition.IndexName)) { mapping.Indexes.Add(indexDefinition); } }
public static int DuplicateCount(UniqueIndex uniqueIndex, Replacements rep) { var primaryKey = uniqueIndex.Table.Columns.Values.Where(a => a.PrimaryKey).Only(); if (primaryKey == null) { throw new InvalidOperationException("No primary key found"); } ; var oldTableName = rep.Apply(Replacements.KeyTablesInverse, uniqueIndex.Table.Name.ToString()); var columnReplacement = rep.TryGetC(Replacements.KeyColumnsForTable(uniqueIndex.Table.Name.ToString()))?.Inverse() ?? new Dictionary <string, string>(); var oldColumns = uniqueIndex.Columns.ToString(c => (columnReplacement.TryGetC(c.Name) ?? c.Name).SqlEscape(), ", "); var oldPrimaryKey = columnReplacement.TryGetC(primaryKey.Name) ?? primaryKey.Name; return((int)Executor.ExecuteScalar( $@"SELECT Count(*) FROM {oldTableName} WHERE {oldPrimaryKey} NOT IN ( SELECT MIN({oldPrimaryKey}) FROM {oldTableName} {(string.IsNullOrWhiteSpace(uniqueIndex.Where) ? "" : "WHERE " + uniqueIndex.Where.Replace(columnReplacement))} GROUP BY {oldColumns} ){(string.IsNullOrWhiteSpace(uniqueIndex.Where) ? "" : "AND " + uniqueIndex.Where.Replace(columnReplacement))}") !); }
public ConfigurationNodeCollection() { _listIndex = new ListIndex <ConfigurationNode>("List"); _nameIndex = new UniqueIndex <string, ConfigurationNode>("Name", node => GetKeyResponse.Create(true, node.Name), SortOrder.Ascending); _collection = new IndexableCollection <ConfigurationNode>(_listIndex); _collection.Indexes.Add(_nameIndex); }
internal XmlSpreadsheetAttributeCollection() { NameIndex = new UniqueIndex <string, XmlSpreadsheetAttribute>( "NameIndex", item => GetKeyResponse.Create(true, item.LocalName), SortOrder.None); _items = new IndexableCollection <XmlSpreadsheetAttribute>(NameIndex); }
private static SqlPreCommand RemoveDuplicates(UniqueIndex uniqueIndex, IColumn primaryKey, string columns, bool commentedOut) { return(new SqlPreCommandSimple($@"DELETE {uniqueIndex.Table.Name} WHERE {primaryKey.Name} NOT IN ( SELECT MIN({primaryKey.Name}) FROM {uniqueIndex.Table.Name} GROUP BY {columns} )".Let(txt => commentedOut ? txt.Indent(2, '-') : txt))); }
/// <summary> /// /// </summary> public TextDataSetTableCollection() { _listIndex = new ListIndex <TextDataSetTable>("List"); _nameIndex = new UniqueIndex <string, TextDataSetTable>( "Name", item => GetKeyResponse.Create(true, item.Name), SortOrder.None); _collection = new IndexableCollection <TextDataSetTable>(_listIndex); _collection.Indexes.Add(_nameIndex); }
public static IDisposable DisableUniqueIndex(UniqueIndex index) { SafeConsole.WriteLineColor(ConsoleColor.DarkMagenta, " DISABLE Unique Index " + index.IndexName); SqlBuilder.DisableIndex(index.Table.Name, index.IndexName).ExecuteLeaves(); return(new Disposable(() => { SafeConsole.WriteLineColor(ConsoleColor.DarkMagenta, " REBUILD Unique Index " + index.IndexName); SqlBuilder.RebuildIndex(index.Table.Name, index.IndexName).ExecuteLeaves(); })); }
public void DeleteItem(IQueueItem item) { lock (this) { Queue.Remove(item as InMemoryQueueItem); if (item.UniqueKey != null) { UniqueIndex.Remove(item.UniqueKey); } } }
public TextDataColumnCollection() { _listIndex = new ListIndex <TextDataColumn>("List"); _nameIndex = new UniqueIndex <string, TextDataColumn>( "Name", column => GetKeyResponse.Create(true, column.ColumnName), SortOrder.None); _collection = new IndexableCollection <TextDataColumn>(_listIndex); }
/// <summary> /// /// </summary> public TextDataParameterCollection() { _listIndex = new ListIndex <TextDataParameter>("List"); _nameIndex = new UniqueIndex <string, TextDataParameter>( "Name", parameter => GetKeyResponse.Create(true, parameter.ParameterName), SortOrder.None); _collection = new IndexableCollection <TextDataParameter>(_listIndex); _collection.Indexes.Add(_nameIndex); }
public static SqlPreCommand DropIndex(UniqueIndex ix) { if (ix.ViewName == null) { return(DropIndex(ix.Table.Name, ix.IndexName)); } else { return(DropViewIndex(new ObjectName(ix.Table.Name.Schema, ix.ViewName), ix.IndexName)); } }
private static SqlPreCommand RemoveDuplicates(UniqueIndex uniqueIndex, IColumn primaryKey, string columns, bool commentedOut) { return(new SqlPreCommandSimple($@"DELETE {uniqueIndex.Table.Name} WHERE {primaryKey.Name} NOT IN ( SELECT MIN({primaryKey.Name}) FROM {uniqueIndex.Table.Name} {(string.IsNullOrWhiteSpace(uniqueIndex.Where) ? "" : "WHERE " + uniqueIndex.Where)} GROUP BY {columns} ){(string.IsNullOrWhiteSpace(uniqueIndex.Where) ? "" : " AND " + uniqueIndex.Where)}".Let(txt => commentedOut ? txt.Indent(2, '-') : txt))); }
/// <summary> /// /// </summary> public ConfigurationAttributeCollection() { _listIndex = new ListIndex <ConfigurationAttribute>("List"); _nameIndex = new UniqueIndex <string, ConfigurationAttribute>( "NameIndex", attribute => GetKeyResponse.Create(true, attribute.Name), SortOrder.None); _collection = new IndexableCollection <ConfigurationAttribute>(_listIndex); _collection.Indexes.Add(_nameIndex); }
public void GetCreateScript_CreateScriptIsCorrect() { // Arrange var index = new UniqueIndex<MyTable>("MyIndex", "MyTable"); index.AddColumn(m => m.MyColumn); // Act var createScripts = index.GetUpScript(); // Assert Assert.Equal(1, createScripts.Count); Assert.Equal("CREATE UNIQUE INDEX MyIndex \r\nON MyTable(MyColumn)\r\n", createScripts.First()); }
static SessionMonitor() { linkedListIndex = new LinkedListIndex <SessionData>("LinkedList"); idIndex = new UniqueIndex <String, SessionData>( "Id", delegate(SessionData sessionData, out String sessionId) { sessionId = sessionData.SessionId; return(true); }, false); sessions = new IndexableCollection <SessionData>(linkedListIndex); sessions.Indexes.Add(idIndex); }
public void AddItem(IQueueItem item) { lock (this) { bool canBeAdded = item.UniqueKey == null || !UniqueIndex.Contains(item.UniqueKey); if (canBeAdded) { Queue.Add(item as InMemoryQueueItem); if (item.UniqueKey != null) { UniqueIndex.Add(item.UniqueKey); } } } }
/// <summary> /// /// </summary> /// <param name="maximumConcurrencyLevel"></param> /// <param name="timerPeriod"></param> public MemoryCache(int maximumConcurrencyLevel, TimeSpan timerPeriod) { this.keyIndex = new UniqueIndex <string, CacheEntry>( "key", entry => GetKeyResponse.Create(true, entry.CacheItem.Key), SortOrder.None); this.absoluteExpirationIndex = new NonUniqueIndex <DateTime, CacheEntry>( "absoluteExpiration", entry => GetKeyResponse.Create(true, entry.AbsoluteExpiration), SortOrder.Ascending); this.entries = new IndexableCollection <CacheEntry>(this.keyIndex); this.entries.Indexes.Add(this.absoluteExpirationIndex); this.scheduler = new LimitedConcurrencyLevelTaskScheduler("MemoryCache", maximumConcurrencyLevel, new ConcurrentQueue <Action>()); this.timer = new Timer(this.TimerCallback, null, timerPeriod, timerPeriod); }
/// <summary> /// Creates unique constraint for the provided field, optionally make it primary key /// </summary> /// <typeparam name="TField"></typeparam> /// <param name="name"></param> /// <param name="field"></param> /// <param name="primaryKey"></param> public void MakeUnique <TField>(string name, IField <TRecord, TField> field, bool primaryKey) { if (primaryKey && this.table.PrimaryKey != null) { throw new InvalidOperationException(Properties.Resources.ErrorPrimaryKeyRedefinition(this.Name)); } this.table.ValidateField(field); IIndex <TRecord> index = new UniqueIndex <TField>(this.table, name, field); List <IIndex <TRecord> > list = this.table.Indexes[field.Order]; if (list == null) { list = new List <IIndex <TRecord> >(); this.table.Indexes[field.Order] = list; } list.Insert(0, index); if (primaryKey) { this.table.PrimaryKey = index; } }
public static SqlPreCommand?RemoveDuplicatesIfNecessary(UniqueIndex uniqueIndex, Replacements rep) { try { var primaryKey = uniqueIndex.Table.Columns.Values.Where(a => a.PrimaryKey).Only(); if (primaryKey == null) { return(null); } int count = DuplicateCount(uniqueIndex, rep); if (count == 0) { return(null); } var columns = uniqueIndex.Columns.ToString(c => c.Name.SqlEscape(), ", "); if (rep.Interactive) { if (SafeConsole.Ask($"There are {count} rows in {uniqueIndex.Table.Name} with the same {columns}. Generate DELETE duplicates script?")) { return(RemoveDuplicates(uniqueIndex, primaryKey, columns, commentedOut: false)); } return(null); } else { return(RemoveDuplicates(uniqueIndex, primaryKey, columns, commentedOut: true)); } } catch (Exception) { return(new SqlPreCommandSimple($"-- Impossible to determine duplicates in new index {uniqueIndex.IndexName}")); } }
public static SqlPreCommand RemoveDuplicatesIfNecessary(UniqueIndex uniqueIndex, Replacements rep) { try { var primaryKey = uniqueIndex.Table.Columns.Values.Where(a => a.PrimaryKey).Only(); if (primaryKey == null) { return(null); } int count = DuplicateCount(uniqueIndex, rep); if (count == 0) { return(null); } var columns = uniqueIndex.Columns.ToString(c => c.Name.SqlEscape(), ", "); if (SafeConsole.Ask($"There are {count} rows in {uniqueIndex.Table.Name} with the same {columns}. Generate DELETE duplicates script?")) { return(new SqlPreCommandSimple($@"DELETE {uniqueIndex.Table.Name} WHERE {primaryKey.Name} NOT IN ( SELECT MIN({primaryKey.Name}) FROM {uniqueIndex.Table.Name} GROUP BY {columns} )")); } return(null); } catch (Exception e) { return(new SqlPreCommandSimple($"-- Impossible to determine duplicates in new index {uniqueIndex.IndexName}")); } }
static TypeNameCollection() { NameIndex = new UniqueIndex <string, TypeCollectionItem>( "Name", item => GetKeyResponse.Create(true, item.Name), SortOrder.None); TypeIndex = new UniqueIndex <Type, TypeCollectionItem>( "Type", item => GetKeyResponse.Create(true, item.Type), new Dictionary <Type, TypeCollectionItem>(TypeEqualityComparer.Instance)); Collection = new IndexableCollection <TypeCollectionItem>(NameIndex); Collection.Indexes.Add(TypeIndex); Add(CSharpTypeName.Boolean, typeof(bool)); Add(CSharpTypeName.Char, typeof(char)); Add(CSharpTypeName.String, typeof(string)); Add(CSharpTypeName.Object, typeof(object)); Add(CSharpTypeName.SByte, typeof(sbyte)); Add(CSharpTypeName.Int16, typeof(short)); Add(CSharpTypeName.Int32, typeof(int)); Add(CSharpTypeName.Int64, typeof(long)); Add(CSharpTypeName.Byte, typeof(byte)); Add(CSharpTypeName.UInt16, typeof(ushort)); Add(CSharpTypeName.UInt32, typeof(uint)); Add(CSharpTypeName.UInt64, typeof(ulong)); Add(CSharpTypeName.Single, typeof(float)); Add(CSharpTypeName.Double, typeof(double)); Add(CSharpTypeName.Decimal, typeof(decimal)); Add(TypeName.DateTime, typeof(DateTime)); Add(TypeName.XmlNode, typeof(XmlNode)); SystemAssembly = Assembly.GetAssembly(typeof(int)); }
/// <summary> /// /// </summary> /// <typeparam name="TField1"></typeparam> /// <typeparam name="TField2"></typeparam> /// <param name="name"></param> /// <param name="field1"></param> /// <param name="field2"></param> /// <param name="unique"></param> private void CreateIndex <TField1, TField2>(string name, IField <TRecord, TField1> field1, IField <TRecord, TField2> field2, bool unique) { this.table.ValidateField(field1); this.table.ValidateField(field2); if (field1 == field2) { throw new ArgumentException(Properties.Resources.ErrorCompositeFields); } CompositeField <TField1, TField2> field = new CompositeField <TField1, TField2>(field1, field2); IFieldIndex <Composite <TField1, TField2> > index; if (unique) { index = new UniqueIndex <Composite <TField1, TField2> >(this.table, name, field); } else { index = new RangeIndex <Composite <TField1, TField2> >(this.table, name, field); } List <IIndex <TRecord> > list1 = this.table.Indexes[field1.Order]; if (list1 == null) { list1 = new List <IIndex <TRecord> >(); this.table.Indexes[field1.Order] = list1; } List <IIndex <TRecord> > list2 = this.table.Indexes[field2.Order]; if (list2 == null) { list2 = new List <IIndex <TRecord> >(); this.table.Indexes[field2.Order] = list2; } list1.Add(index); list2.Add(index); }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { /// Generic Conventions modelBuilder.Conventions.Remove <PluralizingTableNameConvention>(); modelBuilder.Conventions.Add(new AttributeToColumnAnnotationConvention <DefaultValueAttribute, string>(DefaultValueSqlServerMigrationSqlGenerator.AnnotationName, (p, attributes) => attributes.Select(_ => _.Value.ToString()).SingleOrDefault())); modelBuilder.Conventions.Add(new AttributeToColumnAnnotationConvention <UniqueIndex, string>(UniqueSqlServerMigrationSqlGenerator.AnnotationName, (p, attributes) => attributes.Select(_ => UniqueIndex.SerializeToString(_)).SingleOrDefault())); // /// Supporting Entities modelBuilder.Configurations.Add(new ApplicationUserConfiguration()); modelBuilder.Configurations.Add(new ApplicationUserTokenConfiguration()); modelBuilder.Configurations.Add(new AppInstanceConfiguration()); // base.OnModelCreating(modelBuilder); }
public void SetUp() { SUT = new UniqueIndex<string, double>(); }
// ReSharper disable once CSharpWarnings::CS0659 public override bool Equals(object obj) { var pkey = obj as PrimaryKey; return(UniqueIndex.Equals(pkey.UniqueIndex)); }
public void SetUp() { SUT = new UniqueIndex <string, double>(); }