-
Notifications
You must be signed in to change notification settings - Fork 84
/
SQLServerOutputConnector.java
69 lines (59 loc) · 2.14 KB
/
SQLServerOutputConnector.java
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
package org.embulk.output.sqlserver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.embulk.output.jdbc.JdbcOutputConnection;
import org.embulk.output.jdbc.AbstractJdbcOutputConnector;
import org.embulk.spi.Exec;
import org.slf4j.Logger;
public class SQLServerOutputConnector
extends AbstractJdbcOutputConnector
{
private final Logger logger = Exec.getLogger(getClass());
private final String url;
private final Properties properties;
private final String schemaName;
public SQLServerOutputConnector(String url, Properties properties, String schemaName)
{
this.url = url;
this.properties = properties;
this.schemaName = schemaName;
}
@Override
protected JdbcOutputConnection connect() throws SQLException
{
Connection c = DriverManager.getConnection(url, properties);
if (c == null) {
// driver.connect returns null when url is "jdbc:mysql://...".
throw new SQLException("Invalid url : " + url);
}
String schemaName = this.schemaName;
if (schemaName == null) {
// get default schema name for user (Connection#getSchema won't work)
try {
try (PreparedStatement statement = c.prepareStatement("SELECT default_schema_name FROM sys.database_principals WHERE name = ?")) {
statement.setString(1, properties.getProperty("user"));
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
schemaName = rs.getString(1);
}
}
}
} catch (SQLException e) {
logger.warn("Cannot specify default schema : " + e);
}
}
try {
SQLServerOutputConnection con = new SQLServerOutputConnection(c, schemaName);
c = null;
return con;
} finally {
if (c != null) {
c.close();
}
}
}
}