Skip to content

Commit b409d07

Browse files
committed
Ticket #16 : Configure the schema only one time
1 parent c525400 commit b409d07

24 files changed

+302
-376
lines changed

samples/EFCore.Cassandra.Samples/FakeDbContext.cs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,16 @@ namespace EFCore.Cassandra.Samples
1010
{
1111
public class FakeDbContext : DbContext
1212
{
13-
private const string CV_KEYSPACE = "cv";
1413
public DbSet<Applicant> Applicants { get; set; }
1514

1615
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
1716
{
18-
optionsBuilder.UseCassandra($"Contact Points=127.0.0.1", CV_KEYSPACE, opt =>
17+
optionsBuilder.UseCassandra("Contact Points=127.0.0.1;", "cv", opt =>
1918
{
20-
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName, CV_KEYSPACE);
21-
}, b =>
22-
{
23-
b.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalOne))
19+
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName);
20+
}, o => {
21+
22+
o.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalOne))
2423
.WithReconnectionPolicy(new ConstantReconnectionPolicy(1000))
2524
.WithRetryPolicy(new DefaultRetryPolicy())
2625
.WithLoadBalancingPolicy(new TokenAwarePolicy(Policies.DefaultPolicies.LoadBalancingPolicy))
@@ -39,9 +38,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
3938
protected override void OnModelCreating(ModelBuilder modelBuilder)
4039
{
4140
var timeUuidConverter = new TimeUuidToGuidConverter();
42-
modelBuilder.ForCassandraAddKeyspace(CV_KEYSPACE, new KeyspaceReplicationSimpleStrategyClass(2));
41+
modelBuilder.EnsureKeyspaceCreated(new KeyspaceReplicationSimpleStrategyClass(2));
4342
modelBuilder.Entity<Applicant>()
44-
.ToTable("applicants", CV_KEYSPACE)
43+
.ToTable("applicants")
4544
.HasKey(p => new { p.Id, p.Order });
4645
modelBuilder.Entity<Applicant>()
4746
.ForCassandraSetClusterColumns(_ => _.Order)
@@ -52,11 +51,8 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
5251
modelBuilder.Entity<Applicant>()
5352
.Property(p => p.Id)
5453
.HasColumnName("id");
55-
modelBuilder.Entity<CV>()
56-
.ToTable("cvs", CV_KEYSPACE)
57-
.HasKey(c => c.Id);
5854
modelBuilder.Entity<ApplicantAddress>()
59-
.ToUserDefinedType("applicant_addr", CV_KEYSPACE)
55+
.ToUserDefinedType("applicant_addr")
6056
.HasNoKey();
6157
}
6258
}

samples/EFCore.Cassandra.Samples/Migrations/20200917124959_InitialCreate.Designer.cs renamed to samples/EFCore.Cassandra.Samples/Migrations/20201112124214_Init.Designer.cs

Lines changed: 5 additions & 28 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

samples/EFCore.Cassandra.Samples/Migrations/20200917124959_InitialCreate.cs renamed to samples/EFCore.Cassandra.Samples/Migrations/20201112124214_Init.cs

Lines changed: 1 addition & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,10 @@
88

99
namespace EFCore.Cassandra.Samples.Migrations
1010
{
11-
public partial class InitialCreate : Migration
11+
public partial class Init : Migration
1212
{
1313
protected override void Up(MigrationBuilder migrationBuilder)
1414
{
15-
migrationBuilder.EnsureSchema(
16-
name: "cv");
17-
1815
migrationBuilder.CreateTable(
1916
name: "applicants",
2017
schema: "cv",
@@ -39,8 +36,6 @@ protected override void Up(MigrationBuilder migrationBuilder)
3936
LocalDate = table.Column<LocalDate>(nullable: true),
4037
Ip = table.Column<IPAddress>(nullable: true),
4138
LocalTime = table.Column<LocalTime>(nullable: true),
42-
Lst = table.Column<IEnumerable<string>>(nullable: true),
43-
LstInt = table.Column<IEnumerable<int>>(nullable: true),
4439
Dic = table.Column<IDictionary<string, string>>(nullable: true),
4540
Address = table.Column<ApplicantAddress>(type: "applicant_addr", nullable: true)
4641
},
@@ -49,20 +44,6 @@ protected override void Up(MigrationBuilder migrationBuilder)
4944
table.PrimaryKey("PK_applicants", x => new { x.id, x.Order });
5045
});
5146

52-
migrationBuilder.CreateTable(
53-
name: "cvs",
54-
schema: "cv",
55-
columns: table => new
56-
{
57-
Id = table.Column<Guid>(nullable: false),
58-
CvId = table.Column<Guid>(nullable: false),
59-
Name = table.Column<string>(nullable: true)
60-
},
61-
constraints: table =>
62-
{
63-
table.PrimaryKey("PK_cvs", x => x.Id);
64-
});
65-
6647
migrationBuilder.CreateUserDefinedType(
6748
name: "applicant_addr",
6849
schema: "cv",
@@ -79,10 +60,6 @@ protected override void Down(MigrationBuilder migrationBuilder)
7960
name: "applicants",
8061
schema: "cv");
8162

82-
migrationBuilder.DropTable(
83-
name: "cvs",
84-
schema: "cv");
85-
8663
migrationBuilder.DropUserDefinedType(
8764
name: "applicant_addr",
8865
schema: "cv");

samples/EFCore.Cassandra.Samples/Migrations/FakeDbContextModelSnapshot.cs

Lines changed: 3 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
1818
{
1919
#pragma warning disable 612, 618
2020
modelBuilder
21-
.HasAnnotation("Cassandra:Keyspacecv", "{\"ReplicationFactor\":2,\"ReplicationClass\":0}")
21+
.HasAnnotation("Cassandra:KeyspaceConfiguration", "{\"ReplicationFactor\":2,\"ReplicationClass\":0}")
2222
.HasAnnotation("ProductVersion", "3.1.4");
2323

2424
modelBuilder.Entity("EFCore.Cassandra.Samples.Models.Applicant", b =>
@@ -75,12 +75,6 @@ protected override void BuildModel(ModelBuilder modelBuilder)
7575
b.Property<long>("Long")
7676
.HasColumnType("bigint");
7777

78-
b.Property<IList<string>>("Lst")
79-
.HasColumnType("list<text>");
80-
81-
b.Property<IList<int>>("LstInt")
82-
.HasColumnType("list<int>");
83-
8478
b.Property<sbyte>("Sbyte")
8579
.HasColumnType("tinyint");
8680

@@ -92,7 +86,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
9286

9387
b.HasKey("Id", "Order");
9488

95-
b.ToTable("applicants","cv");
89+
b.ToTable("applicants");
9690

9791
b.HasAnnotation("Cassandra:ClusterColumns", new[] { "Order" });
9892

@@ -107,27 +101,10 @@ protected override void BuildModel(ModelBuilder modelBuilder)
107101
b.Property<int>("StreetNumber")
108102
.HasColumnType("int");
109103

110-
b.ToTable("applicant_addr","cv");
104+
b.ToTable("applicant_addr");
111105

112106
b.HasAnnotation("Cassandra:IsUserDefinedType", true);
113107
});
114-
115-
modelBuilder.Entity("EFCore.Cassandra.Samples.Models.CV", b =>
116-
{
117-
b.Property<Guid>("Id")
118-
.ValueGeneratedOnAdd()
119-
.HasColumnType("uuid");
120-
121-
b.Property<Guid>("CvId")
122-
.HasColumnType("uuid");
123-
124-
b.Property<string>("Name")
125-
.HasColumnType("text");
126-
127-
b.HasKey("Id");
128-
129-
b.ToTable("cvs","cv");
130-
});
131108
#pragma warning restore 612, 618
132109
}
133110
}

samples/EFCore.Cassandra.Samples/Program.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@
22
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
33
using Cassandra;
44
using EFCore.Cassandra.Samples.Models;
5-
using Microsoft.EntityFrameworkCore;
65
using System;
76
using System.Collections.Generic;
87
using System.Linq;
8+
using Microsoft.EntityFrameworkCore;
99
using System.Net;
10+
using System.Threading.Tasks;
1011

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

18-
static void Main(string[] args)
19+
static async Task Main(string[] args)
1920
{
2021
using (var dbContext = new FakeDbContext())
2122
{
@@ -25,7 +26,8 @@ static void Main(string[] args)
2526

2627
Console.WriteLine("Add applicant");
2728
var timeUuid = TimeUuid.NewId();
28-
dbContext.Applicants.Add(BuildApplicant());
29+
var app = BuildApplicant();
30+
dbContext.Applicants.Add(app);
2931
dbContext.SaveChanges();
3032
Console.WriteLine("Applicant is added");
3133

src/EFCore.Cassandra.Benchmarks/FakeDbContext.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
1717
{
1818
optionsBuilder.UseCassandra("Contact Points=127.0.0.1;", CV_KEYSPACE, opt =>
1919
{
20-
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName, CV_KEYSPACE);
20+
opt.MigrationsHistoryTable(HistoryRepository.DefaultTableName);
2121
}, o => {
2222

2323
o.WithQueryOptions(new QueryOptions().SetConsistencyLevel(ConsistencyLevel.LocalOne))
@@ -39,9 +39,9 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
3939
protected override void OnModelCreating(ModelBuilder modelBuilder)
4040
{
4141
var timeUuidConverter = new TimeUuidToGuidConverter();
42-
modelBuilder.ForCassandraAddKeyspace("CV_KEYSPACE", new KeyspaceReplicationSimpleStrategyClass(2));
42+
modelBuilder.EnsureKeyspaceCreated(new KeyspaceReplicationSimpleStrategyClass(2));
4343
modelBuilder.Entity<Applicant>()
44-
.ToTable("applicants", CV_KEYSPACE)
44+
.ToTable("applicants")
4545
.HasKey(p => new { p.Id, p.Order });
4646
modelBuilder.Entity<Applicant>()
4747
.ForCassandraSetClusterColumns(_ => _.Order)
@@ -53,7 +53,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
5353
.Property(p => p.Id)
5454
.HasColumnName("id");
5555
modelBuilder.Entity<ApplicantAddress>()
56-
.ToUserDefinedType("applicant_addr", CV_KEYSPACE)
56+
.ToUserDefinedType("applicant_addr")
5757
.HasNoKey();
5858
}
5959
}

src/EFCore.Cassandra/Bulk/SqlBulkOperation.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Cassandra;
44
using Cassandra.Data;
55
using Microsoft.EntityFrameworkCore;
6+
using Microsoft.EntityFrameworkCore.Cassandra.Infrastructure.Internal;
67
using Microsoft.EntityFrameworkCore.Infrastructure;
78
using Microsoft.EntityFrameworkCore.Metadata;
89
using Microsoft.EntityFrameworkCore.Storage;
@@ -34,6 +35,8 @@ private static (BatchStatement batchStatement, ISession session) BuildBatch<T>(D
3435
{
3536
var service = dbContext.GetService<ICommandBatchPreparer>();
3637
var sqlGenerationHelper = dbContext.GetService<ISqlGenerationHelper>();
38+
var relationalConnectionDependencies = dbContext.GetService<RelationalConnectionDependencies>();
39+
var cassandraOptionsExtension = CassandraOptionsExtension.Extract(relationalConnectionDependencies.ContextOptions);
3740
var database = dbContext.Database.GetDbConnection() as CqlConnection;
3841
if (database.State != ConnectionState.Open)
3942
{
@@ -58,7 +61,7 @@ private static (BatchStatement batchStatement, ISession session) BuildBatch<T>(D
5861
}
5962

6063
var tableName = entityType.GetTableName();
61-
var schema = entityType.GetSchema();
64+
var schema = cassandraOptionsExtension.DefaultKeyspace;
6265
var cqlQuery = $"INSERT INTO \"{schema}\".\"{tableName}\" ({string.Join(',', propertyNames)}) VALUES ({string.Join(',', Enumerable.Repeat(1, propertyNames.Count()).Select(_ => "?"))})";
6366
var smt = session.Prepare(cqlQuery);
6467
batch.Add(smt.Bind(propertyValues.ToArray()));
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright (c) SimpleIdServer. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
3+
using System;
4+
using Builder = Cassandra.Builder;
5+
6+
namespace EFCore.Cassandra
7+
{
8+
public class CassandraOptions
9+
{
10+
public string DefaultKeyspace { get; set; }
11+
public Action<Builder> ClusterBuilder { get; set; }
12+
}
13+
}

src/EFCore.Cassandra/CassandraServiceCollectionExtensions.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
using Microsoft.EntityFrameworkCore.Query;
1818
using Microsoft.EntityFrameworkCore.Storage;
1919
using Microsoft.EntityFrameworkCore.Update;
20+
using Microsoft.EntityFrameworkCore.Update.Internal;
2021

2122
namespace Microsoft.Extensions.DependencyInjection
2223
{
@@ -29,6 +30,7 @@ public static IServiceCollection AddEntityFrameworkCassandra(this IServiceCollec
2930
.TryAdd<IRelationalTypeMappingSource, CassandraTypeMappingSource>()
3031
.TryAdd<LoggingDefinitions, CassandraLoggingDefinitions>()
3132
.TryAdd<IMigrationsModelDiffer, CassandraMigrationsModelDiffer>()
33+
.TryAdd<ICommandBatchPreparer, CassandraCommandBatchPreparer>()
3234
// .TryAdd<IMemberTranslator, CassandraCompositeMemberTranslator>()
3335
.TryAdd<IMigrator, CassandraMigrator>()
3436
.TryAdd<ISqlGenerationHelper, CassandraSqlGenerationHelper>()
@@ -52,6 +54,7 @@ public static IServiceCollection AddEntityFrameworkCassandra(this IServiceCollec
5254
.TryAddProviderSpecificServices(b => b.TryAddTransient<ICassandraHistoryRepository, CassandraHistoryRepository>());
5355

5456
builder.TryAddCoreServices();
57+
serviceCollection.AddSingleton<IServiceCollection>(serviceCollection);
5558
return serviceCollection;
5659
}
5760
}

src/EFCore.Cassandra/Extensions/CassandraEntityTypeBuilderExtensions.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@ public static EntityTypeBuilder ForCassandraSetClusteringOrderBy(this EntityType
3535
return entityTypeBuilder;
3636
}
3737

38-
public static EntityTypeBuilder ToUserDefinedType(this EntityTypeBuilder entityTypeBuilder, string name, string schema)
38+
public static EntityTypeBuilder ToUserDefinedType(this EntityTypeBuilder entityTypeBuilder, string name)
3939
{
4040
entityTypeBuilder.Metadata.SetTableName(name);
41-
entityTypeBuilder.Metadata.SetSchema(schema);
4241
entityTypeBuilder.Metadata.SetIsUserDefinedType();
4342
return entityTypeBuilder;
4443
}

src/EFCore.Cassandra/Extensions/CassandraModelBuilderExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ namespace Microsoft.EntityFrameworkCore
55
{
66
public static class CassandraModelBuilderExtensions
77
{
8-
public static ModelBuilder ForCassandraAddKeyspace(this ModelBuilder modelBuilder, string keyspaceName, KeyspaceReplicationConfiguration configuration)
8+
public static ModelBuilder EnsureKeyspaceCreated(this ModelBuilder modelBuilder, KeyspaceReplicationConfiguration configuration)
99
{
1010
var model = modelBuilder.Model;
11-
model.SetKeyspace(keyspaceName, configuration);
11+
model.SetKeyspaceConfiguration(configuration);
1212
return modelBuilder;
1313
}
1414
}

0 commit comments

Comments
 (0)