aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Core/Data/DataExtensions.cs
blob: 20766619eeb706a457cd9d5b498f1dcd5149f868 (plain)
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
using System;
using System.Data;
using System.IO;
using System.Text;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Serialization;

namespace Emby.Server.Core.Data
{
    public static class DataExtensions
    {
        /// <summary>
        /// Determines whether the specified conn is open.
        /// </summary>
        /// <param name="conn">The conn.</param>
        /// <returns><c>true</c> if the specified conn is open; otherwise, <c>false</c>.</returns>
        public static bool IsOpen(this IDbConnection conn)
        {
            return conn.State == ConnectionState.Open;
        }

        public static IDataParameter GetParameter(this IDbCommand cmd, int index)
        {
            return (IDataParameter)cmd.Parameters[index];
        }

        public static IDataParameter GetParameter(this IDbCommand cmd, string name)
        {
            return (IDataParameter)cmd.Parameters[name];
        }

        public static IDataParameter Add(this IDataParameterCollection paramCollection, IDbCommand cmd, string name, DbType type)
        {
            var param = cmd.CreateParameter();

            param.ParameterName = name;
            param.DbType = type;

            paramCollection.Add(param);

            return param;
        }

        public static IDataParameter Add(this IDataParameterCollection paramCollection, IDbCommand cmd, string name)
        {
            var param = cmd.CreateParameter();
            
            param.ParameterName = name;

            paramCollection.Add(param);

            return param;
        }


        /// <summary>
        /// Gets a stream from a DataReader at a given ordinal
        /// </summary>
        /// <returns>Stream.</returns>
        /// <exception cref="System.ArgumentNullException">reader</exception>
        public static Stream GetMemoryStream(this IDataReader reader, int ordinal, IMemoryStreamFactory streamProvider)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            var memoryStream = streamProvider.CreateNew();
            var num = 0L;
            var array = new byte[4096];
            long bytes;
            do
            {
                bytes = reader.GetBytes(ordinal, num, array, 0, array.Length);
                memoryStream.Write(array, 0, (int)bytes);
                num += bytes;
            }
            while (bytes > 0L);
            memoryStream.Position = 0;
            return memoryStream;
        }

        /// <summary>
        /// Runs the queries.
        /// </summary>
        /// <param name="connection">The connection.</param>
        /// <param name="queries">The queries.</param>
        /// <param name="logger">The logger.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
        /// <exception cref="System.ArgumentNullException">queries</exception>
        public static void RunQueries(this IDbConnection connection, string[] queries, ILogger logger)
        {
            if (queries == null)
            {
                throw new ArgumentNullException("queries");
            }

            using (var tran = connection.BeginTransaction())
            {
                try
                {
                    using (var cmd = connection.CreateCommand())
                    {
                        foreach (var query in queries)
                        {
                            cmd.Transaction = tran;
                            cmd.CommandText = query;
                            cmd.ExecuteNonQuery();
                        }
                    }

                    tran.Commit();
                }
                catch (Exception e)
                {
                    logger.ErrorException("Error running queries", e);
                    tran.Rollback();
                    throw;
                }
            }
        }

        public static void Attach(IDbConnection db, string path, string alias)
        {
            using (var cmd = db.CreateCommand())
            {
                cmd.CommandText = string.Format("attach @dbPath as {0};", alias);
                cmd.Parameters.Add(cmd, "@dbPath", DbType.String);
                cmd.GetParameter(0).Value = path;

                cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// Serializes to bytes.
        /// </summary>
        /// <returns>System.Byte[][].</returns>
        /// <exception cref="System.ArgumentNullException">obj</exception>
        public static byte[] SerializeToBytes(this IJsonSerializer json, object obj, IMemoryStreamFactory streamProvider)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            using (var stream = streamProvider.CreateNew())
            {
                json.SerializeToStream(obj, stream);
                return stream.ToArray();
            }
        }

        public static void AddColumn(this IDbConnection connection, ILogger logger, string table, string columnName, string type)
        {
            using (var cmd = connection.CreateCommand())
            {
                cmd.CommandText = "PRAGMA table_info(" + table + ")";

                using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
                {
                    while (reader.Read())
                    {
                        if (!reader.IsDBNull(1))
                        {
                            var name = reader.GetString(1);

                            if (string.Equals(name, columnName, StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }
                        }
                    }
                }
            }

            var builder = new StringBuilder();

            builder.AppendLine("alter table " + table);
            builder.AppendLine("add column " + columnName + " " + type + " NULL");

            connection.RunQueries(new[] { builder.ToString() }, logger);
        }
    }
}