01: /*
02: * Copyright Aduna (http://www.aduna-software.com/) (c) 2008.
03: *
04: * Licensed under the Aduna BSD-style license.
05: */
06: package org.openrdf.sail.rdbms.postgresql;
07:
08: import java.sql.PreparedStatement;
09: import java.sql.SQLException;
10: import java.sql.Types;
11:
12: import org.openrdf.sail.rdbms.schema.RdbmsTable;
13: import org.openrdf.sail.rdbms.schema.ValueTable;
14:
15: /**
16: * Optimises prepared insert statements for PostgreSQL and overrides the DOUBLE
17: * column type.
18: *
19: * @author James Leigh
20: *
21: */
22: public class PgSqlValueTable extends ValueTable {
23:
24: @Override
25: public void initialize() throws SQLException {
26: super .initialize();
27:
28: RdbmsTable tmp = getInsertTable();
29: StringBuilder sb = new StringBuilder();
30: sb.append("PREPARE ").append(tmp.getName());
31: sb.append("_insert (").append(sql(getIdType(), -1))
32: .append(", ");
33: sb.append(sql(getSqlType(), getLength()).replaceAll("\\(.*\\)",
34: ""));
35: sb.append(") AS\n");
36: sb.append("INSERT INTO ").append(tmp.getName());
37: sb.append(" VALUES ($1, $2)");
38: tmp.execute(sb.toString());
39:
40: sb.delete(0, sb.length());
41: sb.append("PREPARE ").append(tmp.getName());
42: sb.append("_insert_select AS\n");
43: sb.append("INSERT INTO ").append(getRdbmsTable().getName());
44: sb.append(" (id, value) SELECT DISTINCT id, value FROM ");
45: sb.append(tmp.getName()).append(" tmp\n");
46: sb.append("WHERE NOT EXISTS (SELECT id FROM ").append(
47: getRdbmsTable().getName());
48: sb.append(" val WHERE val.id = tmp.id)");
49: tmp.execute(sb.toString());
50: }
51:
52: @Override
53: public void close() throws SQLException {
54: RdbmsTable tmp = getInsertTable();
55: tmp.execute("DEALLOCATE " + tmp.getName() + "_insert");
56: tmp.execute("DEALLOCATE " + tmp.getName() + "_insert_select");
57: super .close();
58: }
59:
60: @Override
61: public String sql(int type, int length) {
62: switch (type) {
63: case Types.DOUBLE:
64: return "double precision";
65: default:
66: return super .sql(type, length);
67: }
68: }
69:
70: @Override
71: protected PreparedStatement prepareInsert(String sql)
72: throws SQLException {
73: StringBuilder sb = new StringBuilder();
74: sb.append("EXECUTE ").append(getInsertTable().getName());
75: sb.append("_insert(?, ?)");
76: return super .prepareInsert(sb.toString());
77: }
78:
79: @Override
80: protected PreparedStatement prepareInsertSelect(String sql)
81: throws SQLException {
82: StringBuilder sb = new StringBuilder();
83: sb.append("EXECUTE ").append(getInsertTable().getName());
84: sb.append("_insert_select");
85: return super.prepareInsertSelect(sb.toString());
86: }
87:
88: }
|