-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathMigrate.cs
More file actions
113 lines (102 loc) · 3.27 KB
/
Migrate.cs
File metadata and controls
113 lines (102 loc) · 3.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
using System;
using System.Linq;
using Cassandra;
using Microsoft.Extensions.Logging;
namespace CarePet
{
public class Migrate
{
private static readonly ILogger<Migrate> LOG;
private readonly Config _config;
static Migrate()
{
// You can wire up any logger provider here (Console, Serilog, etc.)
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole();
});
LOG = loggerFactory.CreateLogger<Migrate>();
}
public Migrate(Config config)
{
_config = config;
}
public static void Main(string[] args)
{
var config = Config.Parse(new Config(), args);
var client = new Migrate(config);
client.CreateKeyspace();
client.CreateSchema();
client.PrintMetadata();
}
/// <summary>
/// Initiates a connection without a specific keyspace.
/// </summary>
public ISession Connect()
{
return _config.Builder().Build().Connect();
}
/// <summary>
/// Initiates a connection with the configured keyspace.
/// </summary>
public ISession Keyspace()
{
return _config.Builder(Config.Keyspace).Build().Connect();
}
/// <summary>
/// Creates the keyspace for this example.
/// </summary>
public void CreateKeyspace()
{
LOG.LogInformation("Creating keyspace carepet...");
using (var session = Connect())
{
var cql = Config.GetResource("care-pet-keyspace.cql");
if (!string.IsNullOrWhiteSpace(cql))
{
session.Execute(cql);
}
}
LOG.LogInformation("Keyspace carepet created successfully");
}
/// <summary>
/// Creates the tables for this example.
/// </summary>
public void CreateSchema()
{
LOG.LogInformation("Creating tables...");
using (var session = Keyspace())
{
var ddl = Config.GetResource("care-pet-ddl.cql");
if (!string.IsNullOrWhiteSpace(ddl))
{
var statements = ddl.Split(';')
.Select(s => s.Trim())
.Where(s => !string.IsNullOrEmpty(s));
foreach (var cql in statements)
{
session.Execute(cql);
}
}
}
}
/// <summary>
/// Prints keyspace metadata.
/// </summary>
public void PrintMetadata()
{
using (var session = Keyspace())
{
var metadata = session.Cluster.Metadata;
var ksMeta = metadata.GetKeyspace(Config.Keyspace);
if (ksMeta != null)
{
foreach (var table in ksMeta.GetTablesMetadata())
{
Console.WriteLine($"Keyspace: {Config.Keyspace}; Table: {table.Name}");
}
}
}
}
}
}