aboutsummaryrefslogtreecommitdiff
path: root/lib/VNLib.Plugins.Extensions.Loading.Sql/src/SqlDbConnectionLoader.cs
blob: b48ddd1d945737be7429662c458eeec0a799eaba (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
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
/*
* Copyright (c) 2024 Vaughn Nugent
* 
* Library: VNLib
* Package: VNLib.Plugins.Extensions.Loading.Sql
* File: SqlDbConnectionLoader.cs 
*
* SqlDbConnectionLoader.cs is part of VNLib.Plugins.Extensions.Loading.Sql which is part of the larger 
* VNLib collection of libraries and utilities.
*
* VNLib.Plugins.Extensions.Loading.Sql is free software: you can redistribute it and/or modify 
* it under the terms of the GNU Affero General Public License as 
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* VNLib.Plugins.Extensions.Loading.Sql is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see https://www.gnu.org/licenses/.
*/

using System;
using System.Data;
using System.Text;
using System.Data.Common;
using System.Threading.Tasks;
using System.Collections.Generic;

using Microsoft.EntityFrameworkCore;

using VNLib.Utils.Logging;
using VNLib.Plugins.Extensions.Loading.Sql.DatabaseBuilder;

namespace VNLib.Plugins.Extensions.Loading.Sql
{

    /// <summary>
    /// Provides common basic SQL loading extensions for plugins
    /// </summary>
    public static class SqlDbConnectionLoader
    {
        public const string SQL_CONFIG_KEY = "sql";
        public const string DB_PASSWORD_KEY = "db_password";
        public const string SQL_PROVIDER_DLL_KEY = "provider";
  

        /// <summary>
        /// Gets (or loads) the ambient sql connection factory for the current plugin 
        /// and synchronously blocks the current thread until the connection is ready.
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The ambient <see cref="DbConnection"/> factory</returns>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        public static Func<DbConnection> GetConnectionFactory(this PluginBase plugin)
        {
            //Get the async factory
            IAsyncLazy<Func<DbConnection>> async = plugin.GetConnectionFactoryAsync();

            //Block the current thread until the connection is ready
            return async.GetAwaiter().GetResult();
        }

        /// <summary>
        /// Gets (or loads) the ambient sql connection factory for the current plugin
        /// asynchronously
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The ambient <see cref="DbConnection"/> factory</returns>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        public static IAsyncLazy<Func<DbConnection>> GetConnectionFactoryAsync(this PluginBase plugin)
        {
            IRuntimeDbProvider provider = plugin.GetDbProvider();
            return provider.GetDbConnectionAsync().AsLazy();
        }

        private static IRuntimeDbProvider GetDbProvider(this PluginBase plugin)
        {
            plugin.ThrowIfUnloaded();
            return LoadingExtensions.GetOrCreateSingleton(plugin, LoadDbProvider);
        }

        private static IRuntimeDbProvider LoadDbProvider(PluginBase plugin)
        {
            //Get the sql configuration scope
            IConfigScope sqlConf = plugin.GetConfig(SQL_CONFIG_KEY);
         
            //Get the provider dll path
            string dllPath = sqlConf.GetRequiredProperty(SQL_PROVIDER_DLL_KEY, k => k.GetString()!);
           
            /*
             * I am loading a bare object here and dynamically resolbing the required methods
             * insead of forcing a shared interface. This allows the external library to be
             * more flexible and slimmer.
             */
            return plugin.CreateServiceExternal<IRuntimeDbProvider>(dllPath);
        }

        /// <summary>
        /// Gets (or loads) the ambient <see cref="DbContextOptions"/> configured from 
        /// the ambient sql factory and blocks the current thread until the options are ready
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The ambient <see cref="DbContextOptions"/> for the current plugin</returns>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <remarks>If plugin is in debug mode, writes log data to the default log</remarks>
        public static DbContextOptions GetContextOptions(this PluginBase plugin)
        {
            //Get the async factory
            IAsyncLazy<DbContextOptions> async = plugin.GetContextOptionsAsync();

            //Block the current thread until the connection is ready
            return async.GetAwaiter().GetResult();
        }

        /// <summary>
        /// Gets (or loads) the ambient <see cref="DbContextOptions"/> configured from 
        /// the ambient sql factory
        /// </summary>
        /// <param name="plugin"></param>
        /// <returns>The ambient <see cref="DbContextOptions"/> for the current plugin</returns>
        /// <exception cref="KeyNotFoundException"></exception>
        /// <exception cref="ObjectDisposedException"></exception>
        /// <remarks>If plugin is in debug mode, writes log data to the default log</remarks>
        public static IAsyncLazy<DbContextOptions> GetContextOptionsAsync(this PluginBase plugin)
        {
            IRuntimeDbProvider provider = plugin.GetDbProvider();
            return provider.GetDbOptionsAsync().AsLazy();
        }

        /// <summary>
        /// Ensures the tables that back your desired DbContext exist within the configured database, 
        /// or creates them if needed.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pbase"></param>
        /// <param name="state">The state object to pass to the <see cref="IDbTableDefinition.OnDatabaseCreating(IDbContextBuilder, object?)"/></param>
        /// <returns>A task that resolves when the tables have been created</returns>
        public static Task EnsureDbCreatedAsync<T>(this PluginBase pbase, object? state) where T : IDbTableDefinition, new()
        {
            T creator = new ();
            return EnsureDbCreatedAsync(pbase, creator, state);
        }

        /// <summary>
        /// Ensures the tables that back your desired DbContext exist within the configured database, 
        /// or creates them if needed.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="plugin"></param>
        /// <param name="dbCreator">The instance of the <see cref="IDbTableDefinition"/> to build the database from</param>
        /// <param name="state">The state object to pass to the <see cref="IDbTableDefinition.OnDatabaseCreating(IDbContextBuilder, object?)"/></param>
        /// <returns>A task that resolves when the tables have been created</returns>
        public static async Task EnsureDbCreatedAsync<T>(this PluginBase plugin, T dbCreator, object? state) where T : IDbTableDefinition
        {
            ArgumentNullException.ThrowIfNull(plugin);
            ArgumentNullException.ThrowIfNull(dbCreator);

            DbBuilder builder = new();

            //Invoke onDbCreating to setup the dbBuilder and table's for the context
            dbCreator.OnDatabaseCreating(builder, state);

            //Get the abstract database from the connection type
            IRuntimeDbProvider dbp = plugin.GetDbProvider();
            IDBCommandGenerator cb = dbp.GetCommandGenerator();

            //Wait for the connection factory to load
            Func<DbConnection> dbConFactory = await dbp.GetDbConnectionAsync();

            //Create a new db connection
            await using DbConnection connection = dbConFactory();

            //Compile the db command as a text Sql command
            string[] createComamnds = builder.BuildCreateCommand(cb);

            //begin connection
            await connection.OpenAsync(plugin.UnloadToken);

            //Transaction
            await using DbTransaction transaction = await connection.BeginTransactionAsync(IsolationLevel.Serializable, plugin.UnloadToken);

            //Init new text command
            await using DbCommand command = connection.CreateCommand();
            command.Transaction = transaction;
            command.CommandType = CommandType.Text;

            foreach (string createCmd in createComamnds)
            {
                if (plugin.IsDebug())
                {
                    plugin.Log.Debug("Creating new table for {type} with command\n{cmd}", typeof(T).Name, createCmd);
                }

                //Set the command, were not using parameters, so we dont need to clear anyting
                command.CommandText = createCmd;

                //Excute the command, it may return 0 if the table's already exist
                _ = await command.ExecuteNonQueryAsync(plugin.UnloadToken);
            }

            //Commit transaction now were complete
            await transaction.CommitAsync(plugin.UnloadToken);

            //All done!
            plugin.Log.Debug("Successfully created tables for {type}", typeof(T).Name);
        }
    }
}