1 module hunt.framework.provider.DatabaseServiceProvider;
2 
3 import hunt.framework.provider.ServiceProvider;
4 import hunt.framework.config.ApplicationConfig;
5 
6 import hunt.logging;
7 import hunt.entity;
8 import poodinis;
9 
10 /**
11  * 
12  */
13 class DatabaseServiceProvider : ServiceProvider {
14     private bool _isEnabled = true;
15 
16     override void register() {
17         container.register!EntityManagerFactory.initializedBy(&buildEntityManagerFactory)
18             .singleInstance();
19     }
20 
21     private EntityManagerFactory buildEntityManagerFactory() {
22         ApplicationConfig appConfig = container.resolve!ApplicationConfig();
23         ApplicationConfig.DatabaseConf config = appConfig.database;
24 
25         if (config.enabled) {
26 
27             import hunt.entity.EntityOption;
28 
29             auto option = new EntityOption;
30 
31             // database options
32             option.database.driver = config.driver;
33             option.database.host = config.host;
34             option.database.username = config.username;
35             option.database.password = config.password;
36             option.database.port = config.port;
37             option.database.database = config.database;
38             option.database.charset = config.charset;
39             option.database.prefix = config.prefix;
40 
41             // database pool options
42             option.pool.minIdle = config.pool.minIdle;
43             option.pool.idleTimeout = config.pool.idleTimeout;
44             option.pool.maxPoolSize = config.pool.maxPoolSize;
45             option.pool.minPoolSize = config.pool.minPoolSize;
46             option.pool.maxLifetime = config.pool.maxLifetime;
47             option.pool.connectionTimeout = config.pool.connectionTimeout;
48             option.pool.maxConnection = config.pool.maxConnection;
49             option.pool.minConnection = config.pool.minConnection;
50             option.pool.maxWaitQueueSize = config.pool.maxWaitQueueSize;
51 
52             version(HUNT_DEBUG) infof("Using database: %s", config.driver);
53             return Persistence.createEntityManagerFactory(option);
54         } else {
55             // version(HUNT_DEBUG) warning("The database is disabled.");
56             // return null;
57             throw new Exception("The database is disabled.");
58         }
59     }
60 
61     override void boot() {
62         ApplicationConfig appConfig = container.resolve!ApplicationConfig();
63         ApplicationConfig.DatabaseConf config = appConfig.database;
64         if(config.enabled) {
65             EntityManagerFactory factory = container.resolve!EntityManagerFactory();
66         }
67     }
68 }