Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package ru.rudb.java;
 
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
 
public final class DefaultDriver implements Driver
{
    static
    {
        try
        {
            DriverManager.registerDriver(new DefaultDriver());
        }
        catch (SQLException ex)
        {
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    @Override
    public Connection connect(String url, Properties info) throws SQLException
    {
        if (!acceptsURL(url))
            return null;
        return (Connection) proxy(Connection.class, new SqlHandler("connection", null));
    }
 
    @Override
    public boolean acceptsURL(String url)
    {
        return "jdbc:default:connection".equals(url) || "jdbc:default:connection:".equals(url);
    }
 
    @Override
    public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
    {
        return new DriverPropertyInfo[0];
    }
 
    @Override
    public int getMajorVersion()
    {
        return 1;
    }
 
    @Override
    public int getMinorVersion()
    {
        return 0;
    }
 
    @Override
    public boolean jdbcCompliant()
    {
        return false;
    }
 
    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException
    {
        throw new SQLFeatureNotSupportedException("logger");
    }
 
    private static Object proxy(Class<?> type, SqlHandler handler)
    {
        return Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] {type}, handler);
    }
 
    private static final class Grid
    {
        final List<String[]> rows = new ArrayList<String[]>();
        int cursor = -1;
    }
 
    private static final class SqlHandler implements InvocationHandler
    {
        private final String kind;
        private final String sql;
        private final List<String> types = new ArrayList<String>();
        private final List<String> values = new ArrayList<String>();
        private Grid grid;
 
        SqlHandler(String kind, String sql)
        {
            this.kind = kind;
            this.sql = sql;
        }
 
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
        {
            if (method.getDeclaringClass() == Object.class)
                return objectCall(proxy, method, args);
            String name = method.getName();
            if ("createStatement".equals(name) && (args == null || args.length == 0))
                return proxy(Statement.class, new SqlHandler("statement", null));
            if ("prepareStatement".equals(name) && args != null && args.length == 1)
                return proxy(PreparedStatement.class, new SqlHandler("prepared", String.valueOf(args[0])));
            if ("commit".equals(name))
            {
                roundTrip(Daemon.SQL_COMMIT, "");
                return null;
            }
            if ("rollback".equals(name) && (args == null || args.length == 0))
            {
                roundTrip(Daemon.SQL_ROLLBACK, "");
                return null;
            }
            if ("setAutoCommit".equals(name))
                return null;
            if ("getAutoCommit".equals(name))
                return Boolean.FALSE;
            if ("close".equals(name))
            {
                if ("result".equals(kind))
                {
                    try
                    {
                        Daemon.exchangeSql(Daemon.SQL_CLOSE, new byte[0]);
                    }
                    catch (java.io.IOException ex)
                    {
                        throw new SQLException(ex.getMessage(), ex);
                    }
                }
                return null;
            }
            if ("isClosed".equals(name))
                return Boolean.FALSE;
            if ("executeQuery".equals(name))
            {
                String query = sql;
                if (args != null && args.length == 1)
                    query = String.valueOf(args[0]);
                Daemon.SqlReply reply = roundTrip(Daemon.SQL_EXEC, payload(query));
                if (reply.type != Daemon.SQL_ROWS)
                    throw new SQLException("query");
                Grid got = rowsOf(textOf(reply));
                SqlHandler handler = new SqlHandler("result", null);
                handler.grid = got;
                return proxy(ResultSet.class, handler);
            }
            if ("executeUpdate".equals(name))
            {
                String query = sql;
                if (args != null && args.length == 1)
                    query = String.valueOf(args[0]);
                Daemon.SqlReply reply = roundTrip(Daemon.SQL_EXEC, payload(query));
                if (reply.type != Daemon.SQL_DONE)
                    throw new SQLException("update");
                String body = textOf(reply);
                int nl = body.indexOf('\n');
                String head = nl < 0 ? body : body.substring(0, nl);
                return Integer.valueOf(head.trim());
            }
            if ("setInt".equals(name))
            {
                put(intArg(args[0]), "int", String.valueOf(args[1]));
                return null;
            }
            if ("setString".equals(name) && args != null && args.length == 2)
            {
                if (args[1] == null)
                    put(intArg(args[0]), "null", "");
                else
                    put(intArg(args[0]), "string", String.valueOf(args[1]));
                return null;
            }
            if ("next".equals(name))
            {
                if (grid == null)
                    return Boolean.FALSE;
                grid.cursor++;
                return Boolean.valueOf(grid.cursor < grid.rows.size());
            }
            if ("getString".equals(name) && args != null && args.length == 1 && args[0] instanceof Integer)
            {
                int col = ((Integer) args[0]).intValue() - 1;
                String[] row = grid.rows.get(grid.cursor);
                return row[col];
            }
            if ("isWrapperFor".equals(name))
                return Boolean.FALSE;
            throw new SQLFeatureNotSupportedException(kind + "." + name);
        }
 
        private Object objectCall(Object proxy, Method method, Object[] args)
        {
            if ("toString".equals(method.getName()))
                return "jdbc:default:connection:" + kind;
            if ("hashCode".equals(method.getName()))
                return Integer.valueOf(System.identityHashCode(proxy));
            return Boolean.valueOf(proxy == args[0]);
        }
 
        private void put(int index, String type, String value)
        {
            while (types.size() < index)
            {
                types.add("null");
                values.add("");
            }
            types.set(index - 1, type);
            values.set(index - 1, value);
        }
 
        private static int intArg(Object value)
        {
            if (value instanceof Integer)
                return ((Integer) value).intValue();
            return Integer.parseInt(String.valueOf(value));
        }
 
        private String payload(String query)
        {
            StringBuilder body = new StringBuilder();
            body.append(types.size()).append('\n');
            for (int i = 0; i < types.size(); i++)
            {
                body.append(types.get(i)).append('\n');
                body.append(values.get(i)).append('\n');
            }
            body.append(query);
            return body.toString();
        }
 
        private static Daemon.SqlReply roundTrip(int type, String payload) throws SQLException
        {
            Daemon.SqlReply reply;
            try
            {
                reply = Daemon.exchangeSql(type, payload.getBytes(java.nio.charset.StandardCharsets.UTF_8));
            }
            catch (java.io.IOException ex)
            {
                throw new SQLException(ex.getMessage(), ex);
            }
            if (reply.type == Daemon.SQL_ERROR)
                throw new SQLException(textOf(reply));
            return reply;
        }
 
        private static String textOf(Daemon.SqlReply reply)
        {
            return new String(reply.body, java.nio.charset.StandardCharsets.UTF_8);
        }
 
        private static Grid rowsOf(String text) throws SQLException
        {
            String[] lines = text.split("\n", -1);
            int at = 0;
            if (at >= lines.length)
                throw new SQLException("rows");
            int cols = Integer.parseInt(lines[at++]);
            at += cols;
            if (at >= lines.length)
                throw new SQLException("rows");
            int nrows = Integer.parseInt(lines[at++]);
            Grid grid = new Grid();
            for (int r = 0; r < nrows; r++)
            {
                String[] row = new String[cols];
                for (int c = 0; c < cols; c++)
                {
                    if (at >= lines.length)
                        throw new SQLException("rows");
                    String line = lines[at++];
                    if (line.startsWith("="))
                        row[c] = line.substring(1);
                    else
                        row[c] = null;
                }
                grid.rows.add(row);
            }
            return grid;
        }
    }
}