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
1 change: 1 addition & 0 deletions docs/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* xref:quickstart.adoc[Quickstart]
* How-to
** xref:how-to/databases-and-queries.adoc[Databases and queries]
** xref:how-to/sql-for-sql-users.adoc[ArcadeDB SQL for people who know other SQL]
** xref:how-to/transactions.adoc[Transactions]
** xref:how-to/errors.adoc[Errors: codes, hints and classes]
** xref:how-to/values-and-records.adoc[Values and records]
Expand Down
118 changes: 118 additions & 0 deletions docs/modules/ROOT/pages/how-to/sql-for-sql-users.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
= ArcadeDB SQL for people who know other SQL
:description: The differences from other SQL dialects that matter for everyday writes, deletes and queries.

// Pinned by tests/test_docs_sql_for_sql_users_page.py, which runs every block on both packages.

ArcadeDB SQL looks like the SQL you know, with the differences below. The blocks run one after the other against one new database, and each block that prints is followed by its output. A test in the repository runs them that way (`tests/test_docs_sql_for_sql_users_page.py`).

[source,python]
----
import arcadedb

db = arcadedb.open_or_create_database("./sqlpage")
db.command("sql", "CREATE VERTEX TYPE Author IF NOT EXISTS")
db.command("sql", "CREATE VERTEX TYPE Book IF NOT EXISTS")
db.command("sql", "CREATE EDGE TYPE Wrote IF NOT EXISTS")
for name in ["Ann", "Ben", "Cat"]:
db.command("sql", "CREATE VERTEX Author SET name = ?", name)
for title in ["Emma", "Solaris"]:
db.command("sql", "CREATE VERTEX Book SET title = ?", title)
for name, title in [("Ann", "Emma"), ("Ann", "Solaris"), ("Ben", "Solaris"), ("Cat", "Emma")]:
db.command(
"sql",
"CREATE EDGE Wrote FROM (SELECT FROM Author WHERE name = ?) TO (SELECT FROM Book WHERE title = ?)",
name,
title,
)


def count(type_name):
return db.query("sql", f"SELECT count(*) AS n FROM {type_name}").first().get("n")
----

== Create only what is missing

Creating a type, property or index that exists raises. Add `IF NOT EXISTS` to schema statements that may run again, as above for types. For a property it goes after the name, for an index after `INDEX`:

[source,python]
----
for _ in range(2):
db.command("sql", "CREATE PROPERTY Author.name IF NOT EXISTS STRING")
db.command("sql", "CREATE INDEX IF NOT EXISTS ON Author (name) NOTUNIQUE")
----

== Delete with DELETE FROM

Vertices, edges and documents are all deleted with `DELETE FROM <type>`. The parser refuses `DELETE EDGE ...` and `DELETE VERTEX <type> ...`. Deleting a vertex also deletes its edges:

[source,python]
----
print(count("Author"), count("Wrote"))
db.command("sql", "DELETE FROM Author WHERE name = ?", "Cat")
print(count("Author"), count("Wrote"))
----

[source,text]
----
3 4
2 3
----

To delete a link and keep both vertices, delete from the edge type itself. `out` is the vertex where the edge starts and `in` the vertex it points to:

[source,python]
----
db.command("sql", "DELETE FROM Wrote WHERE out.name = ? AND in.title = ?", "Ann", "Solaris")
print(count("Author"), count("Wrote"))
----

[source,text]
----
2 2
----

Every record has a record id such as `#1:0`, which `get_rid()` returns and `@rid` matches:

[source,python]
----
rid = db.query("sql", "SELECT FROM Author WHERE name = ?", "Ben").first().get_rid()
db.command("sql", "DELETE FROM Author WHERE @rid = ?", rid)
print(count("Author"), count("Wrote"))
----

[source,text]
----
1 1
----

== Call methods on values

There is no `lower()` or `upper()` function. Call the method on the value:

[source,python]
----
print(db.query("sql", "SELECT name.toUpperCase() AS shout FROM Author WHERE name.toLowerCase() = ?", "ann").to_list())
----

[source,text]
----
[{'shout': 'ANN'}]
----

== Pass a list as one parameter

A list that is the only argument is read as the list of positional parameters. To compare with a list, give the parameter a name, or wrap the list in another list:

[source,python]
----
titles = ["Emma", "Solaris"]
print(db.query("sql", "SELECT title FROM Book WHERE title IN :titles ORDER BY title", {"titles": titles}).to_list())
print(db.query("sql", "SELECT title FROM Book WHERE title IN ? ORDER BY title", [titles]).to_list())
db.close()
----

[source,text]
----
[{'title': 'Emma'}, {'title': 'Solaris'}]
[{'title': 'Emma'}, {'title': 'Solaris'}]
----
1 change: 1 addition & 0 deletions docs/modules/ROOT/pages/quickstart.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ In the `{jvm-pkg-name}` wheels from 26.11.1 the server also serves the Studio we
== Next steps

* xref:how-to/databases-and-queries.adoc[Databases and queries]: open, drop and check databases, parameters, pagination, SQLScript and openCypher.
* xref:how-to/sql-for-sql-users.adoc[ArcadeDB SQL for people who know other SQL]: delete records and links, create only what is missing, call methods on values, and pass a list as one parameter.
* xref:how-to/values-and-records.adoc[Values and records]: which Python types go in and what comes back, datetimes, record objects and the `Schema` API.
* xref:how-to/import-export.adoc[Importing and exporting data]: load a file, export a database or a query.
* xref:how-to/dataframes-and-columns.adoc[DataFrames, Arrow and columns]: load and read pandas, Polars, Arrow and numpy data.
Expand Down
99 changes: 99 additions & 0 deletions tests/test_docs_sql_for_sql_users_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Every Python block of the Antora page ``docs/modules/ROOT/pages/how-to/sql-for-sql-users.adoc`` runs, and prints what the page says.

Same pattern as ``test_docs_transactions_page.py``: the blocks are chained on purpose, they run in the order of the page, in one
namespace. The page opens its own database under the current directory, so the run happens in a temporary directory. A block that is
followed by a ``[source,text]`` block must print exactly that text. The statements that the page says are refused are pinned below.
The tests use no Java object, so they run on the JVM build and the native build alike.
"""

import contextlib
import io
import re
from pathlib import Path

import pytest

from arcadedb import ArcadeDBError

PAGE = (
Path(__file__).resolve().parents[1]
/ "docs"
/ "modules"
/ "ROOT"
/ "pages"
/ "how-to"
/ "sql-for-sql-users.adoc"
)

# a Python listing, then (optionally, directly after it) the text listing with its output
BLOCK_RE = re.compile(
r"\[source,python[^\]\n]*\]\n----\n(?P<code>.*?)\n----\n"
r"(?:\n\[source,text\]\n----\n(?P<out>.*?)\n----\n)?",
re.DOTALL,
)


def _blocks():
text = PAGE.read_text(encoding="utf-8")
found = [(m.group("code"), m.group("out")) for m in BLOCK_RE.finditer(text)]
# no Python listing may escape the extraction (a different spelling of the block header would run nowhere)
assert text.count("[source,python") == len(found)
return found


def test_the_page_has_its_blocks():
blocks = _blocks()
assert len(blocks) >= 7
assert sum(1 for _, out in blocks if out is not None) >= 5


def test_every_block_runs_in_order_and_prints_what_the_page_says(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path) # the page opens ./sqlpage
namespace = {"__name__": "sql_for_sql_users_page"}
for number, (code, expected) in enumerate(_blocks(), start=1):
captured = io.StringIO()
compiled = compile(
code, f"sql-for-sql-users.adoc python block {number}", "exec"
)
with contextlib.redirect_stdout(captured):
exec(compiled, namespace) # nosec B102 - the page of this repository
if expected is not None:
assert (
captured.getvalue().strip() == expected.strip()
), f"block {number} printed other text than the page shows:\n{code}"
else:
assert (
captured.getvalue() == ""
), f"block {number} prints, the page shows no output"


def _schema(db):
db.command("sql", "CREATE VERTEX TYPE Author")
db.command("sql", "CREATE VERTEX TYPE Book")
db.command("sql", "CREATE EDGE TYPE Wrote")


@pytest.mark.parametrize(
"statement",
[
"DELETE EDGE Wrote FROM (SELECT FROM Author) TO (SELECT FROM Book)",
"DELETE VERTEX Author WHERE name = 'Ann'",
"SELECT FROM Author WHERE lower(name) = 'ann'",
"SELECT FROM Author WHERE upper(name) = 'ANN'",
"CREATE VERTEX TYPE Author",
],
)
def test_the_statements_the_page_calls_refused_are_refused(temp_db, statement):
_schema(temp_db)
temp_db.command("sql", "CREATE VERTEX Author SET name = 'Ann'")
with pytest.raises(ArcadeDBError):
if statement.startswith("SELECT"):
temp_db.query("sql", statement).to_list()
else:
temp_db.command("sql", statement)


def test_a_list_alone_is_read_as_the_positional_parameters(temp_db):
_schema(temp_db)
with pytest.raises(TypeError):
temp_db.query("sql", "SELECT FROM Book WHERE title IN ?", ["Emma", "Solaris"])
Loading