Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions e2e/src/test/java/com/arcadedb/e2e/JdbcQueriesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,50 @@ void createVertexCypherQuery() throws Exception {
}
}
}

@Test
void createSchemaWithSqlScript() throws SQLException {
try (final Statement st = conn.createStatement()) {

st.execute("""
{sqlscript}
CREATE Document TYPE article IF NOT EXISTS;
CREATE PROPERTY article.created IF NOT EXISTS DATETIME;
CREATE PROPERTY article.updated IF NOT EXISTS DATETIME;
CREATE PROPERTY article.title IF NOT EXISTS STRING;
CREATE PROPERTY article.content IF NOT EXISTS STRING;
CREATE PROPERTY article.author IF NOT EXISTS STRING;
CREATE PROPERTY article.notes IF NOT EXISTS EMBEDDED;

INSERT INTO article CONTENT {"created": "2021-01-01 00:00:00",
"updated": "2021-01-01 00:00:00",
"title": "My first article",
"content": "This is the content of my first article",
"author": "John Doe"};
INSERT INTO article CONTENT {"created": "2021-01-02 00:00:00",
"updated": "2021-01-02 00:00:00",
"title": "My second article",
"content": "This is the content of my second article",
"author": "John Doe"};
INSERT INTO article CONTENT {"created": "2021-01-03 00:00:00",
"updated": "2021-01-03 00:00:00",
"title": "My third article",
"content": "This is the content of my third article",
"author": "John Doe"};
""");
}

try (final Statement st = conn.createStatement()) {
try (final ResultSet rs = st.executeQuery("SELECT * FROM article")) {
assertThat(rs.next()).isTrue();
assertThat(rs.getString("title")).isEqualTo("My first article");
assertThat(rs.next()).isTrue();
assertThat(rs.getString("title")).isEqualTo("My second article");
assertThat(rs.next()).isTrue();
assertThat(rs.getString("title")).isEqualTo("My third article");
assertThat(rs.next()).isFalse();
}

}
}
}
4 changes: 4 additions & 0 deletions engine/src/main/java/com/arcadedb/database/Binary.java
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,10 @@ public int capacity() {
return content.length;
}

public int limit() {
return buffer.limit();
}

public void fill(final byte filler, final int size) {
checkForAllocation(buffer.position(), size);
for (int i = 0; i < size; ++i)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
Expand Down Expand Up @@ -347,34 +349,34 @@ private void queryCommand() {
return;
}

if (DEBUG)
LogManager.instance().log(this, Level.INFO, "PSQL: query -> %s (thread=%s)", queryText, Thread.currentThread().getId());

final Query query = getLanguageAndQuery(queryText);
if (DEBUG)
LogManager.instance().log(this, Level.INFO, "PSQL: query -> %s ", query);

final ResultSet resultSet;
if (queryText.startsWith("SET ")) {
setConfiguration(queryText);
if (query.query.startsWith("SET ")) {
setConfiguration(query.query);
resultSet = new IteratorResultSet(createResultSet("STATUS", "Setting ignored").iterator());
} else if (queryText.equals("SELECT VERSION()"))
} else if (query.query.equals("SELECT VERSION()"))
resultSet = new IteratorResultSet(createResultSet("VERSION", "11.0.0").iterator());
else if (queryText.equals("SELECT CURRENT_SCHEMA()"))
else if (query.query.equals("SELECT CURRENT_SCHEMA()"))
resultSet = new IteratorResultSet(createResultSet("CURRENT_SCHEMA", database.getName()).iterator());
else if (queryText.equalsIgnoreCase("BEGIN") || queryText.equalsIgnoreCase("BEGIN TRANSACTION")) {
else if (query.query.equalsIgnoreCase("BEGIN") ||
query.query.equalsIgnoreCase("BEGIN TRANSACTION")) {
explicitTransactionStarted = true;
database.begin();
resultSet = new IteratorResultSet(Collections.emptyIterator());
} else if (ignoreQueries.contains(queryText))
} else if (ignoreQueries.contains(query.query))
resultSet = new IteratorResultSet(Collections.emptyIterator());
else
resultSet = database.command(query.language, query.query);

final List<Result> cachedResultset = browseAndCacheResultSet(resultSet, 0);
final List<Result> cachedResultSet = browseAndCacheResultSet(resultSet, 0);

final Map<String, PostgresType> columns = getColumns(cachedResultset);
final Map<String, PostgresType> columns = getColumns(cachedResultSet);
writeRowDescription(columns);
writeDataRows(cachedResultset, columns);
writeCommandComplete(queryText, cachedResultset.size());
writeDataRows(cachedResultSet, columns);
writeCommandComplete(queryText, cachedResultSet.size());

} catch (final CommandParsingException e) {
setErrorInTx();
Expand Down Expand Up @@ -473,74 +475,80 @@ private void writeRowDescription(final Map<String, PostgresType> columns) {
bufferDescription.putByteArray(columnName.getBytes(DatabaseFactory.getDefaultCharset()));//The field name.
bufferDescription.putByte((byte) 0);

bufferDescription.putInt(
0); //If the field can be identified as a column of a specific table, the object ID of the table; otherwise zero.
bufferDescription.putShort(
(short) 0); //If the field can be identified as a column of a specific table, the attribute number of the column; otherwise zero.
bufferDescription.putInt(columnType.code);// The object ID of the field's data type.
bufferDescription.putShort(
(short) columnType.size);// The data type size (see pg_type.typlen). Note that negative values denote variable-width types.
bufferDescription.putInt(
columnType.modifier);// The type modifier (see pg_attribute.atttypmod). The meaning of the modifier is type-specific.
bufferDescription.putShort(
(short) 0); // The format code being used for the field. Currently will be zero (text) or one (binary). In a RowDescription returned from the statement variant of Describe, the format code is not yet known and will always be zero.
//If the field can be identified as a column of a specific table, the object ID of the table; otherwise zero.
bufferDescription.putInt(0);
//If the field can be identified as a column of a specific table, the attribute number of the column; otherwise zero.
bufferDescription.putShort((short) 0);
// The object ID of the field's data type.
bufferDescription.putInt(columnType.code);
// The data type size (see pg_type.typlen). Note that negative values denote variable-width types.
bufferDescription.putShort((short) columnType.size);
// The type modifier (see pg_attribute.atttypmod). The meaning of the modifier is type-specific.
bufferDescription.putInt(-1);
// The format code being used for the field. Currently will be zero (text) or one (binary). In a RowDescription returned from the statement variant of Describe, the format code is not yet known and will always be zero.
bufferDescription.putShort((short) 0);
}

bufferDescription.flip();
writeMessage("row description", () -> {
channel.writeUnsignedShort((short) columns.size());
channel.writeBuffer(bufferDescription.getByteBuffer());
}, 'T', 4 + 2 + bufferDescription.capacity());
}, 'T', 4 + 2 + bufferDescription.limit());
}

private void writeDataRows(final List<Result> resultSet, final Map<String, PostgresType> columns) throws IOException {
if (resultSet.isEmpty())
return;

// final ByteBuffer bufferData = ByteBuffer.allocate(128 * 1024).order(ByteOrder.BIG_ENDIAN);
// final ByteBuffer bufferValues = ByteBuffer.allocate(128 * 1024).order(ByteOrder.BIG_ENDIAN);

final Binary bufferData = new Binary();
final Binary bufferValues = new Binary();

for (final Result row : resultSet) {
bufferData.clear();
bufferValues.clear();
bufferValues.putShort((short) columns.size()); // Int16 The number of column values that follow (possibly zero).

for (final Map.Entry<String, PostgresType> entry : columns.entrySet()) {
final String propertyName = entry.getKey();

Object value = null;
if (propertyName.equals("@rid"))
value = row.isElement() ? row.getElement().get().getIdentity() : null;
else if (propertyName.equals("@type"))
value = row.isElement() ? row.getElement().get().getTypeName() : null;
else if (propertyName.equals("@out")) {
if (row.isElement()) {
final Document record = row.getElement().get();
if (record instanceof Vertex vertex)
value = vertex.countEdges(Vertex.DIRECTION.OUT, null);
else if (record instanceof Edge edge)
value = edge.getOut();
Object value = switch (propertyName) {
case "@rid" -> row.isElement() ? row.getElement().get().getIdentity() : null;
case "@type" -> row.isElement() ? row.getElement().get().getTypeName() : null;
case "@out" -> {
if (row.isElement()) {
final Document record = row.getElement().get();
if (record instanceof Vertex vertex)
yield vertex.countEdges(Vertex.DIRECTION.OUT, null);
else if (record instanceof Edge edge)
yield edge.getOut();
}
yield null;
}
} else if (propertyName.equals("@in")) {
if (row.isElement()) {
final Document record = row.getElement().get();
if (record instanceof Vertex vertex)
value = vertex.countEdges(Vertex.DIRECTION.IN, null);
else if (record instanceof Edge edge)
value = edge.getIn();
case "@in" -> {
if (row.isElement()) {
final Document record = row.getElement().get();
if (record instanceof Vertex vertex)
yield vertex.countEdges(Vertex.DIRECTION.IN, null);
else if (record instanceof Edge edge)
yield edge.getIn();
}
yield null;
}
} else if (propertyName.equals("@cat")) {
if (row.isElement()) {
final Document record = row.getElement().get();
if (record instanceof Vertex)
value = "v";
else if (record instanceof Edge)
value = "e";
else
value = "d";
case "@cat" -> {
if (row.isElement()) {
final Document record = row.getElement().get();
if (record instanceof Vertex)
yield "v";
else if (record instanceof Edge)
yield "e";
else
yield "d";
}
yield null;
}
} else
value = row.getProperty(propertyName);
default -> row.getProperty(propertyName);
};

entry.getValue().serializeAsText(entry.getValue().code, bufferValues, value);
}
Expand All @@ -552,13 +560,17 @@ else if (record instanceof Edge)

bufferData.flip();
channel.writeBuffer(bufferData.getByteBuffer());
// channel.flush();

bufferData.clear();
bufferValues.clear();
}

channel.flush();

if (DEBUG)
LogManager.instance().log(this, Level.INFO, "PSQL:-> %d row data (%s) (thread=%s)", resultSet.size(),
FileUtils.getSizeAsString(bufferData.getByteBuffer().limit()), Thread.currentThread().getId());
FileUtils.getSizeAsString(bufferData.limit()), Thread.currentThread().getId());
}

private void bindCommand() {
Expand Down Expand Up @@ -1120,20 +1132,25 @@ private void readBytes(final int len) throws IOException {

private void writeCommandComplete(final String queryText, final int resultSetCount) {
final String upperCaseText = queryText.toUpperCase(Locale.ENGLISH);
String tag = "";
if (upperCaseText.startsWith("CREATE VERTEX") || upperCaseText.startsWith("INSERT INTO"))
tag = "INSERT 0 " + resultSetCount;
else if (upperCaseText.startsWith("SELECT") || upperCaseText.startsWith("MATCH"))
tag = "SELECT " + resultSetCount;
else if (upperCaseText.startsWith("UPDATE"))
tag = "UPDATE " + resultSetCount;
else if (upperCaseText.startsWith("DELETE"))
tag = "DELETE " + resultSetCount;
else if (upperCaseText.equals("BEGIN") || upperCaseText.equals("BEGIN TRANSACTION"))
tag = "BEGIN";

final String finalTag = tag;
writeMessage("command complete", () -> writeString(finalTag), 'C', 4 + tag.length() + 1);
final String tag = getTag(upperCaseText, resultSetCount);
writeMessage("command complete",
() -> writeString(tag), 'C', 4 + tag.length() + 1);
}

private String getTag(String upperCaseText, int resultSetCount) {
if (upperCaseText.startsWith("CREATE VERTEX") || upperCaseText.startsWith("INSERT INTO")) {
return "INSERT 0 " + resultSetCount;
} else if (upperCaseText.startsWith("SELECT") || upperCaseText.startsWith("MATCH")) {
return "SELECT " + resultSetCount;
} else if (upperCaseText.startsWith("UPDATE")) {
return "UPDATE " + resultSetCount;
} else if (upperCaseText.startsWith("DELETE")) {
return "DELETE " + resultSetCount;
} else if (upperCaseText.equals("BEGIN") || upperCaseText.equals("BEGIN TRANSACTION")) {
return "BEGIN";
} else {
return "";
}
}

private void writeNoData() {
Expand All @@ -1155,7 +1172,7 @@ private void createResultSet(final PostgresPortal portal, final Object... elemen

private List<Result> createResultSet(final Object... elements) {
if (elements.length % 2 != 0)
throw new IllegalArgumentException("Resultset elements must be in pairs");
throw new IllegalArgumentException("Result set elements must be in pairs");

final List<Result> resultSet = new ArrayList<>();
for (int i = 0; i < elements.length; i += 2) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,14 @@
import com.arcadedb.server.ServerException;
import com.arcadedb.server.ha.network.ServerSocketFactory;

import java.io.*;
import java.net.*;
import java.util.logging.*;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;

public class PostgresNetworkListener extends Thread {
private final ArcadeDBServer server;
Expand All @@ -39,7 +44,8 @@ public interface ClientConnected {
void connected();
}

public PostgresNetworkListener(final ArcadeDBServer server, final ServerSocketFactory iSocketFactory, final String hostName, final String hostPortRange) {
public PostgresNetworkListener(final ArcadeDBServer server, final ServerSocketFactory iSocketFactory, final String hostName,
final String hostPortRange) {
super(server.getServerName() + " PostgresW listening at " + hostName + ":" + hostPortRange);

this.server = server;
Expand Down Expand Up @@ -108,7 +114,8 @@ private void listen(final String hostName, final String hostPortRange) {

if (serverSocket.isBound()) {
LogManager.instance().log(this, Level.INFO,
"Listening for incoming connections on $ANSI{green " + inboundAddr.getAddress().getHostAddress() + ":" + inboundAddr.getPort() + "} (protocol v."
"Listening for incoming connections on $ANSI{green " + inboundAddr.getAddress().getHostAddress() + ":"
+ inboundAddr.getPort() + "} (protocol v."
+ protocolVersion + ")");

return;
Expand All @@ -124,9 +131,12 @@ private void listen(final String hostName, final String hostPortRange) {
}
}

LogManager.instance().log(this, Level.SEVERE, "Unable to listen for connections using the configured ports '%s' on host '%s'", hostPortRange, hostName);
LogManager.instance()
.log(this, Level.SEVERE, "Unable to listen for connections using the configured ports '%s' on host '%s'", hostPortRange,
hostName);

throw new ServerException("Unable to listen for connections using the configured ports '" + hostPortRange + "' on host '" + hostName + "'");
throw new ServerException(
"Unable to listen for connections using the configured ports '" + hostPortRange + "' on host '" + hostName + "'");
}

private static int[] getPorts(final String iHostPortRange) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import com.arcadedb.query.sql.executor.Result;
import com.arcadedb.query.sql.parser.Statement;

import java.util.*;
import java.util.List;
import java.util.Map;

public class PostgresPortal {
public String query;
Expand All @@ -30,16 +31,15 @@ public class PostgresPortal {
public List<Object> parameterValues;
public List<Integer> resultFormats;
public Statement sqlStatement;
public boolean ignoreExecution = false;
public boolean ignoreExecution = false;
public List<Result> cachedResultset;
public Map<String, PostgresType> columns;
public boolean isExpectingResult = true;
public boolean executed = false;
public boolean isExpectingResult;
public boolean executed = false;

public PostgresPortal(final String query) {
this.query = query;
//final String queryUpperCase = query.toUpperCase();
this.isExpectingResult = true;//queryUpperCase.startsWith("SELECT") || queryUpperCase.startsWith("MATCH");
this.isExpectingResult = true;
}

@Override
Expand Down
Loading