View Javadoc

1   package de.mxro.async.map.sql;
2   
3   import java.sql.CallableStatement;
4   import java.sql.Connection;
5   import java.sql.SQLException;
6   
7   import de.mxro.async.map.AsyncMap;
8   import de.mxro.async.map.sql.internal.SqlAsyncMapImplementation;
9   import de.mxro.async.map.sql.internal.SqlConnectionFactory;
10  
11  /**
12   * <p>
13   * Core methods to interact with async-map-sql module.
14   * <p>
15   * Use {@link #createMap(SqlAsyncMapConfiguration, SqlAsyncMapDependencies)} to
16   * create new SQL backed up AsyncMaps.
17   * 
18   * @author <a href="http://www.mxro.de">Max Rohde</a>
19   *
20   */
21  public class AsyncMapSql {
22  
23  	/**
24  	 * Creates a new AsyncMap persisted by a JDBC compatible SQL database.
25  	 * 
26  	 * @param conf
27  	 *            Configuration for this map.
28  	 * @param deps
29  	 *            Run-time dependencies for the maps.
30  	 * @return
31  	 */
32  	public static final <V> AsyncMap<String, V> createMap(
33  			SqlAsyncMapConfiguration conf, SqlAsyncMapDependencies deps) {
34  		return new SqlAsyncMapImplementation<V>(conf, deps);
35  	}
36  
37  	public static final SqlAsyncMapConfiguration fromSqlConfiguration(
38  			final SqlConnectionConfiguration sqlConf) {
39  		return new SqlAsyncMapConfiguration() {
40  
41  			@Override
42  			public SqlConnectionConfiguration sql() {
43  				return sqlConf;
44  			}
45  		};
46  	}
47  
48  	public static final void assertTable(SqlConnectionConfiguration sqlConf) {
49  		Connection connection = SqlConnectionFactory.createConnection(sqlConf);
50  
51  		try {
52  			CallableStatement statement = connection
53  					.prepareCall("CREATE TABLE IF NOT EXISTS "
54  							+ sqlConf.getTableName()
55  							+ "(ID VARCHAR(512) PRIMARY KEY, VALUE BLOB);");
56  
57  			statement.execute();
58  
59  			/*
60  			 * Don't close the connection for H2 in memory databases. Closing
61  			 * the connection would wipe the created table.
62  			 */
63  			if (!sqlConf.getConnectionString().contains(":mem:")) {
64  				connection.close();
65  			}
66  
67  		} catch (SQLException e) {
68  			throw new RuntimeException(e);
69  		}
70  	}
71  
72  }