Пример #1
0
        private static int DoIndex(IndexOptions opts)
        {
            using (var builder = IndexFactory.CreateBuilder(new PersistentIndexName(".", opts.DictionaryType, opts.FieldsType, opts.PostingType, opts.TextEncoding)))
            {
                builder.Start();

                var timer     = Stopwatch.StartNew();
                var documents = 0;
                foreach (var file in Directory.EnumerateFiles(opts.InputPath, opts.Filter, SearchOption.AllDirectories).Select(f => new FileInfo(f)))
                {
                    PrintConsole(ConsoleColor.Gray, $"{file.FullName}");
                    if (opts.InputType == "text")
                    {
                        builder.AddFile(
                            file.FullName,
                            "{filename:\"" + file.FullName + "\", size:\"" + file.Length + "\", created:\"" + file.CreationTime.ToString("o") + "\"}");
                    }
                    else if (opts.InputType == "name")
                    {
                        builder.AddText(
                            file.FullName,
                            "{filename:\"" + file.FullName + "\", size:\"" + file.Length + "\", created:\"" + file.CreationTime.ToString("o") + "\"}");
                    }
                    else
                    {
                        throw new Exception("Unsupported input type");
                    }
                    ++documents;
                }
                var stat = builder.StopAndWait();
                PrintConsole(ConsoleColor.White, $"Indexed documents: {documents}, terms: {stat.Terms}, occurrences: {stat.Occurrences}, time: {timer.Elapsed}");
            }

            return(0);
        }
Пример #2
0
 /// <summary>
 ///   Initializes a new instance of the Fallen-8 class.
 /// </summary>
 public Fallen8()
 {
     IndexFactory   = new IndexFactory();
     _graphElements = new List <AGraphElement>();
     ServiceFactory = new ServiceFactory(this);
     IndexFactory.Indices.Clear();
 }
Пример #3
0
        public RedisIndexedStore(
            IRedisDatabaseConnector connection,
            ISerializer serializer,
            CollectionWithIndexesSettings <TValue> settings) :
            base(
                connection,
                serializer,
                settings)
        {
            var indexFactory = new IndexFactory <TValue>(CollectionRootName, Expiry, serializer, MasterKeyExtractor);

            _indexManagers = settings.Indexes
                             .Where(index => index.WithPayload)
                             .Select(
                indexDefinition =>
                indexFactory.CreatePayloadIndex(indexDefinition.Unique, indexDefinition.Extractor,
                                                indexDefinition.Name))
                             .Concat(
                settings.Indexes
                .Where(index => !index.WithPayload)
                .Select(
                    indexDefinition =>
                    indexFactory.CreateKeyedIndex(indexDefinition.Unique, indexDefinition.Extractor,
                                                  key => Get(key), indexDefinition.Name))

                //todo  USE THE ASYNC API TO PASS Get(key)
                );
        }
Пример #4
0
 private static void LoadIndices(Fallen8 fallen8, IndexFactory indexFactory, List <String> indexStreams)
 {
     //load the indices
     for (var i = 0; i < indexStreams.Count; i++)
     {
         LoadAnIndex(indexStreams[i], fallen8, indexFactory);
     }
 }
        public void DeleteAllIndicesIntegrationTest()
        {
            Assert.Inconclusive("TODO.");

            var target = new IndexFactory(); // TODO: Initialize to an appropriate value

            target.DeleteAllIndices();
        }
Пример #6
0
        private static int DoSearch(SearchOptions opts)
        {
            var timer          = Stopwatch.StartNew();
            var documentsCount = 0;
            var matchesCount   = 0;

            using (var index = IndexFactory.OpenIndex(new PersistentIndexName(".")))
            {
                var searchQuery = index.Compile(opts.Query);
                var prevDoc     = Occurrence.NoId;
                var doc         = default(TextDocument);
                var hits        = new SortedSet <int>();
                foreach (var match in searchQuery.AsEnumerable())
                {
                    if (match.DocumentId != prevDoc)
                    {
                        if (prevDoc != Occurrence.NoId)
                        {
                            PrintConsole(ConsoleColor.Gray, String.Empty);

                            PrintConsole(ConsoleColor.Gray, "====================");
                            doc = new TextDocument(index.GetText(prevDoc, 1UL).ReadToEnd(),
                                                   index.GetPositions(prevDoc, 1UL));
                            PrintConsole(ConsoleColor.Green, doc.Annotate(hits));
                            PrintConsole(ConsoleColor.Gray, "====================");
                            PrintConsole(ConsoleColor.Gray, String.Empty);
                            hits.Clear();
                        }

                        PrintConsole(ConsoleColor.Gray, index.Fields.GetMetadata(match.DocumentId));
                        prevDoc = match.DocumentId;
                        documentsCount++;
                    }
                    ++matchesCount;
                    foreach (var o in match.GetOccurrences())
                    {
                        hits.Add((int)o.TokenId);
                    }
                    PrintConsole(ConsoleColor.Gray, $"{match} ");
                }
                if (prevDoc != Occurrence.NoId)
                {
                    PrintConsole(ConsoleColor.Gray, String.Empty);

                    PrintConsole(ConsoleColor.Gray, "====================");
                    doc = new TextDocument(index.GetText(prevDoc, 1UL).ReadToEnd(),
                                           index.GetPositions(prevDoc, 1UL));
                    PrintConsole(ConsoleColor.Green, doc.Annotate(hits));
                    PrintConsole(ConsoleColor.Gray, "====================");
                    PrintConsole(ConsoleColor.Gray, String.Empty);
                    hits.Clear();
                }
            }

            PrintConsole(ConsoleColor.White, $"Documents found: {documentsCount}, matches: {matchesCount}, time: {timer.Elapsed}");
            return(0);
        }
        public void GetAvailableIndexPluginsIntegrationTest()
        {
            Assert.Inconclusive("TODO.");

            var target = new IndexFactory();      // TODO: Initialize to an appropriate value
            IEnumerable <string> expected = null; // TODO: Initialize to an appropriate value
            IEnumerable <string> actual;

            actual = target.GetAvailableIndexPlugins();
            Assert.AreEqual(expected, actual);
        }
Пример #8
0
        public static void Read(
            Dictionary <string, UserTable> userTables,
            IDataReader reader)
        {
            var factory = new IndexFactory(reader);

            while (reader.Read())
            {
                factory.CreateIndex(userTables, reader);
            }
        }
Пример #9
0
        public static IFullTextIndex AddToIndex(IIndexName indexName, string text)
        {
            using (var builder = IndexFactory.CreateBuilder(indexName))
            {
                builder.Start();
                builder.AddText(text, null);
                builder.StopAndWait();
            }

            return(IndexFactory.OpenIndex(indexName));
        }
Пример #10
0
        public void Dispose()
        {
            TabulaRasa();

            _graphElements = null;

            IndexFactory.DeleteAllIndices();
            IndexFactory = null;

            ServiceFactory.ShutdownAllServices();
            ServiceFactory = null;
        }
        public void TryDeleteIndexIntegrationTest()
        {
            Assert.Inconclusive("TODO.");

            var    target    = new IndexFactory(); // TODO: Initialize to an appropriate value
            string indexName = string.Empty;       // TODO: Initialize to an appropriate value
            bool   expected  = false;              // TODO: Initialize to an appropriate value
            bool   actual;

            actual = target.TryDeleteIndex(indexName);
            Assert.AreEqual(expected, actual);
        }
Пример #12
0
        private static int DoPrint(PrintOptions opts)
        {
            var timer = Stopwatch.StartNew();

            using (var index = IndexFactory.OpenIndex(new PersistentIndexName(".")))
            {
                var visitor = new PrintVisitor(index);
                index.Visit(visitor);
                PrintConsole(ConsoleColor.White, $"Terms: {visitor.Terms}, time: {timer.Elapsed}");
            }
            return(0);
        }
Пример #13
0
        public bool IndexScan(out ReadOnlyCollection <AGraphElement> result, String indexId, IComparable literal,
                              BinaryOperator binOp)
        {
            IIndex index;

            if (!IndexFactory.TryGetIndex(out index, indexId))
            {
                result = null;
                return(false);
            }

            #region binary operation

            switch (binOp)
            {
            case BinaryOperator.Equals:
                if (!index.TryGetValue(out result, literal))
                {
                    result = null;
                    return(false);
                }
                break;

            case BinaryOperator.Greater:
                result = FindElementsIndex(BinaryGreaterMethod, literal, index);
                break;

            case BinaryOperator.GreaterOrEquals:
                result = FindElementsIndex(BinaryGreaterOrEqualMethod, literal, index);
                break;

            case BinaryOperator.LowerOrEquals:
                result = FindElementsIndex(BinaryLowerOrEqualMethod, literal, index);
                break;

            case BinaryOperator.Lower:
                result = FindElementsIndex(BinaryLowerMethod, literal, index);
                break;

            case BinaryOperator.NotEquals:
                result = FindElementsIndex(BinaryNotEqualsMethod, literal, index);
                break;

            default:
                result = null;
                return(false);
            }

            #endregion

            return(result.Count > 0);
        }
Пример #14
0
        public static async Task ReadAsync(
            Dictionary <string, UserTable> userTables,
            DbDataReader reader,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            var factory = new IndexFactory(reader);

            while (await reader.ReadAsync(cancellationToken))
            {
                cancellationToken.ThrowIfCancellationRequested();
                factory.CreateIndex(userTables, reader);
            }
        }
Пример #15
0
        public void TryGetIndexUnitTest()
        {
            Assert.Inconclusive("TODO");

            var    target        = new IndexFactory(); // TODO: Initialize to an appropriate value
            IIndex index         = null;               // TODO: Initialize to an appropriate value
            IIndex indexExpected = null;               // TODO: Initialize to an appropriate value
            string indexName     = string.Empty;       // TODO: Initialize to an appropriate value
            bool   expected      = false;              // TODO: Initialize to an appropriate value
            bool   actual;

            actual = target.TryGetIndex(out index, indexName);
            Assert.AreEqual(indexExpected, index);
            Assert.AreEqual(expected, actual);
        }
Пример #16
0
        public static IFullTextIndex PrepareIndexForSearch(IIndexName indexName)
        {
            using (var builder = IndexFactory.CreateBuilder(indexName))
            {
                builder.Start();
                builder.AddText("Hello World!", null);
                builder.AddText("Petro Petrolium Petrol", null);
                builder.AddText("This is test document for search unit tests", null);
                builder.AddText("This test document is used for search operators", null);
                builder.AddText("This full-text search only supports boolean operators: and, or", null);
                builder.AddText("Programming is very exciting. Programs can help. This is fantastic!!!", null);
                builder.StopAndWait();
            }

            return(IndexFactory.OpenIndex(indexName));
        }
        public void TryCreateIndexIntegrationTest()
        {
            Assert.Inconclusive("TODO.");

            var    target        = new IndexFactory();     // TODO: Initialize to an appropriate value
            IIndex index         = null;                   // TODO: Initialize to an appropriate value
            IIndex indexExpected = null;                   // TODO: Initialize to an appropriate value
            string indexName     = string.Empty;           // TODO: Initialize to an appropriate value
            string indexTypeName = string.Empty;           // TODO: Initialize to an appropriate value
            IDictionary <string, object> parameter = null; // TODO: Initialize to an appropriate value
            bool expected = false;                         // TODO: Initialize to an appropriate value
            bool actual;

            actual = target.TryCreateIndex(out index, indexName, indexTypeName, parameter);
            Assert.AreEqual(indexExpected, index);
            Assert.AreEqual(expected, actual);
        }
Пример #18
0
        public void TabulaRasa()
        {
            if (WriteResource())
            {
                _currentId     = 0;
                _graphElements = new List <AGraphElement>();
                IndexFactory.DeleteAllIndices();
                VertexCount = 0;
                EdgeCount   = 0;

                FinishWriteResource();

                return;
            }

            throw new CollisionException(this);
        }
Пример #19
0
        public IDocumentCollection <TDocument> CreateHighSecurityFileSystemCollection <TDocument>(string dirPath, byte[] key) where TDocument : AbstractDocument, new()
        {
            FileSystem fileSystem = new FileSystem();

            if (!fileSystem.DirectoryExists(dirPath))
            {
                fileSystem.CreateDirectory(dirPath);
            }
            string        path          = HashedPathGenerator.GetPath(dirPath, "_journal");
            JournalPlayer journalPlayer = new JournalPlayer(path, fileSystem);
            JournalWriter journalWriter = new JournalWriter(path, fileSystem);
            string        path2         = HashedPathGenerator.GetPath(dirPath, "_packedFile");
            string        path3         = HashedPathGenerator.GetPath(dirPath, "_packedFileMeta");
            PackedFile    packedFile    = new PackedFile(path2, path3, journalWriter, fileSystem);
            IndexFactory  indexFactory  = new IndexFactory(dirPath, journalWriter, fileSystem);

            return(new DocumentCollection <TDocument>(packedFile, indexFactory, key, journalPlayer, journalWriter));
        }
Пример #20
0
        private static void LoadAnIndex(string indexLocaion, Fallen8 fallen8, IndexFactory indexFactory)
        {
            //if there is no savepoint file... do nothing
            if (!File.Exists(indexLocaion))
            {
                return;
            }

            using (var file = File.Open(indexLocaion, FileMode.Open, FileAccess.Read))
            {
                var reader = new SerializationReader(file);

                var indexName       = reader.ReadString();
                var indexPluginName = reader.ReadString();

                indexFactory.OpenIndex(indexName, indexPluginName, reader, fallen8);
            }
        }
Пример #21
0
        private static int DoLookup(LookupOptions opts)
        {
            var pattern    = opts.Pattern;
            var timer      = Stopwatch.StartNew();
            var termsFound = 0;

            using (var index = IndexFactory.OpenIndex(new PersistentIndexName(".")))
            {
                var matcher = index.CompilePattern(pattern);
                var terms   = index.GetTerms(matcher);
                foreach (var term in terms)
                {
                    ++termsFound;
                    PrintConsole(ConsoleColor.Gray, term.Key);
                }
            }

            PrintConsole(ConsoleColor.White, $"Terms found: {termsFound}, time: {timer.Elapsed}");
            return(0);
        }
Пример #22
0
        public bool SpatialIndexScan(out ReadOnlyCollection <AGraphElement> result, String indexId, IGeometry geometry)
        {
            IIndex index;

            if (!IndexFactory.TryGetIndex(out index, indexId))
            {
                result = null;
                return(false);
            }

            var spatialIndex = index as ISpatialIndex;

            if (spatialIndex != null)
            {
                return(spatialIndex.TryGetValue(out result, geometry));
            }

            result = null;
            return(false);
        }
Пример #23
0
        public bool FulltextIndexScan(out FulltextSearchResult result, String indexId, string searchQuery)
        {
            IIndex index;

            if (!IndexFactory.TryGetIndex(out index, indexId))
            {
                result = null;
                return(false);
            }

            var fulltextIndex = index as IFulltextIndex;

            if (fulltextIndex != null)
            {
                return(fulltextIndex.TryQuery(out result, searchQuery));
            }

            result = null;
            return(false);
        }
Пример #24
0
        public bool RangeIndexScan(out ReadOnlyCollection <AGraphElement> result, String indexId, IComparable leftLimit,
                                   IComparable rightLimit, bool includeLeft, bool includeRight)
        {
            IIndex index;

            if (!IndexFactory.TryGetIndex(out index, indexId))
            {
                result = null;
                return(false);
            }

            var rangeIndex = index as IRangeIndex;

            if (rangeIndex != null)
            {
                return(rangeIndex.Between(out result, leftLimit, rightLimit, includeLeft, includeRight));
            }

            result = null;
            return(false);
        }
Пример #25
0
        private KeyValuePair <Filter, IConcreteIndex> TryGetFilterWithIndex(ICollection <Filter> sameTableFilters)
        {
            var indexFactory = new IndexFactory(KeyValue.GetDatabaseFileName(database.Name), repository);
            var table        = database.Tables.Single(t => t.Name == sameTableFilters.First().Table);

            foreach (var filter in sameTableFilters)
            {
                var associations = database.Associations.Where(a => a.Child == table.Name && a.ColumnMappings.Values.Contains(filter.Column) && a.ColumnMappings.Count == 1);

                if (associations.Any())
                {
                    var association = associations.First();
                    var parentTable = database.Tables.Single(t => t.Name == association.Parent);
                    var indexMeta   = parentTable.Indexes.Where(i => i.Name.Equals(association.Name)).Single();
                    var index       = indexFactory.GetIndex(indexMeta);

                    return(new KeyValuePair <Filter, IConcreteIndex>(filter, index));
                }
            }

            return(new KeyValuePair <Filter, IConcreteIndex>(filters.First(), null));
        }
Пример #26
0
        /// <summary>
        ///   Load Fallen-8 from a save point
        /// </summary>
        /// <param name="fallen8">Fallen-8</param>
        /// <param name="graphElements">The graph elements </param>
        /// <param name="pathToSavePoint">The path to the save point.</param>
        /// <param name="currentId">The maximum graph element id</param>
        /// <param name="startServices">Start the services</param>
        internal static Boolean Load(Fallen8 fallen8, ref BigList <AGraphElement> graphElements, string pathToSavePoint, ref Int32 currentId, Boolean startServices)
        {
            //if there is no savepoint file... do nothing
            if (!File.Exists(pathToSavePoint))
            {
                Logger.LogError(String.Format("Fallen-8 could not be loaded because the path \"{0}\" does not exist.", pathToSavePoint));

                return(false);
            }

            var pathName = Path.GetDirectoryName(pathToSavePoint);
            var fileName = Path.GetFileName(pathToSavePoint);

            Logger.LogInfo(String.Format("Now loading file \"{0}\" from path \"{1}\"", fileName, pathName));

            using (var file = File.Open(pathToSavePoint, FileMode.Open, FileAccess.Read))
            {
                var reader = new SerializationReader(file);
                currentId = reader.ReadInt32();

                #region graph elements

                //initialize the list of graph elements
                var graphElementStreams           = new List <String>();
                var numberOfGraphElemementStreams = reader.ReadOptimizedInt32();
                for (var i = 0; i < numberOfGraphElemementStreams; i++)
                {
                    var graphElementBunchFilename = Path.Combine(pathName, reader.ReadOptimizedString());
                    Logger.LogInfo(String.Format("Found graph element bunch {0} here: \"{1}\"", i, graphElementBunchFilename));

                    graphElementStreams.Add(graphElementBunchFilename);
                }

                LoadGraphElements(graphElements, graphElementStreams);

                #endregion

                #region indexe

                var indexStreams         = new List <String>();
                var numberOfIndexStreams = reader.ReadOptimizedInt32();
                for (var i = 0; i < numberOfIndexStreams; i++)
                {
                    var indexFilename = Path.Combine(pathName, reader.ReadOptimizedString());
                    Logger.LogInfo(String.Format("Found index number {0} here: \"{1}\"", i, indexFilename));

                    indexStreams.Add(indexFilename);
                }
                var newIndexFactory = new IndexFactory();
                LoadIndices(fallen8, newIndexFactory, indexStreams);
                fallen8.IndexFactory = newIndexFactory;

                #endregion

                #region services

                var serviceStreams         = new List <String>();
                var numberOfServiceStreams = reader.ReadOptimizedInt32();
                for (var i = 0; i < numberOfServiceStreams; i++)
                {
                    var serviceFilename = Path.Combine(pathName, reader.ReadOptimizedString());
                    Logger.LogInfo(String.Format("Found service number {0} here: \"{1}\"", i, serviceFilename));

                    serviceStreams.Add(serviceFilename);
                }
                var newServiceFactory = new ServiceFactory(fallen8);
                fallen8.ServiceFactory = newServiceFactory;
                LoadServices(fallen8, newServiceFactory, serviceStreams, startServices);

                #endregion

                return(true);
            }
        }
Пример #27
0
        static void Main(string[] args)
        {
            PrintConsole(ConsoleColor.Green, "PMS Full-Text Search (c) Petro Protsyk 2017-2018");
            if (args.Length < 1)
            {
                PrintHelp();
                return;
            }

            if (args[0] == "index")
            {
                var fieldsType = (args.Length > 3 && args[2] == "--fieldsType") ? args[3] : "List";
                using (var builder = IndexFactory.CreateBuilder(new PersistentIndexName(".", fieldsType)))
                {
                    builder.Start();

                    var timer     = Stopwatch.StartNew();
                    var documents = 0;
                    foreach (var file in Directory.EnumerateFiles(args[1], "*.txt", SearchOption.AllDirectories).Select(f => new FileInfo(f)))
                    {
                        PrintConsole(ConsoleColor.Gray, $"{file.FullName}");
                        builder.AddFile(
                            file.FullName,
                            "{filename:\"" + file.FullName + "\", size:\"" + file.Length + "\", created:\"" + file.CreationTime.ToString("o") + "\"}");
                        ++documents;
                    }
                    builder.StopAndWait();
                    PrintConsole(ConsoleColor.White, $"Indexed documents: {documents}, time: {timer.Elapsed}");
                }
            }
            else if (args[0] == "search")
            {
                var timer          = Stopwatch.StartNew();
                var documentsCount = 0;
                var matchesCount   = 0;
                using (var index = IndexFactory.OpenIndex(new PersistentIndexName(".")))
                {
                    using (var compiler = new FullTextQueryCompiler(index))
                    {
                        var searchQuery = compiler.Compile(args[1]);
                        var prevDoc     = Occurrence.NoId;
                        foreach (var match in searchQuery.AsEnumerable())
                        {
                            if (match.DocumentId != prevDoc)
                            {
                                if (prevDoc != Occurrence.NoId)
                                {
                                    PrintConsole(ConsoleColor.Gray, String.Empty);
                                }

                                PrintConsole(ConsoleColor.Gray, index.Fields.GetMetadata(match.DocumentId));
                                prevDoc = match.DocumentId;
                                documentsCount++;
                            }
                            ++matchesCount;
                            PrintConsole(ConsoleColor.Gray, $"{match} ");
                        }
                        if (prevDoc != Occurrence.NoId)
                        {
                            PrintConsole(ConsoleColor.Gray, String.Empty);
                        }
                    }
                }

                PrintConsole(ConsoleColor.White, $"Documents found: {documentsCount}, matches: {matchesCount}, time: {timer.Elapsed}");
            }
            else if (args[0] == "print")
            {
                var timer = Stopwatch.StartNew();
                var terms = 0;
                using (var index = IndexFactory.OpenIndex(new PersistentIndexName(".")))
                {
                    index.Visit(new PrintVisitor(index));
                    ++terms;
                }

                PrintConsole(ConsoleColor.White, $"Terms: {terms}, time: {timer.Elapsed}");
            }
            else if (args[0] == "lookup")
            {
                var timer      = Stopwatch.StartNew();
                var termsFound = 0;
                using (var index = IndexFactory.OpenIndex(new PersistentIndexName(".")))
                {
                    int tilda = args[1].IndexOf("~");
                    IEnumerable <DictionaryTerm> terms = null;
                    if (tilda == -1)
                    {
                        terms = index.GetTerms(args[1]);
                    }
                    else
                    {
                        terms = index.GetTerms(args[1].Substring(0, tilda), int.Parse(args[1].Substring(tilda + 1)));
                    }

                    foreach (var term in terms)
                    {
                        ++termsFound;
                        PrintConsole(ConsoleColor.Gray, term.Key);
                    }
                }
                PrintConsole(ConsoleColor.White, $"Terms found: {termsFound}, time: {timer.Elapsed}");
            }
        }
        public void IndexFactoryConstructorIntegrationTest()
        {
            Assert.Inconclusive("TODO.");

            var target = new IndexFactory();
        }
Пример #29
0
        public ReturnStatus Delete(Database database, Table table, ICollection <Filter> filters)
        {
            string databaseFileName  = KeyValue.GetDatabaseFileName(database.Name);
            var    planner           = new SimpleExecutionPlanner(database, repository, new List <Selection>(), new List <Join>(), filters);
            var    rootOperation     = planner.GetRootOperation();
            var    nonKeyColumnNames = table.Columns.Where(c => !table.PrimaryKey.Contains(c.Name)).Select(c => c.Name).ToList();

            var metadata = rootOperation.GetMetadata();
            var rows     = rootOperation.Execute();

            ReturnStatus status = new ReturnStatus();

            var indexFactory = new IndexFactory(databaseFileName, repository);

            var rowsToDelete = new List <string>();
            var rowData      = new List <KeyValuePair <string, string> >();

            foreach (var row in rows)
            {
                rowsToDelete.Add(row.Key);
                rowData.Add(row);
            }

            foreach (var row in rowsToDelete)
            {
                // Check foreign key constraints.
                foreach (var association in database.GetAssociationsWhereTableIsParent(table.Name))
                {
                    var indexMeta = table.Indexes.Where(i => i.Name.Equals(association.Name)).Single();
                    var index     = indexFactory.GetIndex(indexMeta);

                    var foreignKey = string.Empty;

                    if (index.Exists(row))
                    {
                        status.ReturnCode = ReturnCode.ForeignKeyConstraintFailed;
                        status.Message    = string.Format("Foreign key constraint check failed, the key [{0}] is referenced in {1}.", row, association.Child);

                        return(status);
                    }
                }
            }

            foreach (var row in rowData)
            {
                // Delete unique indexes.
                foreach (var uniqueIndex in table.Indexes.Where(i => i.Unique))
                {
                    var index = indexFactory.GetIndex(uniqueIndex);

                    var columnValues = new List <string>();

                    foreach (var column in uniqueIndex.IndexMembers)
                    {
                        columnValues.Add(KeyValue.Split(row.Value).ElementAt(KeyValue.Split(metadata.Value).ToList().IndexOf(column)));
                    }

                    var uniqueKey = KeyValue.Concatenate(columnValues);
                    index.Delete(uniqueKey);
                }

                // Delete foreign key indexes.
                foreach (var association in database.GetAssociationsWhereTableIsChild(table.Name))
                {
                    var parentTable = database.GetTable(association.Parent);
                    var indexMeta   = parentTable.Indexes.Where(i => i.Name.Equals(association.Name)).Single();
                    var index       = indexFactory.GetIndex(indexMeta);

                    var foreignKey = string.Empty;
                    if (table.PrimaryKey.Contains(association.ColumnMappings.Values.First()))
                    {
                        foreignKey = KeyValue.Split(row.Key).ElementAt(table.PrimaryKey.IndexOf(association.ColumnMappings.Values.First()));
                    }
                    else
                    {
                        foreignKey = KeyValue.Split(row.Value).ElementAt(nonKeyColumnNames.IndexOf(association.ColumnMappings.Values.First()));
                    }

                    index.Delete(foreignKey, row.Key);
                }
            }

            foreach (var rowToDelete in rowsToDelete)
            {
                // Delete primary key and data.
                repository.Delete(databaseFileName, table.Name, rowToDelete);
            }


            status.ReturnCode = ReturnCode.Success;
            status.Message    = string.Format("({0} row(s) affected)", rowsToDelete.Count);

            return(status);
        }
Пример #30
0
        public ReturnStatus Insert(Database database, Table table, ICollection <string> keyMembers, ICollection <string> values)
        {
            string databaseFileName = KeyValue.GetDatabaseFileName(database.Name);
            string key   = KeyValue.Concatenate(keyMembers);
            string value = KeyValue.Concatenate(values);

            ReturnStatus status = new ReturnStatus();

            // Check primary key constraints.
            if (repository.Exists(databaseFileName, table.Name, key))
            {
                status.ReturnCode = ReturnCode.PrimaryKeyConstraintFailed;
                status.Message    = string.Format("Primary key constraint check failed for primary key: {0}", key);

                return(status);
            }

            // Check unique index constraints.
            var uniqueIndexes   = new IConcreteIndex[table.Indexes.Where(i => i.Unique).Count()];
            var uniqueIndexKeys = new string[table.Indexes.Where(i => i.Unique).Count()];

            var indexFactory = new IndexFactory(databaseFileName, repository);

            var counter           = 0;
            var nonKeyColumnNames = table.Columns.Where(c => !table.PrimaryKey.Contains(c.Name)).Select(c => c.Name).ToList();

            foreach (var uniqueIndex in table.Indexes.Where(i => i.Unique))
            {
                var index = indexFactory.GetIndex(uniqueIndex);
                uniqueIndexes[counter] = index;

                var columnValues = new List <string>();

                foreach (var column in uniqueIndex.IndexMembers)
                {
                    columnValues.Add(values.ElementAt(nonKeyColumnNames.IndexOf(column)));
                }

                var uniqueKey = KeyValue.Concatenate(columnValues);
                uniqueIndexKeys[counter] = uniqueKey;

                if (index.Exists(uniqueKey))
                {
                    status.ReturnCode = ReturnCode.UniqueConstraintFailed;
                    status.Message    = string.Format("Unique constraint check failed for key: {0}", uniqueKey);

                    return(status);
                }

                counter++;
            }

            // Check foreign key constraints (the key is simple).
            // Check if the key exists in the parent table.
            var foreignKeyIndexes   = new IConcreteIndex[database.GetAssociationsWhereTableIsChild(table.Name).Count()];
            var foreignKeyIndexKeys = new string[database.GetAssociationsWhereTableIsChild(table.Name).Count()];

            counter = 0;

            foreach (var association in database.GetAssociationsWhereTableIsChild(table.Name))
            {
                var parentTable = database.GetTable(association.Parent);
                var indexMeta   = parentTable.Indexes.Where(i => i.Name.Equals(association.Name)).Single();
                var index       = indexFactory.GetIndex(indexMeta);

                var foreignKey = string.Empty;
                if (table.PrimaryKey.Contains(association.ColumnMappings.Values.First()))
                {
                    foreignKey = keyMembers.ElementAt(table.PrimaryKey.IndexOf(association.ColumnMappings.Values.First()));
                }
                else
                {
                    foreignKey = values.ElementAt(nonKeyColumnNames.IndexOf(association.ColumnMappings.Values.First()));
                }

                foreignKeyIndexes[counter]   = index;
                foreignKeyIndexKeys[counter] = foreignKey;

                if (!repository.Exists(databaseFileName, parentTable.Name, foreignKey))
                {
                    status.ReturnCode = ReturnCode.ForeignKeyConstraintFailed;
                    status.Message    = string.Format("Foreign key constraint check failed, key is missing from the parent table ({0} [{1}]): {2}", parentTable.Name,
                                                      association.ColumnMappings.Keys.First(), foreignKey);

                    return(status);
                }

                counter++;
            }

            // Insert unique indexes.
            for (int k = 0; k < uniqueIndexes.Length; k++)
            {
                uniqueIndexes[k].Put(uniqueIndexKeys[k], key);
            }

            // Insert foreign key indexes.
            for (int k = 0; k < foreignKeyIndexes.Length; k++)
            {
                foreignKeyIndexes[k].Put(foreignKeyIndexKeys[k], key);
            }

            // Insert row if there is no errors.
            repository.Put(databaseFileName, table.Name, key, value);

            status.ReturnCode = ReturnCode.Success;
            status.Message    = string.Format("({0} row(s) affected)", 1);

            return(status);
        }