1+ using dotenv . net ;
2+ using Microsoft . Data . Sqlite ;
3+ using System ;
4+ using System . IO ;
5+ using System . Text . RegularExpressions ;
6+
7+ namespace SqlcGenCsharpTests
8+ {
9+ public static class EndToEndCommon
10+ {
11+ private const string EnvFile = ".env" ;
12+ private const string SchemaFile = "sqlite.schema.sql" ;
13+
14+ public const string PostgresConnectionStringEnv = "POSTGRES_CONNECTION_STRING" ;
15+ public const string MySqlConnectionStringEnv = "MYSQL_CONNECTION_STRING" ;
16+ public const string SqliteConnectionStringEnv = "SQLITE_CONNECTION_STRING" ;
17+
18+ public static void SetUp ( )
19+ {
20+ if ( File . Exists ( EnvFile ) )
21+ DotEnv . Load ( options : new DotEnvOptions ( envFilePaths : new [ ] { EnvFile } ) ) ;
22+ RemoveExistingSqliteDb ( ) ;
23+ if ( File . Exists ( SchemaFile ) )
24+ InitSqliteDb ( ) ;
25+ }
26+
27+ public static void TearDown ( )
28+ {
29+ RemoveExistingSqliteDb ( ) ;
30+ }
31+
32+ private static void RemoveExistingSqliteDb ( )
33+ {
34+ var connectionString = Environment . GetEnvironmentVariable ( SqliteConnectionStringEnv ) ;
35+ if ( connectionString == null ) return ;
36+
37+ var dbFilename = SqliteFilenameRegex . Match ( connectionString ) . Groups [ 1 ] . Value ;
38+ Console . WriteLine ( $ "Removing sqlite db from { dbFilename } ") ;
39+ if ( File . Exists ( dbFilename ) )
40+ File . Delete ( dbFilename ) ;
41+ }
42+ private static void InitSqliteDb ( )
43+ {
44+ var schemaSql = File . ReadAllText ( SchemaFile ) ;
45+ var connectionString = Environment . GetEnvironmentVariable ( EndToEndCommon . SqliteConnectionStringEnv ) ;
46+ using ( var connection = new SqliteConnection ( connectionString ) )
47+ {
48+ connection . Open ( ) ;
49+ using ( var command = connection . CreateCommand ( ) )
50+ {
51+ command . CommandText = schemaSql ;
52+ command . ExecuteNonQuery ( ) ;
53+ }
54+ }
55+ }
56+
57+ private static readonly Regex SqliteFilenameRegex = new Regex ( @"Data Source=([\w\.\/\-]+\.db);" , RegexOptions . Compiled ) ;
58+ }
59+ }
0 commit comments