Skip to content

Commit 7c312d8

Browse files
Merge pull request #8 from x7airworker/master
Add SQLDriverFactory
2 parents 607c2ed + 7e95d3f commit 7c312d8

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package org.javawebstack.orm.wrapper;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.function.Supplier;
6+
7+
public class SQLDriverFactory {
8+
private Map<String, Supplier<SQL>> suppliers = new HashMap<>();
9+
private Map<String, String> properties;
10+
11+
public SQLDriverFactory(Map<String, String> properties) {
12+
this.properties = properties;
13+
addDefaultDrivers();
14+
}
15+
16+
public void registerDriver (String name, Supplier<SQL> supplier) {
17+
suppliers.put(name, supplier);
18+
}
19+
20+
private void addDefaultDrivers() {
21+
registerDriver("sqlite", () -> new SQLite(properties.get("file")));
22+
registerDriver("mysql", () -> new MySQL(
23+
properties.get("host"),
24+
Integer.parseInt(properties.get("port")),
25+
properties.get("name"),
26+
properties.get("user"),
27+
properties.get("password")
28+
));
29+
}
30+
31+
public SQL getDriver(String name) throws SQLDriverNotFoundException {
32+
Supplier<SQL> supplier = suppliers.get(name);
33+
if (supplier == null)
34+
throw new SQLDriverNotFoundException(name);
35+
return supplier.get();
36+
}
37+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package org.javawebstack.orm.wrapper;
2+
3+
public class SQLDriverNotFoundException extends Exception {
4+
private String name;
5+
6+
public SQLDriverNotFoundException (String name) {
7+
this.name = name;
8+
}
9+
10+
11+
public String getMessage() {
12+
return "SQL Driver " + name + " not found!";
13+
}
14+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package org.javawebstack.orm.test;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.javawebstack.orm.wrapper.SQLDriverFactory;
6+
import org.javawebstack.orm.wrapper.SQLDriverNotFoundException;
7+
import org.junit.jupiter.api.Test;
8+
9+
import java.util.HashMap;
10+
11+
class SQLDriverFactoryTest {
12+
private SQLDriverFactory factory = new SQLDriverFactory(new HashMap<String, String>() {{
13+
put("file", "sb.sqlite");
14+
put("host", "localhost");
15+
put("port", "3306");
16+
put("name", "app");
17+
put("user", "root");
18+
put("password", "");
19+
}});
20+
21+
@Test
22+
public void testSQLite() throws SQLDriverNotFoundException {
23+
assertNotNull(factory.getDriver("sqlite"));
24+
}
25+
26+
@Test
27+
public void testMySQL() throws SQLDriverNotFoundException {
28+
assertNotNull(factory.getDriver("mysql"));
29+
}
30+
}

0 commit comments

Comments
 (0)