Exemplo n.º 1
0
        public static object ConvertTo <T>(this IDataReader dataReader, IDatabaseModel databaseModel, Dictionary <string, string> nameMappings) where T : IDatabaseModel
        {
            var model = Activator.CreateInstance <T>();

            for (int i = 0; i < dataReader.FieldCount; i++)
            {
                var propertyName = dataReader.GetName(i);

                if (nameMappings != null)
                {
                    var fieldName = nameMappings.FirstOrDefault(m => string.Equals(m.Value, propertyName)).Key;

                    if (!string.IsNullOrEmpty(fieldName))
                    {
                        propertyName = fieldName;
                    }
                }

                var propertyValue = DBNull.Value.Equals(dataReader[i]) ? null : dataReader.GetValue(i);

                var prop = model.GetType().GetProperty(propertyName);

                if (prop != null && prop.CanWrite)
                {
                    prop.SetValue(model, propertyValue, null);
                }
            }

            return(model);
        }
Exemplo n.º 2
0
        public static string GenerateUpdateFields(IDatabaseModel model)
        {
            StringBuilder StringBuilder = new StringBuilder();

            foreach (FieldInfo Field in model.GetType().GetFields(System.Reflection.BindingFlags.Public
                                                                  | System.Reflection.BindingFlags.GetField | BindingFlags.Instance))
            {
                CustomAttributeData l_ExcludeFromUpdate = Field.CustomAttributes.FirstOrDefault(customAttributes => customAttributes.AttributeType == typeof(TableFieldExcludeFromUpdateAttribute));

                if (l_ExcludeFromUpdate != null && Convert.ToBoolean(l_ExcludeFromUpdate.ConstructorArguments.First().Value))
                {
                    continue;
                }

                CustomAttributeData l_TableFieldName = Field.CustomAttributes.FirstOrDefault(customAttributes => customAttributes.AttributeType == typeof(TableFieldNameAttribute));

                if (l_TableFieldName == null)
                {
                    continue;
                }

                string FieldName  = (string)l_TableFieldName.ConstructorArguments.First().Value;
                object FieldValue = Field.GetValue(model);
                StringBuilder.Append(StringBuilder.Length == 0 ? $"{FieldName} = {SQLiteDBCommon.SetValueForSql(FieldValue)}" : $", {FieldName} = {SQLiteDBCommon.SetValueForSql(FieldValue)}");
            }

            return(StringBuilder.ToString());
        }
Exemplo n.º 3
0
        private Expense ConvertToDomain(IDatabaseModel databaseModel)
        {
            var current = databaseModel as IExpenseComposite;

            if (current == null)
            {
                return(null);
            }

            var expense = new Expense
            {
                Id       = databaseModel.Id,
                Category = new Category
                {
                    Id          = current.Category,
                    Description = current.CategoryDescription
                },
                Date        = Convert.ToDateTime(current.Date),
                Description = current.Description,
                Value       = current.Value
            };

            expense.UUID = current.UUID;
            return(expense);
        }
Exemplo n.º 4
0
 public IDatabaseContext CopyWithOverride(IDatabaseContext copied, IDatabaseModel database)
 {
     return(new ProcessorDatabaseContext()
     {
         Database = database,
     });
 }
Exemplo n.º 5
0
 public void Initialize(IInfrastructureFactory infrastructureFactory, IDatabaseModel databaseModel)
 {
     _helpProvider           = infrastructureFactory.CreateHelpProvider();
     _codeCompletionProvider = infrastructureFactory.CreateCodeCompletionProvider();
     _navigationService      = infrastructureFactory.CreateNavigationService();
     _colorizingTransformer.SetParser(infrastructureFactory.CreateParser());
     DocumentRepository = new SqlDocumentRepository(infrastructureFactory.CreateParser(), infrastructureFactory.CreateStatementValidator(), databaseModel);
 }
Exemplo n.º 6
0
        private static Dictionary <string, string> GetFieldNameMappings(IDatabaseModel databaseModel)
        {
            var nameMapping = _nameMappings
                              .Where(m => string.Equals(m.Item1, databaseModel.GetType().FullName))
                              .ToDictionary(c => c.Item2, k => k.Item3);

            return(nameMapping);
        }
Exemplo n.º 7
0
		public void Initialize(IInfrastructureFactory infrastructureFactory, IDatabaseModel databaseModel)
		{
			_helpProvider = infrastructureFactory.CreateHelpProvider();
			_codeCompletionProvider = infrastructureFactory.CreateCodeCompletionProvider();
			_navigationService = infrastructureFactory.CreateNavigationService();
			_colorizingTransformer.SetParser(infrastructureFactory.CreateParser());
			DocumentRepository = new SqlDocumentRepository(infrastructureFactory.CreateParser(), infrastructureFactory.CreateStatementValidator(), databaseModel);
		}
        public override string ProcessContext(string StringContext, IDatabaseContext databaseContext)
        {
            ControlContext(StringContext, databaseContext);
            IDatabaseModel descriptionPojo     = databaseContext.Database;
            string         TrimedStringContext = TrimContextFromContextWrapper(StringContext);
            string         result = string.Join(string.Empty, descriptionPojo.Tables.Select(currentTable =>
                                                                                            TemplateHandler.HandleTemplate(TrimedStringContext, DatabaseContextCopier.CopyWithOverride(databaseContext, currentTable))));

            return(result);
        }
Exemplo n.º 9
0
        private static string GetTableName(IDatabaseModel databaseModel)
        {
            var tableMappingName = _tableMappings.FirstOrDefault(m => string.Equals(m.Key, databaseModel.GetType().FullName)).Value;

            if (!string.IsNullOrEmpty(tableMappingName))
            {
                return(tableMappingName);
            }

            return(databaseModel.GetType().Name);
        }
        private IList <ITableModel> ExtractForeignTables(IDatabaseModel databaseModel, ITableModel tableModel)
        {
            var foreignKeyConstraints = tableModel?.ForeignKeyConstraints ?? new List <IForeignKeyConstraintModel>();
            var tableKeys             =
                foreignKeyConstraints.SelectMany(constraint =>
                                                 (constraint?.Elements ?? new List <IForeignKeyConstraintElementModel>()).Select(m => new { m.Foreign.TableName, m.Foreign.SchemaName })).Distinct().ToList();
            var foreignTables = databaseModel.Tables.InnerJoin(tableKeys, m => $"{m.Name}-{m.Schema}", m => $"{m.TableName}-{m.SchemaName}")
                                .Select(m => m.Item1).ToList();

            return(foreignTables);
        }
        public override string ProcessContext(string StringContext, IDatabaseContext databaseContext)
        {
            ControlContext(StringContext, databaseContext);
            IDatabaseModel database            = databaseContext.Database;
            string         TrimedStringContext = TrimContextFromContextWrapper(StringContext);

            if (TrimedStringContext != "")
            {
                throw new Exception($"There is a problem with the provided StringContext :'{StringContext}' to the suited word '{Signature}'");
            }
            return(database.Name);
        }
Exemplo n.º 12
0
        public void Delete(IDatabaseModel databaseModel)
        {
            #region SQLite-Net

            if (Connection != null)
            {
                var connection = Connection.GetConnection() as SQLite.Net.SQLiteConnection;
                connection.Delete(databaseModel);
            }

            #endregion
        }
Exemplo n.º 13
0
        public SqlDocumentRepository(ISqlParser parser, IStatementValidator validator, IDatabaseModel databaseModel, string statementText = null)
        {
            _parser    = parser ?? throw new ArgumentNullException(nameof(parser));
            _validator = validator ?? throw new ArgumentNullException(nameof(validator));

            _databaseModel = databaseModel;

            if (!String.IsNullOrEmpty(statementText))
            {
                UpdateStatements(statementText);
            }
        }
Exemplo n.º 14
0
        public static IDatabaseModel MapsToTable(this IDatabaseModel databaseModel, string databaseName)
        {
            if (_tableMappings == null)
            {
                _tableMappings = new Dictionary <string, string>();
            }

            if (!_tableMappings.ContainsKey(databaseModel.GetType().FullName) && !_tableMappings.ContainsValue(databaseName))
            {
                _tableMappings.Add(databaseModel.GetType().FullName, databaseName);
            }

            return(databaseModel);
        }
        public override string HandleTrimedContext(string StringTrimedContext, IDatabaseContext databaseContext)
        {
            if (StringTrimedContext == null)
            {
                return(null);
            }
            IDatabaseModel database = databaseContext.Database;

            if (database == null)
            {
                return(StringTrimedContext);
            }
            return(TemplateHandler.HandleTemplate(StringTrimedContext, databaseContext));
        }
        private Category ConvertToDomain(IDatabaseModel databaseModel)
        {
            var current = databaseModel as ICategoryDatabase;

            if (current == null)
            {
                return(null);
            }

            return(new Category
            {
                Id = databaseModel.Id,
                Description = current.Description
            });
        }
        private IList <TypeSetItem> ToTypeSetItems(IDatabaseModel databaseModel)
        {
            if (databaseModel == null)
            {
                new List <string>();
            }
            var tableModels  = databaseModel?.Tables ?? new List <ITableModel>();
            var columnModels = tableModels.SelectMany(m => m?.Columns ?? new List <IColumnModel>());

            return(columnModels.Select(m => m.Type).Distinct().Where(m => !String.IsNullOrWhiteSpace(m))
                   .Select(m => new TypeSetItem()
            {
                Name = m
            }).ToList());
        }
Exemplo n.º 18
0
        public PersistableDatabaseModel ToPersistable(IDatabaseModel converted)
        {
            if (converted == null)
            {
                return(null);
            }
            var result = new PersistableDatabaseModel();

            result.Name             = converted.Name;
            result.ConnectionString = converted.ConnectionString;
            result.TypeSetName      = converted.TypeSetName;
            if (converted.Tables != null)
            {
                result.Tables = converted.Tables.Select(ToPersistable).ToList();
            }
            return(result);
        }
Exemplo n.º 19
0
        private User ConvertToDomain(IDatabaseModel databaseModel)
        {
            var current = databaseModel as IUserDatabase;

            if (current == null)
            {
                return(null);
            }

            var user = new User
            {
                Id          = databaseModel.Id,
                Name        = current.Name,
                Password    = current.Password,
                Email       = current.Email,
                Transaction = current.Transaction
            };

            user.UUID = current.UUID;
            return(user);
        }
Exemplo n.º 20
0
        public static IDatabaseModel MapsToField(this IDatabaseModel databaseModel, Expression <Func <Object> > property, string databasePropertyName)
        {
            if (_nameMappings == null)
            {
                _nameMappings = new List <Tuple <string, string, string> >();
            }



            var propertyName = (property.Body as MemberExpression ?? ((UnaryExpression)property.Body).Operand as MemberExpression).Member.Name;

            var tuple = new Tuple <string, string, string>(databaseModel.GetType().FullName, propertyName, databasePropertyName);

            if (_nameMappings.Contains(tuple))
            {
                return(databaseModel);
            }

            _nameMappings.Add(tuple);

            return(databaseModel);
        }
Exemplo n.º 21
0
 /// <summary>
 /// Returns an empty string if the [TableName] attribute isn't added to the property
 /// </summary>
 public static string TableName(this IDatabaseModel value)
 {
     return(value.GetType()
            .GetCustomAttribute <TableNameAttribute>()
            .TableName);
 }
        public IDatabaseModel Import(string connectionString)
        {
            SqlConnection sqlConnection = new SqlConnection(connectionString);

            sqlConnection.Open();
            var databaseModels          = sqlServerDatabaseDao.GetAll(sqlConnection);
            var tableModels             = sqlServerTableDao.GetAll(sqlConnection);
            var columnModels            = sqlServerColummnDao.GetAll(sqlConnection);
            var indexColumnsModels      = sqlServerIndexColumnsDao.GetAll(sqlConnection);
            var indexesModels           = sqlServerIndexesDao.GetAll(sqlConnection);
            var schemasModels           = sqlServerSchemasDao.GetAll(sqlConnection);
            var foreignKeyModels        = sqLServerForeignKeysDao.GetAll(sqlConnection);
            var foreignKeyColumnsModels = sqlServerForeignKeyColumnsDao.GetAll(sqlConnection);

            var informationSchemaColumnModels = sqlServerInformationSchemaColumnsDao.GetAll(sqlConnection);

            sqlConnection.Close();


            var databaseAndTableModel = databaseModels
                                        .LeftJoin(tableModels, m => true, m => true)
                                        .Select(m => new { database = m.Item1, table = m.Item2 }).ToList();

            var databaseAndTableModelAndSchema = databaseAndTableModel
                                                 .LeftJoin(schemasModels, m => $"{m.table.schema_id}", m => $"{m.schema_id}")
                                                 .Select(m => new { database = m.Item1.database, table = m.Item1.table, schema = m.Item2 })
                                                 .ToList();

            var databaseAndTableModelAndSchemaAndColumnModel =
                databaseAndTableModelAndSchema
                .LeftJoin(columnModels, m => m.table.object_id, m => m.object_id)
                .Select(m => new { database = m.Item1.database, table = m.Item1.table, schema = m.Item1.schema, column = m.Item2 }).ToList();

            var indexColumnsAndIndexesSqlModels =
                indexColumnsModels.InnerJoin(indexesModels, m => $"{m.object_id}-{m.index_id}", m => $"{m.object_id}-{m.index_id}")
                .Select(m => new { indexColumn = m.Item1, index = m.Item2 }).ToList();


            IList <SqlModelJointure> sqlModelsWithIndexes =
                databaseAndTableModelAndSchemaAndColumnModel.LeftJoin(indexColumnsAndIndexesSqlModels, m => $"{m.column.object_id}-{m.column.column_id}", m => $"{m.index.object_id}-{m.indexColumn.column_id}").
                Select(m => new SqlModelJointure()
            {
                database = m.Item1.database, table = m.Item1.table, schema = m.Item1.schema,
                column   = m.Item1.column, index = m.Item2?.index, indexColumn = m.Item2?.indexColumn
            }).ToList();

            var sqlModelJointureWithColumnSchemaInformation =
                sqlModelsWithIndexes.LeftJoin(informationSchemaColumnModels, m => $"{m?.database?.database_name}-{m?.schema?.name}-{m?.table?.name}-{m?.column?.name}", m => $"{m.TABLE_CATALOG}-{m.TABLE_SCHEMA}-{m.TABLE_NAME}-{m.COLUMN_NAME}").ToList();

            sqlModelJointureWithColumnSchemaInformation.ForEach(m => m.Item1.informationSchemaColumns = m.Item2);

            IDatabaseModel databaseModel = ToDatabaseModel(connectionString, sqlModelsWithIndexes);

            databaseModel.TypeSetName = ManagedDbSystem;


            //Second step => Consraint jointure
            var foreignKeyAndForeignKeyColumns = foreignKeyColumnsModels.InnerJoin(foreignKeyModels,
                                                                                   m => $"{m.constraint_object_id}-{m.parent_object_id}-{m.referenced_object_id}",
                                                                                   m => $"{m.object_id}-{m.parent_object_id}-{m.referenced_object_id}")
                                                 .Select(m => new { foreignKeyColumn = m.Item1, foreignKey = m.Item2 }).ToList();

            var referencedKeyAndSqlModelJointure = foreignKeyAndForeignKeyColumns.InnerJoin(sqlModelsWithIndexes,
                                                                                            m => $"{m.foreignKeyColumn.referenced_object_id}-{m.foreignKeyColumn.referenced_column_id}",
                                                                                            m => $"{m.table.object_id}-{m.column.column_id}")
                                                   .Select(m => new { m.Item1.foreignKey, m.Item1.foreignKeyColumn, m.Item2.database, m.Item2.table, m.Item2.column, m.Item2.schema }).ToList();

            var foreignKeyAndSqlModelJointure = foreignKeyAndForeignKeyColumns.InnerJoin(sqlModelsWithIndexes,
                                                                                         m => $"{m.foreignKeyColumn.parent_object_id}-{m.foreignKeyColumn.parent_column_id}",
                                                                                         m => $"{m.table.object_id}-{m.column.column_id}")
                                                .Select(m => new { m.Item1.foreignKey, m.Item1.foreignKeyColumn, m.Item2.database, m.Item2.table, m.Item2.column, m.Item2.schema }).ToList();

            var foreignKeyAndReferencedKeyJointure = referencedKeyAndSqlModelJointure.InnerJoin(foreignKeyAndSqlModelJointure,
                                                                                                m => $"{m.foreignKey.object_id}-{m.foreignKey.parent_object_id}",
                                                                                                m => $"{m.foreignKey.object_id}-{m.foreignKey.parent_object_id}")
                                                     .Select(m => new SqlConstraintJointureModel
            {
                ForeignKey       = m.Item1.foreignKey,
                ReferencedTable  = m.Item1.table,
                ReferencedColumn = m.Item1.column,
                ReferenceSchema  = m.Item1.schema,
                PrimaryTable     = m.Item2.table,
                PrimaryColumn    = m.Item2.column,
                PrimarySchema    = m.Item2.schema,
            }).ToList();

            var dabaseTableConstraintGrouping = databaseModel.Tables.Cast <ImportedTableModelWithMetaData>()
                                                .LeftJoin(foreignKeyAndReferencedKeyJointure, m => $"{m?.object_id}", m => $"{m?.PrimaryTable?.object_id}")
                                                .GroupBy(m => m.Item1.object_id)
                                                .Select(m => Tuple.Create(m.First().Item1, m.Where(m => m.Item2 != null).Select(m => m.Item2).ToList()));

            databaseModel.Tables = dabaseTableConstraintGrouping.Select(m =>
                                                                        new ImportedTableModel()
            {
                Columns = m.Item1.Columns,
                Name    = m.Item1.Name,
                Schema  = m.Item1.Schema,
                ForeignKeyConstraints = ToForeignKeyConstraints(m.Item2.ToList())
            }).Cast <ITableModel>().ToList();

            return(databaseModel);
        }
Exemplo n.º 23
0
 public PublicationViewModel()
 {
     db = new DatabaseModel();
 }
Exemplo n.º 24
0
		internal ICollection<ICodeCompletionItem> ResolveItems(IDatabaseModel databaseModel, string statementText, int cursorPosition, bool forcedInvokation = true, params string[] categories)
		{
			var documentStore = new SqlDocumentRepository(OracleSqlParser.Instance, new OracleStatementValidator(), databaseModel, statementText);
			var sourceItems = ResolveItems(documentStore, databaseModel, cursorPosition, forcedInvokation);
			return sourceItems.Where(i => categories.Length == 0 || categories.Contains(i.Category)).ToArray();
		}
Exemplo n.º 25
0
 public static string GenerateStandardDeleteStatement(IDatabaseModel model, string primaryKeyFieldName, object primaryKeyValue)
 {
     return($"DELETE FROM {model.TableName()} WHERE {GetDatabaseTableFieldName(model, primaryKeyFieldName)} = {primaryKeyValue}");
 }
Exemplo n.º 26
0
 public static string GenerateStandardUpdateStatement(IDatabaseModel model, string primaryKeyFieldName, object primaryKeyValue)
 {
     return($"UPDATE {model.TableName()} SET {GenerateUpdateFields(model)} WHERE {GetDatabaseTableFieldName(model, primaryKeyFieldName)} = {primaryKeyValue}");
 }
Exemplo n.º 27
0
 public static string GenerateStandardInsertStatement(IDatabaseModel model)
 {
     return($"INSERT INTO {model.TableName()} {GenerateInsertFields(model)}");
 }
Exemplo n.º 28
0
        public void Save(string databaseModelPersistenceName, IDatabaseModel databaseModel)
        {
            var persistable = databaseModelConverter.ToPersistable(databaseModel);

            databaseModelPersistor.Save(databaseModelPersistenceName, persistable);
        }
Exemplo n.º 29
0
 public Task executeUpsert(IDatabaseModel arg0)
 {
     return(Call <Task>("executeUpsert", arg0));
 }
Exemplo n.º 30
0
        internal IEnumerable <ICodeSnippet> GetSnippets(string statementText, int cursorPosition, IDatabaseModel databaseModel)
        {
            var documentStore = new SqlDocumentRepository(OracleSqlParser.Instance, new OracleStatementValidator(), databaseModel, statementText);

            return(GetSnippets(documentStore, statementText, cursorPosition));
        }
Exemplo n.º 31
0
 public Task executeDelete(IDatabaseModel arg0)
 {
     return(Call <Task>("executeDelete", arg0));
 }
Exemplo n.º 32
0
 public PublicationViewModel(IDatabaseModel db)
 {
     this.db = db;
 }
Exemplo n.º 33
0
        //private static readonly FeastsModel _instance = new FeastsModel();

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        //static FeastsModel()
        //{
        //}

        public FeastsModel()
        {
            _databaseModel = FreshIOC.Container.Resolve <IDatabaseModel>() as DatabaseModel;
        }
Exemplo n.º 34
0
		public ICollection<ICodeCompletionItem> ResolveItems(SqlDocumentRepository sqlDocumentRepository, IDatabaseModel databaseModel, int cursorPosition, bool forcedInvokation)
		{
			if (sqlDocumentRepository?.Statements == null)
			{
				return EmptyCollection;
			}

			var completionType = new OracleCodeCompletionType(sqlDocumentRepository, sqlDocumentRepository.StatementText, cursorPosition);
			//completionType.PrintResults();

			if (completionType.InComment)
			{
				return EmptyCollection;
			}

			if (!forcedInvokation && !completionType.JoinCondition && String.IsNullOrEmpty(completionType.TerminalValuePartUntilCaret) && !completionType.IsCursorTouchingIdentifier)
			{
				return EmptyCollection;
			}

			StatementGrammarNode currentTerminal;

			var completionItems = Enumerable.Empty<ICodeCompletionItem>();
			var statement = (OracleStatement)sqlDocumentRepository.Statements.LastOrDefault(s => s.GetNodeAtPosition(cursorPosition) != null);

			if (statement == null)
			{
				statement = completionType.Statement;
				if (statement == null)
				{
					return EmptyCollection;
				}

				currentTerminal = statement.GetNearestTerminalToPosition(cursorPosition);

				if (completionType.InUnparsedData || currentTerminal == null)
				{
					return EmptyCollection;
				}
			}
			else
			{
				currentTerminal = statement.GetNodeAtPosition(cursorPosition);
				if (currentTerminal.Type == NodeType.NonTerminal)
				{
					currentTerminal = statement.GetNearestTerminalToPosition(cursorPosition);
				}
				else if (currentTerminal.Id.In(Terminals.RightParenthesis, Terminals.Comma, Terminals.Semicolon))
				{
					var precedingNode = statement.GetNearestTerminalToPosition(cursorPosition - 1);
					if (precedingNode != null)
					{
						currentTerminal = precedingNode;
					}
				}
			}

			var oracleDatabaseModel = (OracleDatabaseModelBase)databaseModel;
			var semanticModel = (OracleStatementSemanticModel)sqlDocumentRepository.ValidationModels[statement].SemanticModel;

			var cursorAtLastTerminal = cursorPosition <= currentTerminal.SourcePosition.IndexEnd + 1;
			var terminalToReplace = completionType.ReferenceIdentifier.IdentifierUnderCursor;

			var referenceContainers = GetReferenceContainers(semanticModel.MainObjectReferenceContainer, completionType.CurrentQueryBlock);

			var extraOffset = currentTerminal.SourcePosition.ContainsIndex(cursorPosition) && !currentTerminal.Id.In(Terminals.LeftParenthesis, Terminals.Dot) ? 1 : 0;

			if (completionType.SchemaDataObject)
			{
				var schemaName = completionType.ReferenceIdentifier.HasSchemaIdentifier
					? currentTerminal.ParentNode.FirstTerminalNode.Token.Value
					: databaseModel.CurrentSchema.ToQuotedIdentifier();

				completionItems = completionItems.Concat(GenerateSchemaDataObjectItems(oracleDatabaseModel, schemaName, completionType.TerminalValuePartUntilCaret, terminalToReplace, insertOffset: extraOffset));

				if (!completionType.ReferenceIdentifier.HasSchemaIdentifier)
				{
					completionItems = completionItems.Concat(GenerateSchemaDataObjectItems(oracleDatabaseModel, OracleObjectIdentifier.SchemaPublic, completionType.TerminalValuePartUntilCaret, terminalToReplace, insertOffset: extraOffset));
				}

				completionItems = completionItems.Concat(GenerateCommonTableExpressionReferenceItems(semanticModel, completionType.TerminalValuePartUntilCaret, terminalToReplace, extraOffset));
			}

			var joinClauseNode = currentTerminal.GetPathFilterAncestor(n => !String.Equals(n.Id, NonTerminals.FromClause), NonTerminals.JoinClause);
			if (joinClauseNode != null && !cursorAtLastTerminal && currentTerminal.Id.In(Terminals.ObjectIdentifier, Terminals.ObjectAlias, Terminals.On))
			{
				var isNotInnerJoin = joinClauseNode.ChildNodes.SingleOrDefault(n => String.Equals(n.Id, NonTerminals.InnerJoinClause)) == null;
				if (isNotInnerJoin || (!joinClauseNode.FirstTerminalNode.Id.In(Terminals.Cross, Terminals.Natural)))
				{
					var joinedTableReferenceNodes = joinClauseNode.GetPathFilterDescendants(n => !n.Id.In(NonTerminals.JoinClause, NonTerminals.NestedQuery), NonTerminals.TableReference).ToArray();
					if (joinedTableReferenceNodes.Length == 1)
					{
						var joinedTableReference = completionType.CurrentQueryBlock.ObjectReferences.SingleOrDefault(t => t.RootNode == joinedTableReferenceNodes[0]);
						if (joinedTableReference != null && (joinedTableReference.Type != ReferenceType.InlineView || joinedTableReference.AliasNode != null))
						{
							foreach (var parentTableReference in completionType.CurrentQueryBlock.ObjectReferences
								.Where(t => t.RootNode.SourcePosition.IndexStart < joinedTableReference.RootNode.SourcePosition.IndexStart &&
								            (t.Type != ReferenceType.InlineView || t.AliasNode != null)))
							{
								var joinSuggestions = GenerateJoinConditionSuggestionItems(parentTableReference, joinedTableReference, completionType, extraOffset);
								completionItems = completionItems.Concat(joinSuggestions);
							}
						}
					}
				}
			}

			if (completionType.JoinType)
			{
				completionItems = completionItems.Concat(CreateJoinTypeCompletionItems(completionType));
			}

			if (String.Equals(currentTerminal.Id, Terminals.Join) ||
				(String.Equals(currentTerminal.Id, Terminals.ObjectAlias) && String.Equals(((OracleToken)currentTerminal.Token).UpperInvariantValue, TerminalValues.Join)))
			{
				completionItems = completionItems.Concat(GenerateSchemaDataObjectItems(oracleDatabaseModel, databaseModel.CurrentSchema.ToQuotedIdentifier(), null, null, insertOffset: extraOffset));
				completionItems = completionItems.Concat(GenerateSchemaDataObjectItems(oracleDatabaseModel, OracleObjectIdentifier.SchemaPublic, null, null, insertOffset: extraOffset));
				completionItems = completionItems.Concat(GenerateCommonTableExpressionReferenceItems(semanticModel, null, null, extraOffset));
			}

			if (completionType.Column || completionType.PlSqlCompletion != PlSqlCompletion.None)
			{
				completionItems = completionItems.Concat(GenerateSelectListItems(referenceContainers, cursorPosition, oracleDatabaseModel, completionType, forcedInvokation));
			}

			if (completionType.Column || completionType.SpecialFunctionParameter)
			{
				var programOverloads = ResolveProgramOverloads(referenceContainers, currentTerminal, cursorPosition);
				var specificFunctionParameterCodeCompletionItems = CodeCompletionSearchHelper.ResolveSpecificFunctionParameterCodeCompletionItems(currentTerminal, programOverloads, oracleDatabaseModel);
				completionItems = completionItems.Concat(specificFunctionParameterCodeCompletionItems);
			}

			if (completionType.ColumnAlias)
			{
				completionItems = completionItems.Concat(GenerateColumnAliases(terminalToReplace, completionType));
			}

			if (completionType.UpdateSetColumn && semanticModel.MainObjectReferenceContainer.MainObjectReference != null)
			{
				completionItems = completionItems.Concat(GenerateSimpleColumnItems(semanticModel.MainObjectReferenceContainer.MainObjectReference, completionType));
			}

			if (completionType.InsertIntoColumn)
			{
				var columnList = currentTerminal.GetAncestor(NonTerminals.ParenthesisEnclosedPrefixedIdentifierList);
				var insertTarget = semanticModel.InsertTargets.SingleOrDefault(t => t.ColumnListNode == columnList && t.DataObjectReference != null);
				if (insertTarget != null)
				{
					completionItems = completionItems.Concat(GenerateSimpleColumnItems(insertTarget.DataObjectReference, completionType));
				}
			}

			if (completionType.DatabaseLink)
			{
				var databaseLinkItems = oracleDatabaseModel.DatabaseLinks.Values
					.Where(
						l =>
							l.FullyQualifiedName.NormalizedOwner.In(OracleObjectIdentifier.SchemaPublic, oracleDatabaseModel.CurrentSchema.ToQuotedIdentifier()) &&
							(String.IsNullOrEmpty(completionType.TerminalValueUnderCursor) || !String.Equals(completionType.TerminalValueUnderCursor.ToQuotedIdentifier(), l.FullyQualifiedName.NormalizedName)) &&
							CodeCompletionSearchHelper.IsMatch(l.FullyQualifiedName.Name, completionType.TerminalValuePartUntilCaret))
					.Select(
						l =>
							new OracleCodeCompletionItem
							{
								Name = l.FullyQualifiedName.Name.ToSimpleIdentifier(),
								Text = l.FullyQualifiedName.Name.ToSimpleIdentifier(),
								Category = OracleCodeCompletionCategory.DatabaseLink,
								StatementNode = completionType.CurrentTerminal
							});

				completionItems = completionItems.Concat(databaseLinkItems);
			}

			if (completionType.ExplicitPartition || completionType.ExplicitSubPartition)
			{
				var tableReferenceNode = completionType.EffectiveTerminal.GetAncestor(NonTerminals.TableReference);
				var tableReference = referenceContainers.SelectMany(c => c.ObjectReferences).SingleOrDefault(o => o.RootNode == tableReferenceNode && o.SchemaObject != null);
				if (tableReference != null)
				{
					completionItems = completionItems.Concat(GenerateTablePartitionItems(tableReference, completionType, completionType.ExplicitSubPartition));
				}
			}

			if (completionType.DataType)
			{
				completionItems = completionItems.Concat(GenerateDataTypeItems(completionType, oracleDatabaseModel));
			}

			if (completionType.Schema && !completionType.UpdateSetColumn &&
				(!completionType.ReferenceIdentifier.HasSchemaIdentifier || String.Equals(completionType.EffectiveTerminal.Id, Terminals.SchemaIdentifier)))
			{
				completionItems = completionItems.Concat(GenerateSchemaItems(completionType, terminalToReplace, extraOffset, oracleDatabaseModel, 2));
			}

			if (completionType.BindVariable)
			{
				var providerConfiguration = WorkDocumentCollection.GetProviderConfiguration(oracleDatabaseModel.ConnectionString.ProviderName);
				var currentNormalizedValue = completionType.TerminalValuePartUntilCaret.ToQuotedIdentifier();
				var bindVariables =
					providerConfiguration.BindVariables.Where(bv => bv.Value != null && !Equals(bv.Value, String.Empty) && !Equals(bv.Value, DateTime.MinValue) && !String.Equals(bv.Name.ToQuotedIdentifier(), currentNormalizedValue) && CodeCompletionSearchHelper.IsMatch(bv.Name.ToQuotedIdentifier(), completionType.TerminalValuePartUntilCaret))
						.Select(
							bv =>
								new OracleCodeCompletionItem
								{
									Name = bv.Name,
									Text = bv.Name,
									Category = OracleCodeCompletionCategory.BindVariable,
									StatementNode = completionType.ReferenceIdentifier.IdentifierUnderCursor
								});

				completionItems = completionItems.Concat(bindVariables);
			}

			completionItems = completionItems.Concat(GenerateKeywordItems(completionType));

			return completionItems.OrderItems().ToArray();

			// TODO: Add option to search all/current/public schemas
		}
Exemplo n.º 35
0
 public UserViewModelUnitTest()
 {
     db = new TestDatabaseModel();
     viewModel = new UserViewModel(db);
 }
Exemplo n.º 36
0
 public OrdersController(IDatabaseModel database)
 {
     _database = database;
 }
Exemplo n.º 37
0
		internal IEnumerable<ICodeSnippet> GetSnippets(string statementText, int cursorPosition, IDatabaseModel databaseModel)
		{
			var documentStore = new SqlDocumentRepository(OracleSqlParser.Instance, new OracleStatementValidator(), databaseModel, statementText);
			return GetSnippets(documentStore, statementText, cursorPosition);
		}