ホテル管理システム
ogi
yesterday 1a1c8e71fcd14858f595029f089b2d4a00202b32
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
using HotelPms.Share.IO;
using Npgsql;
using System.Data;
using System.Data.Common;
 
namespace HotelPms.Share.Data;
 
public class PostgreSqlNet : DataAccess
{
    #region  ★★★★★ Declartions ★★★★★
 
    public string ConnectionString { get; set; } = string.Empty;
 
    /// <summary>ユーザー</summary>
    public override string UseID { get; set; } = string.Empty;
 
    /// <summary>パスワード</summary>
    public override string PassWord { get; set; } = string.Empty;
 
    /// <summary>データベース所在のパソコン名</summary>
    public override string DataSource { get; set; } = string.Empty;
 
    /// <summary>データベース名</summary>
    public override string Catalog { get; set; } = string.Empty;
 
    public override string Schema { get; set; } = "public";
 
    public override int Port { get; set; } = 5432;
 
    /// <summary>
    /// デッドロック関連: 1205,3635,5231,5252,17888,22840,23424
    /// </summary>
    public int Message_id { get; set; } = 0;
 
    public string SqlState { get; set; } = string.Empty;
 
    /// <summary>エラー情報</summary>
    public override string ErrInfo { get; set; } = string.Empty;
 
    /// <summary>エラーコード</summary>
    public override int ErrNo { get; set; } = 0;
 
    public bool PoolEnabled { get; set; } = false;
 
    public int MaxPoolSize { get; set; } = 1000;
 
    public int RetryCount { get; set; } = 12;
 
    public int RetryInterval { get; set; } = 5;
 
    /// <summary>
    /// タイマー単位のSQL
    /// </summary>
    public bool IsTimerAccess { get; set; } = false;
 
    public bool FireInfoMessageEventOnUserErrors { get; set; } = false;
 
    public bool MessageEventEnabled { get; set; } = false;
 
    #endregion
 
 
    public PostgreSqlNet(string connectionString)
    {
        ConnectionString = connectionString;
        NpgsqlConnectionStringBuilder ssb = new NpgsqlConnectionStringBuilder(connectionString);
        DataSource = ssb.Host;
        Port = ssb.Port;
        UseID = ssb.Username;
        PassWord = ssb.Password;
        Catalog = ssb.Database;
        MaxPoolSize = ssb.MaxPoolSize;
    }
 
    public PostgreSqlNet(DBConnectItem connecitem) : this(connecitem.HostName, connecitem.UserID, connecitem.Password, connecitem.Port, connecitem.DBName)
    { }
 
    public PostgreSqlNet(string dataSource, string userID, string passWord) : this(dataSource, userID, passWord, 5432, "postgres")
    {
    }
 
    public PostgreSqlNet(string dataSource, string userID, string passWord, int port) : this(dataSource, userID, passWord, port, "postgres")
    { }
 
    public PostgreSqlNet(string dataSource, string userID, string passWord, int port,  string catalog)
    {
        DataSource = dataSource;
        Port = port;
        UseID = userID;
        PassWord = passWord;
        Catalog = catalog;
        ResetConnectionString();
    }
 
    public override void Dispose()
    {
 
    }
 
    public void ResetConnectionString()
    {
        NpgsqlConnectionStringBuilder ssb = new NpgsqlConnectionStringBuilder();
        ssb.Host = DataSource;
        ssb.Port = Port;
        ssb.Username = UseID;
        ssb.Password = PassWord;
        ssb.Database = Catalog;
        ssb.Enlist = true;
        //ssb.MaxPoolSize = MaxPoolSize;
        ssb.ApplicationName = System.IO.Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
        ssb.Encoding = "UTF8";
        //ssb.ApplicationName = System.IO.Path.GetFileNameWithoutExtension(Application.ExecutablePath);
        ConnectionString = ssb.ToString();
    }
 
    public static bool CreateDataBase(DBConnectItem item)
    {
        using (PostgreSqlNet dbAccess = new PostgreSqlNet(item.HostName, item.UserID, item.Password, item.Port))
        {
            if (dbAccess.ErrNo != 0) { return false; }
            return (dbAccess.ExecuteNonQuery($"CREATE DATABASE \"{item.DBName}\" ENCODING 'UTF8'") != -1);
        }
    }
 
    /// 可変戻り値
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sql"></param>
    /// <param name="fillReaderHandler"></param>
    /// <returns></returns>
    public override T GetDataReader<T>(string sql, Action<DbDataReader, T> Fetch)
    {
        OperationLog.Instance.WriteLog(string.Format("MsSqlNet.GetDataReader({0})", sql), GetLogLevel());
        for (int i = 0; i < RetryCount; i++)
        {
            if (i > 0) { OperationLog.Instance.WriteLog(string.Format("{1}⇒MsSqlNet.GetDataReader({0})", sql, i), OperationLog.LogLevelType.Normal); }
            try
            {
                ErrClear();
                T t = new T();
                using (NpgsqlConnection dbConnect = Open())
                {
                    using (NpgsqlCommand command = new NpgsqlCommand(sql, dbConnect))
                    {
                        command.CommandTimeout = 6000;
                        using (NpgsqlDataReader reader = command.ExecuteReader(CommandBehavior.Default))
                        {
                            
                            Fetch(reader, t);
                        }  //自動クロス
                    }
                }
                return t;
            }
            catch (Exception ex)
            {
                if (!IsTransient(ex, sql)) { return default; }
            }
            Thread.Sleep(RetryInterval * 1000);
        }
        return default;
    }
 
    public override DataSet GetDataSet(string sql)
    {
        throw new NotImplementedException();
    }
 
    public override DataSet GetDataSetWithTran(string sql)
    {
        throw new NotImplementedException();
    }
 
    public override DataTable GetDataTable(string sql)
    {
        OperationLog.Instance.WriteLog(string.Format("GetDataTable({0})", sql), GetLogLevel());
        for (int i = 0; i < RetryCount; i++)
        {
            if (i > 0) { OperationLog.Instance.WriteLog(string.Format("{1}⇒GetDataTable({0})", sql, i), OperationLog.LogLevelType.Normal); }
            try
            {
                ErrClear();
                using (NpgsqlConnection dbConnect = Open())
                {
                    using (NpgsqlCommand command = new NpgsqlCommand(sql, dbConnect))
                    {
                        command.CommandTimeout = 60000;
                        DataTable dataTable = new DataTable();
                        using (NpgsqlDataAdapter adapter = new NpgsqlDataAdapter())
                        {
                            adapter.SelectCommand = command;
                            adapter.Fill(dataTable);
                        }
                        return dataTable;
                    }
                }
            }
            catch (Exception ex)
            {
                if (!IsTransient(ex, sql)) { return null; }
            }
            Thread.Sleep(RetryInterval * 1000);
        }
        return null;
    }
 
    public override object ExecuteScalar(string sql)
    {
        OperationLog.Instance.WriteLog($"ExecuteScalar({sql})", GetLogLevel());
 
        for (int i = 0; i < RetryCount; i++)
        {
            if (i > 0) { OperationLog.Instance.WriteLog($"{i}⇒ExecuteScalar({sql})", OperationLog.LogLevelType.Normal); }
            try
            {
                ErrClear();
                using (NpgsqlConnection dbConnect = Open())
                {
                    using (NpgsqlCommand command = new NpgsqlCommand(sql, dbConnect))
                    {
                        return command.ExecuteReader();
                    }
                }
            }
            catch (Exception ex)
            {
                if (!IsTransient(ex, sql)) { return null; }
            }
            Thread.Sleep(RetryInterval * 1000);
        }
        return null;
    }
 
    public override int ExecuteGetID(string sql)
    {
        throw new NotImplementedException();
    }
 
    public override int ExecuteNonQuery(string sql)
    {
        OperationLog.Instance.WriteLog($"ExecuteNonQuery({sql})", GetLogLevel());
 
        for (int i = 0; i < RetryCount; i++)
        {
            if (i > 0) { OperationLog.Instance.WriteLog($"{i}⇒ExecuteNonQuery({sql})", OperationLog.LogLevelType.Normal); }
            try
            {
                ErrClear();
                using (NpgsqlConnection dbConnect = Open())
                {
                    using (NpgsqlCommand command = new NpgsqlCommand(sql, dbConnect))
                    {
                        int row = command.ExecuteNonQuery();
                        return (row == -1 ? 0 : row);
                    }
                }
            }
            catch (Exception ex)
            {
                if (!IsTransient(ex, sql)) { return -1; }
            }
            Thread.Sleep(RetryInterval * 1000);
        }
        return -1;
    }
 
    public override bool ExecuteNonQueryWithTran(string sql)
    {
        OperationLog.Instance.WriteLog($"ExecuteNonQuery({sql})", GetLogLevel());
 
        for (int i = 0; i < RetryCount; i++)
        {
            if (i > 0) { OperationLog.Instance.WriteLog($"{i}⇒ExecuteNonQuery({sql})", OperationLog.LogLevelType.Normal); }
            NpgsqlTransaction tran = null;
            try
            {
                ErrClear();
                using (NpgsqlConnection dbConnect = Open())
                {
                    tran = dbConnect.BeginTransaction();
                    using (NpgsqlCommand command = new NpgsqlCommand(sql, dbConnect))
                    {
                        int row = command.ExecuteNonQuery();
                        if (row == -1)
                        {
                            tran.Rollback();
                            return false;
                        }
                        else
                        {
                            tran.Commit();
                            return true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                tran?.Rollback(); 
                if (!IsTransient(ex, sql)) { return false; }
            }
            Thread.Sleep(RetryInterval * 1000);
        }
        return false;
    }
 
    public NpgsqlConnection Open()
    {
        NpgsqlConnection dbConnect = new NpgsqlConnection();
        dbConnect.ConnectionString = ConnectionString;
        dbConnect.Open();
        return dbConnect;
    }
 
    /// <summary>
    /// 一時的なエラー
    /// </summary>
    /// <param name="ex"></param>
    /// <returns></returns>
    private bool IsTransient(Exception ex, string sql)
    {
        NpgsqlException exSql = null;
        if (ex is NpgsqlException)
        {
            exSql = ex as NpgsqlException;
            Message_id = exSql.HResult;
            ErrNo = exSql.ErrorCode;
            SqlState = exSql.SqlState;
        }
        else
        {
            ErrNo = -1;
        }
        ErrInfo = ex.Message;
        OperationLog.Instance.WriteLog(string.Format("IsTransient({0},{1},{2},{3})", Message_id, ErrNo, ErrInfo, sql), OperationLog.LogLevelType.Normal);
 
        if (exSql != null)
        {
            //Specifies whether the exception is considered transient, that is, whether retrying the operation could succeed (e.g. a network error or a timeout).
            if (exSql.IsTransient) { return true; }
            if (exSql.SqlState == "40P01") { return true; }  //デッドロックの検出
        }
        else if (ex is TimeoutException)
        {
            return true;
        }
        return false;
    }
 
    private void ErrClear()
    {
        ErrNo = 0;
        ErrInfo = string.Empty;
        SqlState = string.Empty;
        Message_id = 0;
    }
 
    private OperationLog.LogLevelType GetLogLevel()
    {
        return IsTimerAccess ? OperationLog.LogLevelType.Level8 : OperationLog.LogLevelType.Level7;
    }
 
    /// <summary>
    /// テーブル一覧を取得
    /// ※一般的にschema = publicですが
    /// </summary>
    /// <returns></returns>
    public override DataTable GetTableList()
    {
        return GetDataTable($"SELECT \"table_name\" AS \"Name\" FROM \"information_schema\".\"tables\" WHERE \"table_schema\"='{Schema}';");
    }
 
    /// <summary>
    /// テーブル一覧を取得
    /// </summary>
    /// <returns></returns>
    public override DataTable GetTableList(string whereAdding)
    {
        return GetDataTable($"SELECT \"table_name\" AS \"Name\" FROM \"information_schema\".\"tables\" WHERE \"table_schema\"='{Schema}' AND {whereAdding};");
    }
}