Skip to content

Commit

Permalink
Ticket #16 : Configure the schema only one time
Browse files Browse the repository at this point in the history
  • Loading branch information
thabart committed Nov 12, 2020
1 parent c525400 commit b409d07
Show file tree
Hide file tree
Showing 24 changed files with 302 additions and 376 deletions.
20 changes: 8 additions & 12 deletions samples/EFCore.Cassandra.Samples/FakeDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,16 @@ namespace EFCore.Cassandra.Samples
{
public class FakeDbContext : DbContext
{
private const string CV_KEYSPACE = "cv";
public DbSet<Applicant> Applicants { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseCassandra($"Contact Points=127.0.0.1", CV_KEYSPACE, opt =>
optionsBuilder.UseCassandra("Contact Points=127.0.0.1;", "cv", opt =>
{
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName, CV_KEYSPACE);
}, b =>
{
b.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalOne))
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName);
}, o => {
o.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalOne))
.WithReconnectionPolicy(new ConstantReconnectionPolicy(1000))
.WithRetryPolicy(new DefaultRetryPolicy())
.WithLoadBalancingPolicy(new TokenAwarePolicy(Policies.DefaultPolicies.LoadBalancingPolicy))
Expand All @@ -39,9 +38,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var timeUuidConverter = new TimeUuidToGuidConverter();
modelBuilder.ForCassandraAddKeyspace(CV_KEYSPACE, new KeyspaceReplicationSimpleStrategyClass(2));
modelBuilder.EnsureKeyspaceCreated(new KeyspaceReplicationSimpleStrategyClass(2));
modelBuilder.Entity<Applicant>()
.ToTable("applicants", CV_KEYSPACE)
.ToTable("applicants")
.HasKey(p => new { p.Id, p.Order });
modelBuilder.Entity<Applicant>()
.ForCassandraSetClusterColumns(_ => _.Order)
Expand All @@ -52,11 +51,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.Entity<Applicant>()
.Property(p => p.Id)
.HasColumnName("id");
modelBuilder.Entity<CV>()
.ToTable("cvs", CV_KEYSPACE)
.HasKey(c => c.Id);
modelBuilder.Entity<ApplicantAddress>()
.ToUserDefinedType("applicant_addr", CV_KEYSPACE)
.ToUserDefinedType("applicant_addr")
.HasNoKey();
}
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,10 @@

namespace EFCore.Cassandra.Samples.Migrations
{
public partial class InitialCreate : Migration
public partial class Init : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "cv");

migrationBuilder.CreateTable(
name: "applicants",
schema: "cv",
Expand All @@ -39,8 +36,6 @@ protected override void Up(MigrationBuilder migrationBuilder)
LocalDate = table.Column<LocalDate>(nullable: true),
Ip = table.Column<IPAddress>(nullable: true),
LocalTime = table.Column<LocalTime>(nullable: true),
Lst = table.Column<IEnumerable<string>>(nullable: true),
LstInt = table.Column<IEnumerable<int>>(nullable: true),
Dic = table.Column<IDictionary<string, string>>(nullable: true),
Address = table.Column<ApplicantAddress>(type: "applicant_addr", nullable: true)
},
Expand All @@ -49,20 +44,6 @@ protected override void Up(MigrationBuilder migrationBuilder)
table.PrimaryKey("PK_applicants", x => new { x.id, x.Order });
});

migrationBuilder.CreateTable(
name: "cvs",
schema: "cv",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
CvId = table.Column<Guid>(nullable: false),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_cvs", x => x.Id);
});

migrationBuilder.CreateUserDefinedType(
name: "applicant_addr",
schema: "cv",
Expand All @@ -79,10 +60,6 @@ protected override void Down(MigrationBuilder migrationBuilder)
name: "applicants",
schema: "cv");

migrationBuilder.DropTable(
name: "cvs",
schema: "cv");

migrationBuilder.DropUserDefinedType(
name: "applicant_addr",
schema: "cv");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Cassandra:Keyspacecv", "{\"ReplicationFactor\":2,\"ReplicationClass\":0}")
.HasAnnotation("Cassandra:KeyspaceConfiguration", "{\"ReplicationFactor\":2,\"ReplicationClass\":0}")
.HasAnnotation("ProductVersion", "3.1.4");

modelBuilder.Entity("EFCore.Cassandra.Samples.Models.Applicant", b =>
Expand Down Expand Up @@ -75,12 +75,6 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Property<long>("Long")
.HasColumnType("bigint");
b.Property<IList<string>>("Lst")
.HasColumnType("list<text>");
b.Property<IList<int>>("LstInt")
.HasColumnType("list<int>");
b.Property<sbyte>("Sbyte")
.HasColumnType("tinyint");
Expand All @@ -92,7 +86,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.HasKey("Id", "Order");
b.ToTable("applicants","cv");
b.ToTable("applicants");
b.HasAnnotation("Cassandra:ClusterColumns", new[] { "Order" });
Expand All @@ -107,27 +101,10 @@ protected override void BuildModel(ModelBuilder modelBuilder)
b.Property<int>("StreetNumber")
.HasColumnType("int");
b.ToTable("applicant_addr","cv");
b.ToTable("applicant_addr");
b.HasAnnotation("Cassandra:IsUserDefinedType", true);
});

modelBuilder.Entity("EFCore.Cassandra.Samples.Models.CV", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("CvId")
.HasColumnType("uuid");
b.Property<string>("Name")
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("cvs","cv");
});
#pragma warning restore 612, 618
}
}
Expand Down
8 changes: 5 additions & 3 deletions samples/EFCore.Cassandra.Samples/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Cassandra;
using EFCore.Cassandra.Samples.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Net;
using System.Threading.Tasks;

namespace EFCore.Cassandra.Samples
{
Expand All @@ -15,7 +16,7 @@ class Program
private static Guid ApplicantPartitionId = Guid.Parse("be2106c5-791f-45d2-890a-50fc221f96e8");
private static Guid ApplicantId = Guid.Parse("09e0f68e-8818-452a-9a47-3c8ca2c941c8");

static void Main(string[] args)
static async Task Main(string[] args)
{
using (var dbContext = new FakeDbContext())
{
Expand All @@ -25,7 +26,8 @@ static void Main(string[] args)

Console.WriteLine("Add applicant");
var timeUuid = TimeUuid.NewId();
dbContext.Applicants.Add(BuildApplicant());
var app = BuildApplicant();
dbContext.Applicants.Add(app);
dbContext.SaveChanges();
Console.WriteLine("Applicant is added");

Expand Down
8 changes: 4 additions & 4 deletions src/EFCore.Cassandra.Benchmarks/FakeDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseCassandra("Contact Points=127.0.0.1;", CV_KEYSPACE, opt =>
{
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName, CV_KEYSPACE);
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName);
}, o => {
o.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalOne))
Expand All @@ -39,9 +39,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var timeUuidConverter = new TimeUuidToGuidConverter();
modelBuilder.ForCassandraAddKeyspace("CV_KEYSPACE", new KeyspaceReplicationSimpleStrategyClass(2));
modelBuilder.EnsureKeyspaceCreated(new KeyspaceReplicationSimpleStrategyClass(2));
modelBuilder.Entity<Applicant>()
.ToTable("applicants", CV_KEYSPACE)
.ToTable("applicants")
.HasKey(p => new { p.Id, p.Order });
modelBuilder.Entity<Applicant>()
.ForCassandraSetClusterColumns(_ => _.Order)
Expand All @@ -53,7 +53,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
.Property(p => p.Id)
.HasColumnName("id");
modelBuilder.Entity<ApplicantAddress>()
.ToUserDefinedType("applicant_addr", CV_KEYSPACE)
.ToUserDefinedType("applicant_addr")
.HasNoKey();
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/EFCore.Cassandra/Bulk/SqlBulkOperation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Cassandra;
using Cassandra.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Cassandra.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
Expand Down Expand Up @@ -34,6 +35,8 @@ private static (BatchStatement batchStatement, ISession session) BuildBatch<T>(D
{
var service = dbContext.GetService<ICommandBatchPreparer>();
var sqlGenerationHelper = dbContext.GetService<ISqlGenerationHelper>();
var relationalConnectionDependencies = dbContext.GetService<RelationalConnectionDependencies>();
var cassandraOptionsExtension = CassandraOptionsExtension.Extract(relationalConnectionDependencies.ContextOptions);
var database = dbContext.Database.GetDbConnection() as CqlConnection;
if (database.State != ConnectionState.Open)
{
Expand All @@ -58,7 +61,7 @@ private static (BatchStatement batchStatement, ISession session) BuildBatch<T>(D
}

var tableName = entityType.GetTableName();
var schema = entityType.GetSchema();
var schema = cassandraOptionsExtension.DefaultKeyspace;
var cqlQuery = $"INSERT INTO \"{schema}\".\"{tableName}\" ({string.Join(',', propertyNames)}) VALUES ({string.Join(',', Enumerable.Repeat(1, propertyNames.Count()).Select(_ => "?"))})";
var smt = session.Prepare(cqlQuery);
batch.Add(smt.Bind(propertyValues.ToArray()));
Expand Down
13 changes: 13 additions & 0 deletions src/EFCore.Cassandra/CassandraOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Copyright (c) SimpleIdServer. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
using Builder = Cassandra.Builder;

namespace EFCore.Cassandra
{
public class CassandraOptions
{
public string DefaultKeyspace { get; set; }
public Action<Builder> ClusterBuilder { get; set; }
}
}
3 changes: 3 additions & 0 deletions src/EFCore.Cassandra/CassandraServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Update;
using Microsoft.EntityFrameworkCore.Update.Internal;

namespace Microsoft.Extensions.DependencyInjection
{
Expand All @@ -29,6 +30,7 @@ public static IServiceCollection AddEntityFrameworkCassandra(this IServiceCollec
.TryAdd<IRelationalTypeMappingSource, CassandraTypeMappingSource>()
.TryAdd<LoggingDefinitions, CassandraLoggingDefinitions>()
.TryAdd<IMigrationsModelDiffer, CassandraMigrationsModelDiffer>()
.TryAdd<ICommandBatchPreparer, CassandraCommandBatchPreparer>()
// .TryAdd<IMemberTranslator, CassandraCompositeMemberTranslator>()
.TryAdd<IMigrator, CassandraMigrator>()
.TryAdd<ISqlGenerationHelper, CassandraSqlGenerationHelper>()
Expand All @@ -52,6 +54,7 @@ public static IServiceCollection AddEntityFrameworkCassandra(this IServiceCollec
.TryAddProviderSpecificServices(b => b.TryAddTransient<ICassandraHistoryRepository, CassandraHistoryRepository>());

builder.TryAddCoreServices();
serviceCollection.AddSingleton<IServiceCollection>(serviceCollection);
return serviceCollection;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,9 @@ public static EntityTypeBuilder ForCassandraSetClusteringOrderBy(this EntityType
return entityTypeBuilder;
}

public static EntityTypeBuilder ToUserDefinedType(this EntityTypeBuilder entityTypeBuilder, string name, string schema)
public static EntityTypeBuilder ToUserDefinedType(this EntityTypeBuilder entityTypeBuilder, string name)
{
entityTypeBuilder.Metadata.SetTableName(name);
entityTypeBuilder.Metadata.SetSchema(schema);
entityTypeBuilder.Metadata.SetIsUserDefinedType();
return entityTypeBuilder;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ namespace Microsoft.EntityFrameworkCore
{
public static class CassandraModelBuilderExtensions
{
public static ModelBuilder ForCassandraAddKeyspace(this ModelBuilder modelBuilder, string keyspaceName, KeyspaceReplicationConfiguration configuration)
public static ModelBuilder EnsureKeyspaceCreated(this ModelBuilder modelBuilder, KeyspaceReplicationConfiguration configuration)
{
var model = modelBuilder.Model;
model.SetKeyspace(keyspaceName, configuration);
model.SetKeyspaceConfiguration(configuration);
return modelBuilder;
}
}
Expand Down
Loading

0 comments on commit b409d07

Please sign in to comment.