24 using System.Diagnostics.CodeAnalysis;
48 namespace Ntp.Data.Provider
56 private const string CreateDatabaseSql1 =
57 "SELECT COUNT(*) FROM pg_database WHERE datname = lower('{0}');";
59 private const string CreateDatabaseSql2 =
60 "CREATE DATABASE {0};";
62 private const string CheckTableSql =
64 "FROM information_schema.tables " +
65 "WHERE table_catalog = lower('{0}') " +
66 "AND table_name = lower('{1}');";
70 return new NpgsqlCommand();
75 return new NpgsqlConnection(BuildConnectionString());
78 [SuppressMessage(
"Microsoft.Security",
"CA2100:Review SQL queries for security vulnerabilities")]
81 var connection = CreateGenericConnection();
84 var command = Instance.CreateCommand();
85 command.Connection = connection;
86 command.CommandText =
string.Format(CreateDatabaseSql1, Config.Name);
88 int count = Convert.ToInt32(command.ExecuteScalar());
92 command.CommandText =
string.Format(CreateDatabaseSql2, Config.Name);
94 command.ExecuteNonQuery();
102 return new NpgsqlConnection(BuildConnectionString(
false));
107 return new NpgsqlParameter(name, value);
112 return $
"{dateColumn} - {minuteColumn} * INTERVAL '1 minute'";
117 return PrepareSql(
string.Format(CheckTableSql, Config.Name, table));
123 Replace(
"UNIQUE KEY",
"UNIQUE").
124 Replace(
"BIT(1)",
"BOOL");
126 return PrepareSql(
string.Format(sql2,
"SERIAL",
string.Empty));
131 return PrepareSql(
string.Format(sql,
"SELECT LASTVAL();"));
136 return sql.Replace(
'[',
'\"').Replace(
']',
'\"');
141 if (Config.ConnectionString != null)
142 return Config.ConnectionString;
144 var
b =
new StringBuilder();
145 b.Append($
"Server={Config.Host};");
147 if (Config.Port != null)
148 b.Append($
"Port={Config.Port};");
150 b.Append(includeName ? $
"Database={Config.Name};" :
@"Database=postgres;");
152 b.Append($
"User Id={Config.User};");
153 b.Append($
"Password={Config.Pass};");
155 if (Config.ConnectionTimeout.HasValue)
156 b.Append($
"Timeout={Config.ConnectionTimeout.Value};");
158 b.Append(Config.EnableSsl ?
@"SslMode=Require;" :
@"SslMode=Disable;");
160 if (Config.Protocol.HasValue)
161 b.Append($
"Protocol={Config.Protocol.Value};");
override string PrepareSql(string sql)
override string PrepareCheckTableSql(string table)
override IDbDataParameter CreateParameter(string name, object value)
override IDbCommand CreateCommand()
override string PrepareInsertSql(string sql)
override void CreateDatabase()
override IDbConnection CreateGenericConnection()
override string DateAddMinutes(string dateColumn, string minuteColumn)
override string PrepareCreateTableSql(string sql)
static string BuildConnectionString(bool includeName=true)
override IDbConnection CreateConnection()