1
+ using System . Data . Common ;
2
+ using Npgsql ;
3
+
4
+ namespace DBAccess . DatabaseConnectors
5
+ {
6
+ public class PostgresConnector : IDatabaseConnector
7
+ {
8
+ private static string ? dbUsername = Environment . GetEnvironmentVariable ( "DB_USERNAME" ) ;
9
+ private static string ? dbPassword = Environment . GetEnvironmentVariable ( "DB_PASSWORD" ) ;
10
+ private NpgsqlConnection ? connection ;
11
+
12
+ public PostgresConnector ( string ? host , string ? databaseName , string ? databasePort )
13
+ {
14
+ host = ( host == null ) ? "localhost" : host ;
15
+ databaseName = ( databaseName == null ) ? "postgres" : databaseName ;
16
+ databasePort = ( databasePort == null ) ? "5432" : databasePort ;
17
+
18
+ var connectionString = buildConnectionString ( host , dbUsername , dbPassword , databaseName , databasePort ) ;
19
+ try
20
+ {
21
+ ConnectToDatabase ( connectionString ) ;
22
+ }
23
+ catch ( Exception e )
24
+ {
25
+ Console . WriteLine ( e . Message ) ;
26
+ }
27
+
28
+ }
29
+
30
+ public string GetTables ( )
31
+ {
32
+ var sqlQuerry = "select * from pg_catalog.pg_tables where schemaname != 'pg_catalog' and schemaname != 'information_schema';" ;
33
+ return ExecuteSQL ( sqlQuerry ) ;
34
+ }
35
+ public static string ? GetUsername ( )
36
+ {
37
+ return dbUsername ;
38
+ }
39
+
40
+ public string ? GetDatabaseVersion ( string ? host , string databaseName , string databasePort )
41
+ {
42
+
43
+ var sqlQuery = "SELECT version()" ;
44
+
45
+ return ExecuteSQL ( sqlQuery ) ;
46
+ }
47
+
48
+ public string ExecuteSQL ( string SQLQuery )
49
+ {
50
+ using var command = new NpgsqlCommand ( SQLQuery , connection ) ;
51
+ string ? queryResult = "" ;
52
+ try
53
+ {
54
+ if ( command . ExecuteScalar ( ) != null &&
55
+ connection != null )
56
+ {
57
+ queryResult = command . ExecuteScalar ( ) . ToString ( ) ;
58
+ }
59
+ }
60
+ catch ( Exception e )
61
+ {
62
+ Console . WriteLine ( e . Message ) ;
63
+ return e . Message ;
64
+ }
65
+
66
+
67
+ return queryResult ;
68
+ }
69
+
70
+ private void ConnectToDatabase ( string connectionString )
71
+ {
72
+ connection = new NpgsqlConnection ( connectionString ) ;
73
+ connection . Open ( ) ;
74
+ }
75
+
76
+ private string buildConnectionString ( string host , string ? username , string ? password , string databaseName , string databasePort )
77
+ {
78
+ string usernameConstruct =
79
+ username == null ? "" : $ "Username={ username } ;";
80
+ string passwordConstruct =
81
+ password == null ? "" : $ "Password={ password } ;";
82
+ return $ "Host={ host } ;{ usernameConstruct } { passwordConstruct } Database={ databaseName } ;Port={ databasePort } ";
83
+ }
84
+
85
+ }
86
+ }
0 commit comments