public UserSuppliedQueryHandler(IDocumentSchema schema, ISerializer serializer, string sql, object[] parameters)
 {
     _schema     = schema;
     _serializer = serializer;
     _sql        = sql;
     _parameters = parameters;
 }
Exemple #2
0
        public SelectManyQuery(IDocumentSchema schema, IQueryableDocument mapping, QueryModel query, int index)
        {
            Index = index;

            _schema = schema;
            _query  = query;

            _from = query.BodyClauses[index - 1].As <AdditionalFromClause>();

            var members = FindMembers.Determine(_from.FromExpression);

            _field = mapping.FieldFor(members);

            IsDistinct = query.HasOperator <DistinctResultOperator>();

            var next = query.BodyClauses.Skip(index + 1).FirstOrDefault(x => x is AdditionalFromClause);

            if (next != null)
            {
                throw new NotSupportedException("Not yet supporting SelectMany().SelectMany()");
            }
            else
            {
                _take = _query.BodyClauses.Count - index;
            }


            _tableAlias   = "sub" + Index;
            _documentType = _field.MemberType.GetElementType();
            _document     = _schema.StoreOptions.GetChildDocument(_tableAlias + ".x", _documentType);
        }
Exemple #3
0
 public AdvancedOptions(IDocumentCleaner cleaner, StoreOptions options, ISerializer serializer, IDocumentSchema schema)
 {
     _serializer = serializer;
     _schema     = schema;
     Options     = options;
     Clean       = cleaner;
 }
Exemple #4
0
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            var table = StorageTable();

            table.Write(writer);
            writer.WriteLine();
            writer.WriteLine();

            new UpsertFunction(_mapping).WriteFunctionSql(schema?.StoreOptions?.UpsertType ?? PostgresUpsertType.Legacy,
                                                          writer);

            _mapping.ForeignKeys.Each(x =>
            {
                writer.WriteLine();
                writer.WriteLine((string)x.ToDDL());
            });

            _mapping.Indexes.Each(x =>
            {
                writer.WriteLine();
                writer.WriteLine(x.ToDDL());
            });

            writer.WriteLine();
            writer.WriteLine();
        }
Exemple #5
0
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            var table = StorageTable();

            table.Write(writer);
            writer.WriteLine();
            writer.WriteLine();

            new UpsertFunction(_mapping).WriteFunctionSql(writer);

            _mapping.ForeignKeys.Each(x =>
            {
                writer.WriteLine();
                writer.WriteLine((string)x.ToDDL());
            });

            _mapping.Indexes.Each(x =>
            {
                writer.WriteLine();
                writer.WriteLine(x.ToDDL());
            });

            DependentScripts.Each(script =>
            {
                writer.WriteLine();
                writer.WriteLine();

                writer.WriteSql(_mapping.DatabaseSchemaName, script);
            });

            writer.WriteLine();
            writer.WriteLine();
        }
Exemple #6
0
        public LinqQuery(IDocumentSchema schema, QueryModel model, IIncludeJoin[] joins, QueryStatistics stats)
        {
            Model    = model;
            _schema  = schema;
            _joins   = joins;
            _mapping = schema.MappingFor(model.SourceType()).ToQueryableDocument();

            for (var i = 0; i < model.BodyClauses.Count; i++)
            {
                var clause = model.BodyClauses[i];
                if (clause is AdditionalFromClause)
                {
                    // TODO -- to be able to go recursive, have _subQuery start to read the BodyClauses
                    _subQuery = new SelectManyQuery(schema, _mapping, model, i + 1);


                    break;
                }
            }

            Selector   = BuildSelector(joins, stats, _subQuery, joins);
            SourceType = Model.SourceType();

            Where = buildWhereFragment();
        }
Exemple #7
0
 public AdvancedOptions(IDocumentCleaner cleaner, StoreOptions options, ISerializer serializer, IDocumentSchema schema)
 {
     _serializer = serializer;
     _schema = schema;
     Options = options;
     Clean = cleaner;
 }
Exemple #8
0
        public SchemaDiff(IDocumentSchema schema, SchemaObjects existing, DocumentMapping mapping)
        {
            if (existing.HasNone())
            {
                AllMissing = true;
            }
            else
            {
                var expectedTable = mapping.ToTable(schema);
                TableDiff = new TableDiff(expectedTable, existing.Table);

                // TODO -- drop obsolete indices?

                mapping.Indexes.Each(index =>
                {
                    if (existing.ActualIndices.ContainsKey(index.IndexName))
                    {
                        var actualIndex = existing.ActualIndices[index.IndexName];
                        if (!index.Matches(actualIndex))
                        {
                            IndexChanges.Add($"drop index {expectedTable.Table.Schema}.{index.IndexName};{index.ToDDL()}");
                        }
                    }
                    else
                    {
                        IndexChanges.Add(index.ToDDL());
                    }
                });

            }

            _existing = existing;
            _mapping = mapping;
            _schema = schema;
        }
Exemple #9
0
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            // TODO -- will need to do something to add the JS module for mt_transforms
            // maybe doing it by replacing all instances of ' with " and building the sql directly?
            // See EventStoreAdmin.RebuildEventStoreSchema()

            writer.WriteSql("mt_stream");
            writer.WriteSql("mt_initialize_projections");
            writer.WriteSql("mt_apply_transform");
            writer.WriteSql("mt_apply_aggregation");


            //writer.WriteLine("COMMIT;");
            //writer.WriteLine("");


            // This is going to have to be done separately
            //var js = SchemaBuilder.GetJavascript("mt_transforms").Replace("'", "\"").Replace("\n", "").Replace("\r", "");

            //writer.WriteLine($"insert into mt_modules (name, definition) values ('mt_transforms', '{js}');");

            //writer.WriteLine();

            //writer.WriteLine("select mt_initialize_projections();");
        }
Exemple #10
0
 public EventStore(IManagedConnection connection, IDocumentSchema schema, ISerializer serializer, IDocumentSchemaCreation creation)
 {
     _connection = connection;
     _schema     = schema;
     _serializer = serializer;
     _creation   = creation;
 }
Exemple #11
0
        public static ISelector <T> BuildSelector <T>(this IDocumentSchema schema, IQueryableDocument mapping, QueryModel query)
        {
            var selectable = query.AllResultOperators().OfType <ISelectableOperator>().FirstOrDefault();

            if (selectable != null)
            {
                return(selectable.BuildSelector <T>(schema, mapping));
            }

            if (query.SelectClause.Selector.Type == query.SourceType())
            {
                if (typeof(T) == typeof(string))
                {
                    return((ISelector <T>) new JsonSelector());
                }

                // I'm so ashamed of this hack, but "simplest thing that works"
                if (typeof(T) == typeof(IEvent))
                {
                    return(mapping.As <EventQueryMapping>().Selector.As <ISelector <T> >());
                }

                var resolver = schema.ResolverFor <T>();
                return(new WholeDocumentSelector <T>(mapping, resolver));
            }


            var visitor = new SelectorParser(query);

            visitor.Visit(query.SelectClause.Selector);

            return(visitor.ToSelector <T>(schema, mapping));
        }
Exemple #12
0
        public SchemaDiff(IDocumentSchema schema, SchemaObjects existing, DocumentMapping mapping)
        {
            if (existing.HasNone())
            {
                AllMissing = true;
            }
            else
            {
                var expectedTable = mapping.SchemaObjects.As <DocumentSchemaObjects>().StorageTable();
                TableDiff = new TableDiff(expectedTable, existing.Table);

                // TODO -- drop obsolete indices?

                mapping.Indexes.Each(index =>
                {
                    if (existing.ActualIndices.ContainsKey(index.IndexName))
                    {
                        var actualIndex = existing.ActualIndices[index.IndexName];
                        if (!index.Matches(actualIndex))
                        {
                            IndexChanges.Add($"drop index {expectedTable.Table.Schema}.{index.IndexName};{Environment.NewLine}{index.ToDDL()};");
                        }
                    }
                    else
                    {
                        IndexChanges.Add(index.ToDDL());
                    }
                });
            }

            _existing = existing;
            _mapping  = mapping;
        }
Exemple #13
0
 public SequenceFactory(IDocumentSchema schema, IConnectionFactory factory, StoreOptions options, IMartenLogger logger)
 {
     _schema = schema;
     _factory = factory;
     _options = options;
     _logger = logger;
 }
Exemple #14
0
        private FunctionDiff functionDiff(IDocumentSchema schema)
        {
            var body     = schema.DbObjects.DefinitionForFunction(Function);
            var expected = new FunctionBody(Function, new string[] { ToDropSignature() }, GenerateFunction());

            return(new FunctionDiff(expected, body));
        }
Exemple #15
0
 public SequenceFactory(IDocumentSchema schema, IConnectionFactory factory, StoreOptions options, IMartenLogger logger)
 {
     _schema  = schema;
     _factory = factory;
     _options = options;
     _logger  = logger;
 }
        public SequenceFactoryTests()
        {
            _schema = theStore.Schema;

            _schema.Sequences.Hilo(typeof(Target), new HiloSettings())
            .ShouldBeOfType <HiloSequence>();
        }
Exemple #17
0
 public EventStoreAdmin(IDocumentSchema schema, IConnectionFactory connectionFactory, StoreOptions options, ISerializer serializer)
 {
     _schema            = schema;
     _connectionFactory = connectionFactory;
     _options           = options;
     _serializer        = serializer;
 }
Exemple #18
0
        public void WritePatch(IDocumentSchema schema, SchemaPatch patch)
        {
            var diff = CreateSchemaDiff(schema);

            if (!diff.HasDifferences())
            {
                return;
            }

            if (diff.AllMissing)
            {
                patch.Rollbacks.Drop(this, _mapping.Table);
                WriteSchemaObjects(schema, patch.UpWriter);
            }
            else if (diff.CanPatch())
            {
                diff.CreatePatch(schema.StoreOptions, patch);
            }

            if (schema.StoreOptions.OwnerName.IsNotEmpty())
            {
                var ownership = $"ALTER TABLE {_mapping.Table} OWNER TO \"{schema.StoreOptions.OwnerName}\";";
                patch.Updates.Apply(this, ownership);
            }
        }
        public static IEnumerable<IDocumentStorage> Build(IDocumentSchema schema, DocumentMapping[] mappings)
        {
            // Generate the actual source code
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            // Tell the generator which other assemblies that it should be referencing 
            // for the compilation
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType<NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType<QueryModel>();
            generator.ReferenceAssemblyContainingType<DbCommand>();
            generator.ReferenceAssemblyContainingType<Component>();
            generator.ReferenceAssemblyContainingType<DbDataReader>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            // build the new assembly -- this will blow up if there are any
            // compilation errors with the list of errors and the actual code

            var assembly = generator.Generate(code);

            return assembly
                .GetExportedTypes()
                .Where(x => x.IsConcreteTypeOf<IDocumentStorage>())
                .Select(x => BuildStorageObject(schema, mappings, x));
        }
        public DocumentSchemaWithOverridenDefaultSchemaAndEventsTests()
        {
            StoreOptions(_ =>
            {
                // SAMPLE: override_schema_name
                _.DatabaseSchemaName = "other";
                // ENDSAMPLE
                _.Storage.MappingFor(typeof(User)).DatabaseSchemaName  = "yet_another";
                _.Storage.MappingFor(typeof(Issue)).DatabaseSchemaName = "overriden";
                _.Storage.MappingFor(typeof(Company));
                _.Events.AddEventType(typeof(MembersJoined));
            });

            _schema = theStore.Schema;

            _sql = _schema.ToDDL();

            using (var session = theStore.OpenSession())
            {
                session.Store(new User());
                session.Store(new Issue());
                session.Store(new Company());
                session.SaveChanges();
            }

            _tables    = _schema.DbObjects.SchemaTables();
            _functions = _schema.DbObjects.Functions();
        }
Exemple #21
0
        public static IEnumerable <IDocumentStorage> Build(IDocumentSchema schema, DocumentMapping[] mappings)
        {
            // Generate the actual source code
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();

            // Tell the generator which other assemblies that it should be referencing
            // for the compilation
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType <NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType <QueryModel>();
            generator.ReferenceAssemblyContainingType <DbCommand>();
            generator.ReferenceAssemblyContainingType <Component>();
            generator.ReferenceAssemblyContainingType <DbDataReader>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            // build the new assembly -- this will blow up if there are any
            // compilation errors with the list of errors and the actual code

            var assembly = generator.Generate(code);

            return(assembly
                   .GetExportedTypes()
                   .Where(x => x.IsConcreteTypeOf <IDocumentStorage>())
                   .Select(x => BuildStorageObject(schema, mappings, x)));
        }
Exemple #22
0
 public EventStoreAdmin(IDocumentSchema schema, IConnectionFactory connectionFactory, StoreOptions options, ISerializer serializer)
 {
     _schema = schema;
     _connectionFactory = connectionFactory;
     _options = options;
     _serializer = serializer;
 }
        public SequenceFactoryTests()
        {
            _schema = theStore.Schema;

            _schema.Sequences.Hilo(typeof(Target), new HiloSettings())
                .ShouldBeOfType<HiloSequence>();
        }
        public void CreateSchema(IDocumentSchema schema, DocumentMapping mapping)
        {
            var writer= new StringWriter();
            mapping.WriteSchemaObjects(schema, writer);

            _runner.Execute(writer.ToString());
        }
Exemple #25
0
 public LinqQueryHandler(IDocumentSchema schema, QueryModel query, IIncludeJoin[] joins, QueryStatistics stats)
     : base(BuildSelector(schema, query, joins, stats))
 {
     _mapping = schema.MappingFor(query).ToQueryableDocument();
     _schema  = schema;
     _query   = query;
 }
Exemple #26
0
        public DocumentSchemaWithOverridenSchemaTests()
        {
            #region sample_override_schema_per_table

            StoreOptions(_ =>
            {
                _.Storage.MappingFor(typeof(User)).DatabaseSchemaName  = "other";
                _.Storage.MappingFor(typeof(Issue)).DatabaseSchemaName = "overriden";
                _.Storage.MappingFor(typeof(Company));
                _.Storage.MappingFor(typeof(IntDoc));

                // this will tell marten to use the default 'public' schema name.
                _.DatabaseSchemaName = DbObjectName.DefaultDatabaseSchemaName;
            });

            #endregion sample_override_schema_per_table

            _schema = theStore.Schema;
            _sql    = _schema.ToDatabaseScript();

            using (var session = theStore.OpenSession())
            {
                session.Store(new User());
                session.Store(new Issue());
                session.Store(new Company());
                session.SaveChanges();
            }

            _tables    = theStore.Tenancy.Default.SchemaTables().GetAwaiter().GetResult().ToArray();
            _functions = theStore.Tenancy.Default.Functions().GetAwaiter().GetResult().ToArray();
        }
Exemple #27
0
        public ISelector <T> ToSelector <T>(IDocumentSchema schema, IQueryableDocument mapping)
        {
            if (_selectionType == SelectionType.AsJson && _target == null)
            {
                return(new JsonSelector().As <ISelector <T> >());
            }

            if (_selectionType == SelectionType.AsJson && _target != null)
            {
                return(_target.ToJsonSelector <T>(mapping));
            }


            if (_selectionType == SelectionType.TransformToJson)
            {
                var transform = schema.TransformFor(_transformName);
                return(new TransformToJsonSelector(transform, mapping).As <ISelector <T> >());
            }

            if (_selectionType == SelectionType.TransformTo)
            {
                var transform = schema.TransformFor(_transformName);

                return(new TransformToTypeSelector <T>(transform, mapping));
            }

            if (_target == null || _target.Type != typeof(T))
            {
                return(new SingleFieldSelector <T>(mapping, _currentField.Members.Reverse().ToArray()));
            }

            return(_target.ToSelector <T>(mapping));
        }
Exemple #28
0
        public DocumentSchemaWithOverridenDefaultSchemaAndEventsTests()
        {
            StoreOptions(_ =>
            {
                #region sample_override_schema_name

                _.DatabaseSchemaName = "other";

                #endregion sample_override_schema_name

                _.Storage.MappingFor(typeof(User)).DatabaseSchemaName  = "yet_another";
                _.Storage.MappingFor(typeof(Issue)).DatabaseSchemaName = "overriden";
                _.Storage.MappingFor(typeof(Company));
                _.Events.AddEventType(typeof(MembersJoined));
            });

            _schema = theStore.Schema;

            _sql = _schema.ToDatabaseScript();

            using (var session = theStore.OpenSession())
            {
                session.Store(new User());
                session.Store(new Issue());
                session.Store(new Company());
                session.SaveChanges();
            }

            _tables    = theStore.Tenancy.Default.SchemaTables().GetAwaiter().GetResult().ToArray();
            _functions = theStore.Tenancy.Default.Functions().GetAwaiter().GetResult().ToArray();
        }
 public void WritePatch(IDocumentSchema schema, IDDLRunner runner)
 {
     if (functionShouldBeReloaded(schema))
     {
         runner.Apply(this, GenerateFunction());
     }
 }
Exemple #30
0
 public EventStore(ICommandRunner runner, IDocumentSchema schema, ISerializer serializer, IDocumentSchemaCreation creation)
 {
     _runner     = runner;
     _schema     = schema;
     _serializer = serializer;
     _creation   = creation;
 }
        public void GenerateSchemaObjectsIfNecessary(AutoCreate autoCreateSchemaObjectsMode, IDocumentSchema schema, SchemaPatch patch)
        {
            if (_checkedSchema) return;

            _checkedSchema = true;

            var tableExists = schema.DbObjects.TableExists(_parent.Table);

            if (tableExists) return;

            if (autoCreateSchemaObjectsMode == AutoCreate.None)
            {
                throw new InvalidOperationException(
                    "The EventStore schema objects do not exist and the AutoCreateSchemaObjects is configured as " +
                    autoCreateSchemaObjectsMode);
            }

            lock (_locker)
            {
                if (!schema.DbObjects.TableExists(_parent.Table))
                {
                    var writer = new StringWriter();

                    writeBasicTables(schema, writer);

                    patch.Updates.Apply(this, writer.ToString());
                }
            }
        }
        public DocumentSchemaWithOverridenSchemaTests()
        {
            // SAMPLE: override_schema_per_table
            StoreOptions(_ =>
            {
                _.Storage.MappingFor(typeof(User)).DatabaseSchemaName  = "other";
                _.Storage.MappingFor(typeof(Issue)).DatabaseSchemaName = "overriden";
                _.Storage.MappingFor(typeof(Company));
                _.Storage.MappingFor(typeof(IntDoc));

                // this will tell marten to use the default 'public' schema name.
                _.DatabaseSchemaName = Marten.StoreOptions.DefaultDatabaseSchemaName;
            });
            // ENDSAMPLE

            _schema = theStore.Schema;
            _sql    = _schema.ToDDL();

            using (var session = theStore.OpenSession())
            {
                session.Store(new User());
                session.Store(new Issue());
                session.Store(new Company());
                session.SaveChanges();
            }

            _tables    = _schema.DbObjects.SchemaTables();
            _functions = _schema.DbObjects.Functions();
        }
Exemple #33
0
        public IDocumentStorage BuildStorage(IDocumentSchema schema)
        {
            var parentStorage = Parent.As <IDocumentMapping>().BuildStorage(schema);

            return(typeof(SubClassDocumentStorage <,>).CloseAndBuildAs <IDocumentStorage>(parentStorage, DocumentType,
                                                                                          Parent.DocumentType));
        }
        public static IEnumerable<IDocumentStorage> Build(IDocumentSchema schema, DocumentMapping[] mappings)
        {
            var code = GenerateDocumentStorageCode(mappings);

            var generator = new AssemblyGenerator();
            generator.ReferenceAssembly(Assembly.GetExecutingAssembly());
            generator.ReferenceAssemblyContainingType<NpgsqlConnection>();
            generator.ReferenceAssemblyContainingType<QueryModel>();
            generator.ReferenceAssemblyContainingType<DbCommand>();
            generator.ReferenceAssemblyContainingType<Component>();

            mappings.Select(x => x.DocumentType.Assembly).Distinct().Each(assem => generator.ReferenceAssembly(assem));

            var assembly = generator.Generate(code);

            return assembly
                .GetExportedTypes()
                .Where(x => x.IsConcreteTypeOf<IDocumentStorage>())
                .Select(x =>
                {
                    var docType =
                        x.FindInterfaceThatCloses(typeof (IdAssignment<>)).GetGenericArguments().Single();

                    var mapping = mappings.Single(m => m.DocumentType == docType);

                    var arguments = mapping.IdStrategy.ToArguments().Select(arg => arg.GetValue(schema)).ToArray();

                    var ctor = x.GetConstructors().Single();

                    return ctor.Invoke(arguments).As<IDocumentStorage>();
                });
        }
Exemple #35
0
        public void CreateSchema(IDocumentSchema schema, DocumentMapping mapping)
        {
            var writer = new StringWriter();

            mapping.WriteSchemaObjects(schema, writer);

            _runner.Execute(writer.ToString());
        }
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            var body = SchemaBuilder.GetSqlScript(schema.StoreOptions.DatabaseSchemaName, _function.Name);


            writer.WriteLine(body);
            writer.WriteLine("");
        }
        public static IDocumentStorage BuildStorageObject(IDocumentSchema schema, Type storageType, DocumentMapping mapping)
        {
            var arguments = mapping.ToArguments().Select(arg => arg.GetValue(schema)).ToArray();

            var ctor = storageType.GetConstructors().Single();

            return ctor.Invoke(arguments).As<IDocumentStorage>();
        }
Exemple #38
0
 public MartenQueryExecutor(IConnectionFactory factory, IDocumentSchema schema, ISerializer serializer,
                            IQueryParser parser)
 {
     _schema     = schema;
     _serializer = serializer;
     _parser     = parser;
     _runner     = new CommandRunner(factory);
 }
Exemple #39
0
 public QuerySession(IDocumentSchema schema, ISerializer serializer, IManagedConnection connection, IQueryParser parser, IIdentityMap identityMap)
 {
     _schema      = schema;
     _serializer  = serializer;
     _connection  = connection;
     _parser      = parser;
     _identityMap = identityMap;
 }
Exemple #40
0
 public QuerySession(IDocumentSchema schema, ISerializer serializer, ICommandRunner runner, IQueryParser parser, IIdentityMap identityMap)
 {
     _schema      = schema;
     _serializer  = serializer;
     _runner      = runner;
     _parser      = parser;
     _identityMap = identityMap;
 }
        public void CreateSchema(IDocumentSchema schema, IDocumentMapping mapping)
        {
            var className = nameof(StoreOptions);
            var propName = nameof(StoreOptions.AutoCreateSchemaObjects);

            string message = $"No document storage exists for type {mapping.DocumentType.FullName} and cannot be created dynamically unless the {className}.{propName} = true. See http://jasperfx.github.io/marten/documentation/documents/ for more information";
            throw new InvalidOperationException(message);
        }
        public static IDocumentStorage BuildStorageObject(IDocumentSchema schema, DocumentMapping[] mappings, Type storageType)
        {
            var docType = storageType.DocumentTypeForStorage();

            var mapping = mappings.Single(m => m.DocumentType == docType);

            return BuildStorageObject(schema, storageType, mapping);
        }
Exemple #43
0
        public IdAssignment <T> ToIdAssignment <T>(IDocumentSchema schema)
        {
            var idType = IdMember.GetMemberType();

            var assignerType = typeof(IdAssigner <,>).MakeGenericType(typeof(T), idType);

            return((IdAssignment <T>)Activator.CreateInstance(assignerType, IdMember, IdStrategy, schema));
        }
Exemple #44
0
        public void WritePatch(IDocumentSchema schema, SchemaPatch patch)
        {
            var diff = functionDiff(schema);

            if (diff.AllNew || diff.HasChanged)
            {
                diff.WritePatch(schema.StoreOptions, patch);
            }
        }
        public void WritePatch(IDocumentSchema schema, SchemaPatch patch)
        {
            var diff = functionDiff(schema);

            if (diff.AllNew || !diff.Actual.Body.Contains(Body))
            {
                diff.WritePatch(schema.StoreOptions, patch);
            }
        }
        private FunctionDiff createFunctionDiff(IDocumentSchema schema)
        {
            var actual = schema.DbObjects.DefinitionForFunction(_function);

            var expectedBody = SchemaBuilder.GetSqlScript(schema.StoreOptions.DatabaseSchemaName, _function.Name);

            var expected = new FunctionBody(_function, new string[] { _dropSql }, expectedBody);

            return new FunctionDiff(expected, actual);
        }
Exemple #47
0
        public void WritePatch(IDocumentSchema schema, SchemaPatch patch)
        {
            if (!schema.DbObjects.TableExists(Table))
            {
                var sqlScript = SchemaBuilder.GetSqlScript(Table.Schema, "mt_hilo");
                patch.Updates.Apply(this, sqlScript);

                patch.Rollbacks.Drop(this, Table);
            }
        }
Exemple #48
0
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            var patch = new SchemaPatch(schema.StoreOptions.DdlRules, writer);

            var sqlScript = SchemaBuilder.GetSqlScript(Table.Schema, "mt_hilo");

            writer.WriteLine(sqlScript);
            writer.WriteLine("");
            writer.WriteLine("");
        }
Exemple #49
0
        public when_deriving_the_table_definition_from_the_database_schema_Tests()
        {
            _schema = theStore.Schema;

            theMapping = _schema.MappingFor(typeof(User)).As<DocumentMapping>();
            theMapping.DuplicateField("UserName");

            _storage = _schema.StorageFor(typeof(User));

            theDerivedTable = _schema.DbObjects.TableSchema(theMapping);
        }
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            writeBasicTables(schema, writer);

            if (schema.StoreOptions.OwnerName.IsNotEmpty())
            {
                var ddl = createOwnershipDDL(schema.StoreOptions);
                writer.WriteLine();
                writer.WriteLine(ddl);
            }
        }
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            writer.WriteLine(GenerateFunction());

            if (schema.StoreOptions.OwnerName.IsNotEmpty())
            {
                writer.WriteLine();
                var expected = new FunctionBody(Function, new string[] { ToDropSignature() }, GenerateFunction());

                writer.WriteLine(expected.ToOwnershipCommand(schema.StoreOptions.OwnerName));
            }
        }
        public void WritePatch(IDocumentSchema schema, SchemaPatch patch)
        {
            if (!_parent.IsActive) return;

            var tableExists = schema.DbObjects.TableExists(_parent.Table);

            if (tableExists) return;

            patch.Updates.Apply(this, SchemaBuilder.GetSqlScript(_parent.DatabaseSchemaName, "mt_stream"));

            patch.Rollbacks.Drop(this, new TableName(schema.Events.DatabaseSchemaName, "mt_streams"));
        }
 public void CreateSchema(IDocumentSchema schema, IDocumentMapping mapping, Func<bool> shouldRegenerate)
 {
     if (shouldRegenerate())
     {
         lock (_lock)
         {
             if (shouldRegenerate())
             {
                 writeSchemaObjects(schema, mapping);
             }
         }
     }
 }
        public void WriteSchemaObjects(IDocumentSchema schema, StringWriter writer)
        {
            var sqlScript = SchemaBuilder.GetSqlScript(Table.Schema, "mt_hilo");
            writer.WriteLine(sqlScript);
            writer.WriteLine("");
            writer.WriteLine("");

            if (schema.StoreOptions.OwnerName.IsNotEmpty())
            {
                writer.WriteLine($"ALTER TABLE {schema.StoreOptions.DatabaseSchemaName}.mt_hilo OWNER TO \"{schema.StoreOptions.OwnerName}\";");
                writer.WriteLine($"ALTER FUNCTION {schema.StoreOptions.DatabaseSchemaName}.mt_get_next_hi(varchar) OWNER TO \"{schema.StoreOptions.OwnerName}\";");
            }
        }
        public void CreateSchema(IDocumentSchema schema, DocumentMapping mapping)
        {
            var writer= new StringWriter();
            SchemaBuilder.WriteSchemaObjects(mapping, schema, writer);

            var sql = writer.ToString();
            try
            {
                _runner.Execute(sql);
            }
            catch (Exception e)
            {
                throw new MartenSchemaException(mapping.DocumentType, sql, e);
            }
        }
Exemple #56
0
        public void GenerateSchemaObjectsIfNecessary(AutoCreate autoCreateSchemaObjectsMode, IDocumentSchema schema, SchemaPatch patch)
        {
            if (_checked) return;

            _checked = true;

            if (!schema.DbObjects.TableExists(Table))
            {
                if (_options.AutoCreateSchemaObjects == AutoCreate.None)
                {
                    throw new InvalidOperationException($"Hilo table is missing, but {nameof(StoreOptions.AutoCreateSchemaObjects)} is {_options.AutoCreateSchemaObjects}");
                }

                WritePatch(schema, patch);
            }
        }
        private void writeSchemaObjects(IDocumentSchema schema, IDocumentMapping mapping)
        {
            var writer = new StringWriter();
            SchemaBuilder.WriteSchemaObjects(mapping, schema, writer);
            var sql = writer.ToString();

            try
            {
                _factory.RunSql(sql);
            }
            catch (Exception e)
            {
                throw new MartenSchemaException(mapping.DocumentType, sql, e);
            }


        }
        public void GenerateSchemaObjectsIfNecessary(AutoCreate autoCreateSchemaObjectsMode, IDocumentSchema schema, SchemaPatch patch)
        {
            if (Checked) return;

            Checked = true;

            var diff = createFunctionDiff(schema);

            if (!diff.HasChanged) return;

            if (autoCreateSchemaObjectsMode == AutoCreate.None)
            {
                throw new InvalidOperationException($"{_function.QualifiedName} function is missing, but {nameof(StoreOptions.AutoCreateSchemaObjects)} is {autoCreateSchemaObjectsMode}");
            }

            diff.WritePatch(schema.StoreOptions, patch);
        }
Exemple #59
0
        public static void WriteSchemaObjects(IDocumentMapping mapping, IDocumentSchema schema, StringWriter writer)
        {
            var table = mapping.ToTable(schema);
            table.Write(writer);
            writer.WriteLine();
            writer.WriteLine();

            mapping.ToUpsertFunction().WriteFunctionSql(schema?.UpsertType ?? PostgresUpsertType.Legacy, writer);

            mapping.Indexes.Each(x =>
            {
                writer.WriteLine();
                writer.WriteLine(x.ToDDL());
            });

            writer.WriteLine();
            writer.WriteLine();
        }
Exemple #60
0
        private static ValidationResult Validate(ViolationCollector collector, IDocumentSchema schema, IAutomatonDocument document, IDocOp docOp)
        {
            if (schema == null)
            {
                schema = DocumentSchema.NoSchemaConstraints;
            }

            var automation = new DocOpAutomaton(document, schema);
            var accu = new ValidationResult[] { ValidationResult.Valid };
            try
            {
                docOp.Apply(new ValidationDocOpCursor(collector, automation, accu));
            }
            catch (IllFormedException illFormed)
            {
                return ValidationResult.IllFormed;
            }

            accu[0] = accu[0].MergeWith(automation.CheckFinish(collector));
            return accu[0];
        }