Skip to content

Commit abd6c3a

Browse files
authored
Docs: a how-to page on the SQL differences for people who know other SQL (#491)
Code written from the quickstart fails on statements that other SQL dialects accept and ArcadeDB refuses (DELETE EDGE, DELETE VERTEX <type>, lower()), on a list passed as the only parameter, and on schema statements for things that exist. One page states each with a runnable example, linked from the nav and the quickstart. tests/test_docs_sql_for_sql_users_page.py runs every block on both packages and pins the refused statements. Closes #490
1 parent fa487fb commit abd6c3a

4 files changed

Lines changed: 219 additions & 0 deletions

File tree

‎docs/modules/ROOT/nav.adoc‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* xref:quickstart.adoc[Quickstart]
66
* How-to
77
** xref:how-to/databases-and-queries.adoc[Databases and queries]
8+
** xref:how-to/sql-for-sql-users.adoc[ArcadeDB SQL for people who know other SQL]
89
** xref:how-to/transactions.adoc[Transactions]
910
** xref:how-to/errors.adoc[Errors: codes, hints and classes]
1011
** xref:how-to/values-and-records.adoc[Values and records]
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
= ArcadeDB SQL for people who know other SQL
2+
:description: The differences from other SQL dialects that matter for everyday writes, deletes and queries.
3+
4+
// Pinned by tests/test_docs_sql_for_sql_users_page.py, which runs every block on both packages.
5+
6+
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`).
7+
8+
[source,python]
9+
----
10+
import arcadedb
11+
12+
db = arcadedb.open_or_create_database("./sqlpage")
13+
db.command("sql", "CREATE VERTEX TYPE Author IF NOT EXISTS")
14+
db.command("sql", "CREATE VERTEX TYPE Book IF NOT EXISTS")
15+
db.command("sql", "CREATE EDGE TYPE Wrote IF NOT EXISTS")
16+
for name in ["Ann", "Ben", "Cat"]:
17+
db.command("sql", "CREATE VERTEX Author SET name = ?", name)
18+
for title in ["Emma", "Solaris"]:
19+
db.command("sql", "CREATE VERTEX Book SET title = ?", title)
20+
for name, title in [("Ann", "Emma"), ("Ann", "Solaris"), ("Ben", "Solaris"), ("Cat", "Emma")]:
21+
db.command(
22+
"sql",
23+
"CREATE EDGE Wrote FROM (SELECT FROM Author WHERE name = ?) TO (SELECT FROM Book WHERE title = ?)",
24+
name,
25+
title,
26+
)
27+
28+
29+
def count(type_name):
30+
return db.query("sql", f"SELECT count(*) AS n FROM {type_name}").first().get("n")
31+
----
32+
33+
== Create only what is missing
34+
35+
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`:
36+
37+
[source,python]
38+
----
39+
for _ in range(2):
40+
db.command("sql", "CREATE PROPERTY Author.name IF NOT EXISTS STRING")
41+
db.command("sql", "CREATE INDEX IF NOT EXISTS ON Author (name) NOTUNIQUE")
42+
----
43+
44+
== Delete with DELETE FROM
45+
46+
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:
47+
48+
[source,python]
49+
----
50+
print(count("Author"), count("Wrote"))
51+
db.command("sql", "DELETE FROM Author WHERE name = ?", "Cat")
52+
print(count("Author"), count("Wrote"))
53+
----
54+
55+
[source,text]
56+
----
57+
3 4
58+
2 3
59+
----
60+
61+
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:
62+
63+
[source,python]
64+
----
65+
db.command("sql", "DELETE FROM Wrote WHERE out.name = ? AND in.title = ?", "Ann", "Solaris")
66+
print(count("Author"), count("Wrote"))
67+
----
68+
69+
[source,text]
70+
----
71+
2 2
72+
----
73+
74+
Every record has a record id such as `#1:0`, which `get_rid()` returns and `@rid` matches:
75+
76+
[source,python]
77+
----
78+
rid = db.query("sql", "SELECT FROM Author WHERE name = ?", "Ben").first().get_rid()
79+
db.command("sql", "DELETE FROM Author WHERE @rid = ?", rid)
80+
print(count("Author"), count("Wrote"))
81+
----
82+
83+
[source,text]
84+
----
85+
1 1
86+
----
87+
88+
== Call methods on values
89+
90+
There is no `lower()` or `upper()` function. Call the method on the value:
91+
92+
[source,python]
93+
----
94+
print(db.query("sql", "SELECT name.toUpperCase() AS shout FROM Author WHERE name.toLowerCase() = ?", "ann").to_list())
95+
----
96+
97+
[source,text]
98+
----
99+
[{'shout': 'ANN'}]
100+
----
101+
102+
== Pass a list as one parameter
103+
104+
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:
105+
106+
[source,python]
107+
----
108+
titles = ["Emma", "Solaris"]
109+
print(db.query("sql", "SELECT title FROM Book WHERE title IN :titles ORDER BY title", {"titles": titles}).to_list())
110+
print(db.query("sql", "SELECT title FROM Book WHERE title IN ? ORDER BY title", [titles]).to_list())
111+
db.close()
112+
----
113+
114+
[source,text]
115+
----
116+
[{'title': 'Emma'}, {'title': 'Solaris'}]
117+
[{'title': 'Emma'}, {'title': 'Solaris'}]
118+
----

‎docs/modules/ROOT/pages/quickstart.adoc‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ In the `{jvm-pkg-name}` wheels from 26.11.1 the server also serves the Studio we
199199
== Next steps
200200

201201
* xref:how-to/databases-and-queries.adoc[Databases and queries]: open, drop and check databases, parameters, pagination, SQLScript and openCypher.
202+
* 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.
202203
* 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.
203204
* xref:how-to/import-export.adoc[Importing and exporting data]: load a file, export a database or a query.
204205
* xref:how-to/dataframes-and-columns.adoc[DataFrames, Arrow and columns]: load and read pandas, Polars, Arrow and numpy data.
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
"""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.
2+
3+
Same pattern as ``test_docs_transactions_page.py``: the blocks are chained on purpose, they run in the order of the page, in one
4+
namespace. The page opens its own database under the current directory, so the run happens in a temporary directory. A block that is
5+
followed by a ``[source,text]`` block must print exactly that text. The statements that the page says are refused are pinned below.
6+
The tests use no Java object, so they run on the JVM build and the native build alike.
7+
"""
8+
9+
import contextlib
10+
import io
11+
import re
12+
from pathlib import Path
13+
14+
import pytest
15+
16+
from arcadedb import ArcadeDBError
17+
18+
PAGE = (
19+
Path(__file__).resolve().parents[1]
20+
/ "docs"
21+
/ "modules"
22+
/ "ROOT"
23+
/ "pages"
24+
/ "how-to"
25+
/ "sql-for-sql-users.adoc"
26+
)
27+
28+
# a Python listing, then (optionally, directly after it) the text listing with its output
29+
BLOCK_RE = re.compile(
30+
r"\[source,python[^\]\n]*\]\n----\n(?P<code>.*?)\n----\n"
31+
r"(?:\n\[source,text\]\n----\n(?P<out>.*?)\n----\n)?",
32+
re.DOTALL,
33+
)
34+
35+
36+
def _blocks():
37+
text = PAGE.read_text(encoding="utf-8")
38+
found = [(m.group("code"), m.group("out")) for m in BLOCK_RE.finditer(text)]
39+
# no Python listing may escape the extraction (a different spelling of the block header would run nowhere)
40+
assert text.count("[source,python") == len(found)
41+
return found
42+
43+
44+
def test_the_page_has_its_blocks():
45+
blocks = _blocks()
46+
assert len(blocks) >= 7
47+
assert sum(1 for _, out in blocks if out is not None) >= 5
48+
49+
50+
def test_every_block_runs_in_order_and_prints_what_the_page_says(tmp_path, monkeypatch):
51+
monkeypatch.chdir(tmp_path) # the page opens ./sqlpage
52+
namespace = {"__name__": "sql_for_sql_users_page"}
53+
for number, (code, expected) in enumerate(_blocks(), start=1):
54+
captured = io.StringIO()
55+
compiled = compile(
56+
code, f"sql-for-sql-users.adoc python block {number}", "exec"
57+
)
58+
with contextlib.redirect_stdout(captured):
59+
exec(compiled, namespace) # nosec B102 - the page of this repository
60+
if expected is not None:
61+
assert (
62+
captured.getvalue().strip() == expected.strip()
63+
), f"block {number} printed other text than the page shows:\n{code}"
64+
else:
65+
assert (
66+
captured.getvalue() == ""
67+
), f"block {number} prints, the page shows no output"
68+
69+
70+
def _schema(db):
71+
db.command("sql", "CREATE VERTEX TYPE Author")
72+
db.command("sql", "CREATE VERTEX TYPE Book")
73+
db.command("sql", "CREATE EDGE TYPE Wrote")
74+
75+
76+
@pytest.mark.parametrize(
77+
"statement",
78+
[
79+
"DELETE EDGE Wrote FROM (SELECT FROM Author) TO (SELECT FROM Book)",
80+
"DELETE VERTEX Author WHERE name = 'Ann'",
81+
"SELECT FROM Author WHERE lower(name) = 'ann'",
82+
"SELECT FROM Author WHERE upper(name) = 'ANN'",
83+
"CREATE VERTEX TYPE Author",
84+
],
85+
)
86+
def test_the_statements_the_page_calls_refused_are_refused(temp_db, statement):
87+
_schema(temp_db)
88+
temp_db.command("sql", "CREATE VERTEX Author SET name = 'Ann'")
89+
with pytest.raises(ArcadeDBError):
90+
if statement.startswith("SELECT"):
91+
temp_db.query("sql", statement).to_list()
92+
else:
93+
temp_db.command("sql", statement)
94+
95+
96+
def test_a_list_alone_is_read_as_the_positional_parameters(temp_db):
97+
_schema(temp_db)
98+
with pytest.raises(TypeError):
99+
temp_db.query("sql", "SELECT FROM Book WHERE title IN ?", ["Emma", "Solaris"])

0 commit comments

Comments
 (0)