code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
async def _extension_test_01(self):
await self.con.execute('''
create extension ltree version '1.0'
''')
await self.assert_query_result(
'''
select ext::ltree::nlevel(
<ext::ltree::ltree><json><ext::ltree::ltree>'foo.bar');
''',
[2],
)
await self.assert_query_result(
'''
select ext::ltree::asdf(
<ext::ltree::ltree><json><ext::ltree::ltree>'foo.bar');
''',
[3],
)
await self.assert_query_result(
'''
select <str>(
<ext::ltree::ltree><json><ext::ltree::ltree>'foo.bar');
''',
['foo.bar'],
)
await self.assert_query_result(
'''
select <ext::ltree::ltree>'foo.bar'
= <ext::ltree::ltree>'foo.baz';
''',
[False],
)
await self.assert_query_result(
'''
select <ext::ltree::ltree>'foo.bar'
!= <ext::ltree::ltree>'foo.baz';
''',
[True],
)
await self.assert_query_result(
'''
select <ext::ltree::ltree><json><ext::ltree::ltree>'foo.bar';
''',
[['foo', 'bar']],
json_only=True,
)
await self.con.execute('''
create type Foo { create property x -> ext::ltree::ltree };
insert Foo { x := <ext::ltree::ltree>'foo.bar.baz' };
''')
await self.assert_query_result(
'''
select Foo.x;
''',
[['foo', 'bar', 'baz']],
json_only=True,
)
await self.con.execute("""
START MIGRATION TO {
using extension ltree version '2.0';
module default {
type Foo { property x -> ext::ltree::ltree };
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'''
select ext::ltree::hash(<ext::ltree::ltree>'foo.bar');
''',
[-2100566927],
)
await self.con.execute('''
drop type Foo;
drop extension ltree;
''') | )
await self.assert_query_result( | _extension_test_01 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_01(self):
pg_ver = edb.buildmeta.parse_pg_version(await self.con.query_single('''
select sys::_postgres_version();
'''))
# Skip if postgres is old, since it doesn't have ltree 1.3
if pg_ver.major < 17:
self.skipTest('Postgres version too old')
# Make an extension that wraps a tiny bit of the ltree package.
await self.con.execute('''
create extension package ltree VERSION '1.0' {
set ext_module := "ext::ltree";
set sql_extensions := ["ltree >=1.2,<1.3"];
set sql_setup_script := $$
CREATE FUNCTION edgedb.asdf(val edgedb.ltree) RETURNS int4
LANGUAGE sql
STRICT
IMMUTABLE
AS $function$
SELECT edgedb.nlevel(val) + 1
$function$;
$$;
set sql_teardown_script := $$
DROP FUNCTION edgedb.asdf(edgedb.ltree);
$$;
create module ext::ltree;
create scalar type ext::ltree::ltree extending anyscalar {
set sql_type := "ltree";
};
create cast from ext::ltree::ltree to std::str {
SET volatility := 'Immutable';
USING SQL CAST;
};
create cast from std::str to ext::ltree::ltree {
SET volatility := 'Immutable';
USING SQL CAST;
};
# Use a non-trivial json representation just to show that we can.
create cast from ext::ltree::ltree to std::json {
SET volatility := 'Immutable';
USING SQL $$
select to_jsonb(string_to_array("val"::text, '.'));
$$
};
create cast from std::json to ext::ltree::ltree {
SET volatility := 'Immutable';
USING SQL $$
select string_agg(edgedb.raise_on_null(
edgedbstd."std|cast@std|json@std|str_f"(z.z),
'invalid_parameter_value', 'invalid null value in cast'),
'.')::ltree
from unnest(
edgedbstd."std|cast@std|json@array<std||json>_f"("val"))
as z(z);
$$
};
create function ext::ltree::nlevel(
v: ext::ltree::ltree) -> std::int32 {
using sql function 'edgedb.nlevel';
};
create function ext::ltree::asdf(v: ext::ltree::ltree) -> std::int32 {
using sql function 'edgedb.asdf';
};
};
create extension package ltree VERSION '2.0' {
set ext_module := "ext::ltree";
set sql_extensions := ["ltree >=1.3,<10.0"];
set sql_setup_script := $$
CREATE FUNCTION edgedb.asdf(val edgedb.ltree) RETURNS int4
LANGUAGE sql
STRICT
IMMUTABLE
AS $function$
SELECT edgedb.nlevel(val) + 1
$function$;
$$;
set sql_teardown_script := $$
DROP FUNCTION edgedb.asdf(edgedb.ltree);
$$;
create module ext::ltree;
create scalar type ext::ltree::ltree extending anyscalar {
set sql_type := "ltree";
};
create cast from ext::ltree::ltree to std::str {
SET volatility := 'Immutable';
USING SQL CAST;
};
create cast from std::str to ext::ltree::ltree {
SET volatility := 'Immutable';
USING SQL CAST;
};
# Use a non-trivial json representation just to show that we can.
create cast from ext::ltree::ltree to std::json {
SET volatility := 'Immutable';
USING SQL $$
select to_jsonb(string_to_array("val"::text, '.'));
$$
};
create cast from std::json to ext::ltree::ltree {
SET volatility := 'Immutable';
USING SQL $$
select string_agg(edgedb.raise_on_null(
edgedbstd."std|cast@std|json@std|str_f"(z.z),
'invalid_parameter_value', 'invalid null value in cast'),
'.')::ltree
from unnest(
edgedbstd."std|cast@std|json@array<std||json>_f"("val"))
as z(z);
$$
};
create function ext::ltree::nlevel(
v: ext::ltree::ltree) -> std::int32 {
using sql function 'edgedb.nlevel';
};
create function ext::ltree::asdf(v: ext::ltree::ltree) -> std::int32 {
using sql function 'edgedb.asdf';
};
create function ext::ltree::hash(v: ext::ltree::ltree) -> std::int32 {
using sql function 'edgedb.hash_ltree';
};
};
create extension package ltree migration from version '1.0'
to version '2.0' {
create function ext::ltree::hash(v: ext::ltree::ltree) -> std::int32 {
using sql function 'edgedb.hash_ltree';
};
};
''')
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_01()
finally:
await self.con.execute('''
drop extension package ltree VERSION '1.0';
drop extension package ltree VERSION '2.0';
drop extension package ltree migration from
VERSION '1.0' TO VERSION '2.0';
''') | ))
# Skip if postgres is old, since it doesn't have ltree 1.3
if pg_ver.major < 17:
self.skipTest('Postgres version too old')
# Make an extension that wraps a tiny bit of the ltree package.
await self.con.execute( | test_edgeql_extensions_01 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def _extension_test_02a(self):
await self.con.execute('''
create extension varchar
''')
await self.con.execute('''
create scalar type vc5 extending ext::varchar::varchar<5>;
create type X {
create property foo: vc5;
};
''')
await self.assert_query_result(
'''
describe scalar type vc5;
''',
[
'create scalar type default::vc5 '
'extending ext::varchar::varchar<5>;'
],
)
await self.assert_query_result(
'''
describe scalar type vc5 as sdl;
''',
['scalar type default::vc5 extending ext::varchar::varchar<5>;'],
)
await self.assert_query_result(
'''
select schema::ScalarType { arg_values }
filter .name = 'default::vc5'
''',
[{'arg_values': ['5']}],
)
await self.con.execute('''
insert X { foo := <vc5>"0123456789" }
''')
await self.assert_query_result(
'''
select X.foo
''',
['01234'],
json_only=True,
)
async with self.assertRaisesRegexTx(
edgedb.SchemaError,
"parameterized scalar types may not have constraints",
):
await self.con.execute('''
alter scalar type vc5 create constraint expression on (true);
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError,
"invalid scalar type argument",
):
await self.con.execute('''
create scalar type fail extending ext::varchar::varchar<foo>;
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError,
"does not accept parameters",
):
await self.con.execute('''
create scalar type yyy extending str<1, 2>;
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError,
"incorrect number of arguments",
):
await self.con.execute('''
create scalar type yyy extending ext::varchar::varchar<1, 2>;
''')
# If no params are specified, it just makes a normal scalar type
await self.con.execute('''
create scalar type vc extending ext::varchar::varchar {
create constraint expression on (false);
};
''')
async with self.assertRaisesRegexTx(
edgedb.ConstraintViolationError,
"invalid",
):
await self.con.execute('''
select <str><vc>'a';
''') | )
await self.con.execute( | _extension_test_02a | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def _extension_test_02b(self):
await self.con.execute(r"""
START MIGRATION TO {
using extension varchar version "1.0";
module default {
scalar type vc5 extending ext::varchar::varchar<5>;
type X {
foo: vc5;
};
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.con.execute('''
insert X { foo := <vc5>"0123456789" }
''')
await self.assert_query_result(
'''
select X.foo
''',
['01234'],
json_only=True,
)
# Try dropping everything that uses it but not the extension
async with self._run_and_rollback():
await self.con.execute(r"""
START MIGRATION TO {
using extension varchar version "1.0";
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
# Try dropping everything including the extension
await self.con.execute(r"""
START MIGRATION TO {
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""") | )
await self.con.execute( | _extension_test_02b | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_02(self):
# Make an extension that wraps some of varchar
await self.con.execute('''
create extension package varchar VERSION '1.0' {
set ext_module := "ext::varchar";
set sql_extensions := [];
create module ext::varchar;
create scalar type ext::varchar::varchar {
create annotation std::description := 'why are we doing this';
set id := <uuid>'26dc1396-0196-11ee-a005-ad0eaed0df03';
set sql_type := "varchar";
set sql_type_scheme := "varchar({__arg_0__})";
set num_params := 1;
};
create cast from ext::varchar::varchar to std::str {
SET volatility := 'Immutable';
USING SQL CAST;
};
create cast from std::str to ext::varchar::varchar {
SET volatility := 'Immutable';
USING SQL CAST;
};
# This is meaningless but I need to test having an array in a cast.
create cast from ext::varchar::varchar to array<std::float32> {
SET volatility := 'Immutable';
USING SQL $$
select array[0.0]
$$
};
create abstract index ext::varchar::with_param(
named only lists: int64
) {
set code := ' ((__col__) NULLS FIRST)';
};
create type ext::varchar::ParentTest extending std::BaseObject {
create property foo -> str;
};
create type ext::varchar::ChildTest
extending ext::varchar::ParentTest;
create type ext::varchar::GrandChildTest
extending ext::varchar::ChildTest;
};
''')
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_02a()
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_02b()
finally:
await self.con.execute('''
drop extension package varchar VERSION '1.0'
''') | )
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_02a()
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_02b()
finally:
await self.con.execute( | test_edgeql_extensions_02 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_03(self):
await self.con.execute('''
create extension package ltree_broken VERSION '1.0' {
set ext_module := "ext::ltree";
set sql_extensions := ["ltree >=1000.0"];
create module ltree;
};
''')
try:
async with self.assertRaisesRegexTx(
edgedb.UnsupportedBackendFeatureError,
r"could not find extension satisfying ltree >=1000.0: "
r"only found versions 1\."):
await self.con.execute(r"""
CREATE EXTENSION ltree_broken;
""")
finally:
await self.con.execute('''
drop extension package ltree_broken VERSION '1.0'
''') | )
try:
async with self.assertRaisesRegexTx(
edgedb.UnsupportedBackendFeatureError,
r"could not find extension satisfying ltree >=1000.0: "
r"only found versions 1\."):
await self.con.execute(r | test_edgeql_extensions_03 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_04(self):
await self.con.execute('''
create extension package ltree_broken VERSION '1.0' {
set ext_module := "ext::ltree";
set sql_extensions := ["loltree >=1.0"];
create module ltree;
};
''')
try:
async with self.assertRaisesRegexTx(
edgedb.UnsupportedBackendFeatureError,
r"could not find extension satisfying loltree >=1.0: "
r"extension not found"):
await self.con.execute(r"""
CREATE EXTENSION ltree_broken;
""")
finally:
await self.con.execute('''
drop extension package ltree_broken VERSION '1.0'
''') | )
try:
async with self.assertRaisesRegexTx(
edgedb.UnsupportedBackendFeatureError,
r"could not find extension satisfying loltree >=1.0: "
r"extension not found"):
await self.con.execute(r | test_edgeql_extensions_04 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def _extension_test_05(self, in_tx):
await self.con.execute('''
create extension _conf
''')
# Check that the ids are stable
await self.assert_query_result(
'''
select schema::ObjectType {
id,
properties: { name, id } filter .name = 'value'
} filter .name = 'ext::_conf::Obj'
''',
[
{
"id": "dc7c6ed1-759f-5a70-9bc3-2252b2d3980a",
"properties": [
{
"name": "value",
"id": "0dff1c2f-f51b-59fd-bae9-9d66cb963896",
},
],
},
],
)
Q = '''
select cfg::%s {
conf := assert_single(.extensions[is ext::_conf::Config] {
config_name,
opt_value,
obj: { name, value, fixed },
objs: { name, value, opt_value,
[is ext::_conf::SubObj].extra,
tname := .__type__.name }
order by .name,
})
};
'''
async def _check(_cfg_obj='Config', **kwargs):
q = Q % _cfg_obj
await self.assert_query_result(
q,
[{'conf': kwargs}],
)
await _check(
config_name='',
objs=[],
)
await self.con.execute('''
configure current database set ext::_conf::Config::config_name :=
"test";
''')
await _check(
config_name='test',
opt_value=None,
objs=[],
)
await self.con.execute('''
configure current database set ext::_conf::Config::opt_value :=
"opt!";
''')
await self.con.execute('''
configure current database set ext::_conf::Config::secret :=
"foobaz";
''')
await _check(
config_name='test',
opt_value='opt!',
objs=[],
)
if not in_tx:
with self.assertRaisesRegex(
edgedb.ConfigurationError, "is not allowed"):
await self.con.execute('''
configure instance set ext::_conf::Config::config_name :=
"session!";
''')
await self.con.execute('''
configure session set ext::_conf::Config::config_name :=
"session!";
''')
await _check(
config_name='session!',
objs=[],
)
await self.con.execute('''
configure session reset ext::_conf::Config::config_name;
''')
await _check(
config_name='test',
objs=[],
)
await self.con.execute('''
configure current database insert ext::_conf::Obj {
name := '1',
value := 'foo',
};
''')
await self.con.execute('''
configure current database insert ext::_conf::Obj {
name := '2',
value := 'bar',
opt_value := 'opt.',
};
''')
await self.con.execute('''
configure current database insert ext::_conf::SubObj {
name := '3',
value := 'baz',
extra := 42,
};
''')
async with self.assertRaisesRegexTx(
edgedb.ConfigurationError, "invalid setting value"
):
await self.con.execute('''
configure current database insert ext::_conf::SubObj {
name := '3!',
value := 'asdf_wrong',
extra := 42,
};
''')
# This is fine, constraint on value is delegated
await self.con.execute('''
configure current database insert ext::_conf::SecretObj {
name := '4',
value := 'foo',
secret := '123456',
};
''')
# But this collides
async with self.assertRaisesRegexTx(
edgedb.ConstraintViolationError, "value violate"
):
await self.con.execute('''
configure current database insert ext::_conf::SecretObj {
name := '5',
value := 'foo',
};
''')
await self.con.execute('''
configure current database insert ext::_conf::SecretObj {
name := '5',
value := 'quux',
};
''')
async with self.assertRaisesRegexTx(
edgedb.QueryError, "protected"
):
await self.con.execute('''
configure current database insert ext::_conf::SingleObj {
name := 'single',
value := 'val',
fixed := 'variable??',
};
''')
await self.con.execute('''
configure current database insert ext::_conf::SingleObj {
name := 'single',
value := 'val',
};
''')
async with self.assertRaisesRegexTx(
edgedb.ConstraintViolationError, ""
):
await self.con.execute('''
CONFIGURE CURRENT BRANCH INSERT ext::_conf::SingleObj {
name := 'fail',
value := '',
};
''')
await self.con.execute('''
configure current database set ext::_conf::Config::config_name :=
"ready";
''')
await _check(
config_name='ready',
objs=[
dict(name='1', value='foo', tname='ext::_conf::Obj',
opt_value=None),
dict(name='2', value='bar', tname='ext::_conf::Obj',
opt_value='opt.'),
dict(name='3', value='baz', extra=42,
tname='ext::_conf::SubObj', opt_value=None),
dict(name='4', value='foo',
tname='ext::_conf::SecretObj', opt_value=None),
dict(name='5', value='quux',
tname='ext::_conf::SecretObj', opt_value=None),
],
obj=dict(name='single', value='val', fixed='fixed!'),
)
await self.assert_query_result(
'''
with c := cfg::Config.extensions[is ext::_conf::Config]
select ext::_conf::get_secret(
(select c.objs[is ext::_conf::SecretObj] filter .name = '4'))
''',
['123456'],
)
await self.assert_query_result(
'''
select ext::_conf::get_top_secret()
''',
['foobaz'],
)
await self.assert_query_result(
'''
select ext::_conf::OK
''',
[True],
)
await self.con.execute('''
configure current database set ext::_conf::Config::secret :=
"123456";
''')
await self.assert_query_result(
'''
select ext::_conf::OK
''',
[False],
)
# Make sure secrets are redacted from get_config_json
cfg_json = await self.con.query_single('''
select to_str(cfg::get_config_json());
''')
self.assertNotIn('123456', cfg_json, 'secrets not redacted')
# test not being able to access secrets
async with self.assertRaisesRegexTx(
edgedb.QueryError, "because it is secret"
):
await self.con.execute('''
select cfg::Config {
conf := assert_single(.extensions[is ext::_conf::Config] {
secret
})
};
''')
async with self.assertRaisesRegexTx(
edgedb.QueryError, "because it is secret"
):
await self.con.execute('''
select cfg::Config {
conf := assert_single(
.extensions[is ext::_conf::Config] {
objs: { [is ext::_conf::SecretObj].secret }
})
};
''')
async with self.assertRaisesRegexTx(
edgedb.QueryError, "because it is secret"
):
await self.con.execute('''
select ext::_conf::Config.secret
''')
async with self.assertRaisesRegexTx(
edgedb.QueryError, "because it is secret"
):
await self.con.execute('''
select ext::_conf::SecretObj.secret
''')
async with self.assertRaisesRegexTx(
edgedb.QueryError, "because it is secret"
):
await self.con.execute('''
configure current database reset ext::_conf::SecretObj
filter .secret = '123456'
''')
if not in_tx:
# Load the in-memory config state via a HTTP debug endpoint
# Retry until we see 'ready' is visible
async for tr in self.try_until_succeeds(ignore=AssertionError):
async with tr:
with self.http_con() as http_con:
rdata, _headers, _status = self.http_con_request(
http_con,
prefix="",
path="server-info",
)
data = json.loads(rdata)
if 'databases' not in data:
# multi-tenant instance - use the first tenant
data = next(iter(data['tenants'].values()))
db_data = data['databases'][self.get_database_name()]
config = db_data['config']
assert (
config['ext::_conf::Config::config_name'] == 'ready'
)
self.assertEqual(
sorted(
config['ext::_conf::Config::objs'],
key=lambda x: x['name'],
),
[
{'_tname': 'ext::_conf::Obj',
'name': '1', 'value': 'foo', 'opt_value': None},
{'_tname': 'ext::_conf::Obj',
'name': '2', 'value': 'bar', 'opt_value': 'opt.'},
{'_tname': 'ext::_conf::SubObj',
'name': '3', 'value': 'baz', 'extra': 42,
'duration_config': 'PT10M',
'opt_value': None},
{'_tname': 'ext::_conf::SecretObj',
'name': '4', 'value': 'foo',
'opt_value': None, 'secret': {'redacted': True}},
{'_tname': 'ext::_conf::SecretObj',
'name': '5', 'value': 'quux',
'opt_value': None, 'secret': None},
],
)
self.assertEqual(
config['ext::_conf::Config::obj'],
{'_tname': 'ext::_conf::SingleObj',
'name': 'single', 'value': 'val', 'fixed': 'fixed!'},
)
val = await self.con.query_single('''
describe current branch config
''')
test_expected = textwrap.dedent('''\
CONFIGURE CURRENT BRANCH SET ext::_conf::Config::config_name := \
'ready';
CONFIGURE CURRENT BRANCH INSERT ext::_conf::SingleObj {
name := 'single',
value := 'val',
};
CONFIGURE CURRENT BRANCH INSERT ext::_conf::Obj {
name := '1',
value := 'foo',
};
CONFIGURE CURRENT BRANCH INSERT ext::_conf::Obj {
name := '2',
opt_value := 'opt.',
value := 'bar',
};
CONFIGURE CURRENT BRANCH INSERT ext::_conf::SecretObj {
name := '4',
secret := {}, # REDACTED
value := 'foo',
};
CONFIGURE CURRENT BRANCH INSERT ext::_conf::SecretObj {
name := '5',
secret := {}, # REDACTED
value := 'quux',
};
CONFIGURE CURRENT BRANCH INSERT ext::_conf::SubObj {
duration_config := <std::duration>'PT10M',
extra := 42,
name := '3',
value := 'baz',
};
CONFIGURE CURRENT BRANCH SET ext::_conf::Config::opt_value := 'opt!';
CONFIGURE CURRENT BRANCH SET ext::_conf::Config::secret := \
{}; # REDACTED
''')
self.assertEqual(val, test_expected)
await self.con.execute('''
configure current database reset ext::_conf::Obj
filter .value like 'ba%'
''')
await self.con.execute('''
configure current database reset ext::_conf::SecretObj
''')
await _check(
config_name='ready',
objs=[
dict(name='1', value='foo'),
],
)
await self.con.execute('''
configure current database reset ext::_conf::Obj
''')
await self.con.execute('''
configure current database reset ext::_conf::Config::opt_value;
''')
await _check(
config_name='ready',
opt_value=None,
objs=[],
obj=dict(name='single', value='val'),
)
await self.con.execute('''
configure current database reset ext::_conf::SingleObj
''')
await _check(
config_name='ready',
opt_value=None,
objs=[],
obj=None,
)
await self.con.execute('''
configure current database reset ext::_conf::Config::secret;
''')
await self.con.execute('''
configure current database reset ext::_conf::Config::config_name;
''')
await _check(
config_name='',
objs=[],
)
if not in_tx:
con2 = await self.connect(database=self.con.dbname)
try:
await con2.query('select 1')
await self.con.execute('''
CONFIGURE CURRENT BRANCH INSERT ext::_conf::Obj {
name := 'fail',
value := '',
};
''')
# This needs to fail
with self.assertRaisesRegex(
edgedb.ConstraintViolationError, ""
):
await self.con.execute('''
CONFIGURE CURRENT BRANCH INSERT ext::_conf::Obj {
name := 'fail',
value := '',
};
insert Test;
''')
# The code path by which the above fails is subtle (it
# gets triggered by config processing code in the
# server). Make sure that the error properly aborts
# the whole script.
await self.assert_query_result(
'select count(Test)',
[0],
)
finally:
await con2.aclose() | )
# Check that the ids are stable
await self.assert_query_result( | _extension_test_05 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_05(self):
# Test config extension
await self.con.execute('''
create type Test;
''')
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_05(in_tx=True)
try:
await self._extension_test_05(in_tx=False)
finally:
await self.con.execute('''
drop extension _conf
''')
finally:
await self.con.execute('''
drop type Test;
''') | )
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_05(in_tx=True)
try:
await self._extension_test_05(in_tx=False)
finally:
await self.con.execute( | test_edgeql_extensions_05 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def _extension_test_06b(self):
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version "2.0";
module default {
function lol() -> str using (ext::bar::fubar())
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'select lol()',
['foobar'],
)
# Try dropping everything that uses it but not the extension
async with self._run_and_rollback():
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version "2.0";
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
# Try dropping it but adding bar
async with self._run_and_rollback():
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version "2.0";
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
# Try dropping everything including the extension
await self.con.execute(r"""
START MIGRATION TO {
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
# Try it explicitly specifying an old version. Note
# that we don't *yet* support upgrading between extension
# versions; you need to drop it and recreate everything, which
# obviously is not great.
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version '1.0';
module default {
function lol() -> str using (ext::bar::fubar())
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'select lol()',
['foo?bar'],
)
# Try dropping everything including the extension
await self.con.execute(r"""
START MIGRATION TO {
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
with self.assertRaisesRegex(
edgedb.SchemaError,
"cannot install extension 'foo' version 2.0: "
"version 1.0 is already installed"
):
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version '1.0';
using extension foo version '2.0';
module default {
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""") | )
await self.assert_query_result(
'select lol()',
['foobar'],
)
# Try dropping everything that uses it but not the extension
async with self._run_and_rollback():
await self.con.execute(r | _extension_test_06b | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_06(self):
# Make an extension with dependencies
await self.con.execute('''
create extension package foo VERSION '1.0' {
set ext_module := "ext::foo";
create module ext::foo;
create function ext::foo::test() -> str using ("foo?");
};
create extension package foo VERSION '2.0' {
set ext_module := "ext::foo";
create module ext::foo;
create function ext::foo::test() -> str using ("foo");
};
create extension package bar VERSION '1.0' {
set ext_module := "ext::bar";
set dependencies := ["foo>=1.0"];
create module ext::bar;
create function ext::bar::fubar() -> str using (
ext::foo::test() ++ "bar"
);
};
create extension package bar VERSION '2.0' {
set ext_module := "ext::bar";
set dependencies := ["foo>=2.0"];
create module ext::bar;
create function ext::bar::fubar() -> str using (
ext::foo::test() ++ "bar"
);
};
''')
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_06b()
finally:
await self.con.execute('''
drop extension package bar VERSION '1.0';
drop extension package foo VERSION '1.0';
drop extension package bar VERSION '2.0';
drop extension package foo VERSION '2.0';
''') | )
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_06b()
finally:
await self.con.execute( | test_edgeql_extensions_06 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def _extension_test_07(self):
await self.con.execute(r"""
START MIGRATION TO {
using extension asdf version "1.0";
module default {
function lol() -> int64 using (ext::asdf::getver())
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'select lol()',
[1],
)
await self.con.execute(r"""
START MIGRATION TO {
using extension asdf version "3.0";
module default {
function lol() -> int64 using (ext::asdf::getver())
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'select lol()',
[3],
)
await self.assert_query_result(
'select ext::asdf::getsver()',
['3'],
) | )
await self.assert_query_result(
'select lol()',
[1],
)
await self.con.execute(r | _extension_test_07 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_07(self):
# Make an extension with chained upgrades
await self.con.execute('''
create extension package asdf version '1.0' {
set ext_module := "ext::asdf";
create module ext::asdf;
create function ext::asdf::getver() -> int64 using (1);
};
create extension package asdf version '2.0' {
set ext_module := "ext::asdf";
create module ext::asdf;
create function ext::asdf::getver() -> int64 using (2);
create function ext::asdf::getsver() -> str using (
<str>ext::asdf::getver());
};
create extension package asdf version '3.0' {
set ext_module := "ext::asdf";
create module ext::asdf;
create function ext::asdf::getver() -> int64 using (3);
create function ext::asdf::getsver() -> str using (
<str>ext::asdf::getver());
};
create extension package asdf migration
from version '1.0' to version '2.0' {
alter function ext::asdf::getver() using (2);
create function ext::asdf::getsver() -> str using (
<str>ext::asdf::getver());
};
create extension package asdf migration
from version '2.0' to version '3.0' {
alter function ext::asdf::getver() using (3);
};
''')
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_07()
finally:
await self.con.execute('''
drop extension package asdf version '1.0';
drop extension package asdf version '2.0';
drop extension package asdf migration
from version '1.0' to version '2.0';
drop extension package asdf version '3.0';
drop extension package asdf migration
from version '2.0' to version '3.0';
''') | )
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_07()
finally:
await self.con.execute( | test_edgeql_extensions_07 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def _extension_test_08(self):
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version "1.0";
module default {
function lol() -> str using (ext::bar::fubar())
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'select lol()',
['bar'],
)
# Direct upgrade command should fail.
async with self.assertRaisesRegexTx(
edgedb.SchemaError,
"cannot create extension 'bar' version '2.0': "
"it depends on extension foo which has not been created",
):
await self.con.execute(r"""
alter extension bar to version '2.0';
""")
# Migration should work, though, since it will create the dependency.
await self.con.execute(r"""
START MIGRATION TO {
using extension bar version "2.0";
module default {
function lol() -> str using (ext::bar::fubar())
}
};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.assert_query_result(
'select lol()',
['foobar'],
) | )
await self.assert_query_result(
'select lol()',
['bar'],
)
# Direct upgrade command should fail.
async with self.assertRaisesRegexTx(
edgedb.SchemaError,
"cannot create extension 'bar' version '2.0': "
"it depends on extension foo which has not been created",
):
await self.con.execute(r | _extension_test_08 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
async def test_edgeql_extensions_08(self):
# Make an extension with dependencies
await self.con.execute('''
create extension package foo VERSION '2.0' {
set ext_module := "ext::foo";
create module ext::foo;
create function ext::foo::test() -> str using ("foo");
};
create extension package bar VERSION '1.0' {
set ext_module := "ext::bar";
create module ext::bar;
create function ext::bar::fubar() -> str using (
"bar"
);
};
create extension package bar VERSION '2.0' {
set ext_module := "ext::bar";
set dependencies := ["foo>=2.0"];
create module ext::bar;
create function ext::bar::fubar() -> str using (
ext::foo::test() ++ "bar"
);
};
create extension package bar migration
from version '1.0' to version '2.0' {
alter function ext::bar::fubar() using (
ext::foo::test() ++ "bar"
);
};
''')
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_08()
finally:
await self.con.execute('''
drop extension package bar VERSION '1.0';
drop extension package bar VERSION '2.0';
drop extension package foo VERSION '2.0';
drop extension package bar migration
from version '1.0' to version '2.0';
''') | )
try:
async for tx in self._run_and_rollback_retrying():
async with tx:
await self._extension_test_08()
finally:
await self.con.execute( | test_edgeql_extensions_08 | python | geldata/gel | tests/test_edgeql_extensions.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_extensions.py | Apache-2.0 |
def test_codegen_fts_search_no_score(self):
sql = self._compile(
'''
select fts::search(Issue, 'spiced', language := 'eng').object
'''
)
self.assertNotIn(
"score_serialized",
sql,
"std::fts::search score should not be serialized when not needed",
) | select fts::search(Issue, 'spiced', language := 'eng').object | test_codegen_fts_search_no_score | python | geldata/gel | tests/test_edgeql_sql_codegen.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_sql_codegen.py | Apache-2.0 |
def test_codegen_typeid_no_join(self):
sql = self._compile(
'''
select Issue { name, number, tid := .__type__.id }
'''
)
self.assertNotIn(
"edgedbstd",
sql,
"typeid injection shouldn't joining ObjectType table",
) | select Issue { name, number, tid := .__type__.id } | test_codegen_typeid_no_join | python | geldata/gel | tests/test_edgeql_sql_codegen.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_sql_codegen.py | Apache-2.0 |
def test_codegen_nested_for_no_uuid(self):
sql = self._compile(
'''
for x in {1,2,3} union (for y in {3,4,5} union (x+y))
'''
)
self.assertNotIn(
"uuid_generate",
sql,
"unnecessary uuid_generate for FOR loop without volatility",
) | for x in {1,2,3} union (for y in {3,4,5} union (x+y)) | test_codegen_nested_for_no_uuid | python | geldata/gel | tests/test_edgeql_sql_codegen.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_sql_codegen.py | Apache-2.0 |
async def test_edgeql_for_in_computable_02(self):
await self.con.execute(
"""
UPDATE User
FILTER .name = "Alice"
SET {
deck += {
(INSERT Card {
name := "Ice Elemental",
element := "Water",
cost := 10,
}),
(INSERT Card {
name := "Basilisk",
element := "Earth",
cost := 20,
}),
}
}
"""
)
await self.assert_query_result(
r"""
SELECT User {
select_deck := (
SELECT DISTINCT((
FOR letter IN {'I', 'B'}
UNION (
FOR cost IN {1, 2, 10, 20}
UNION (
SELECT User.deck {
name,
letter := letter ++ <str>cost
}
FILTER
.name[0] = letter AND .cost = cost
)
)
))
ORDER BY .name THEN .letter
)
} FILTER .name = 'Alice';
""",
[
{
'select_deck': [
{'name': 'Basilisk', 'letter': 'B20'},
{'name': 'Bog monster', 'letter': 'B2'},
{'name': 'Ice Elemental', 'letter': 'I10'},
{'name': 'Imp', 'letter': 'I1'},
]
}
]
) | UPDATE User
FILTER .name = "Alice"
SET {
deck += {
(INSERT Card {
name := "Ice Elemental",
element := "Water",
cost := 10,
}),
(INSERT Card {
name := "Basilisk",
element := "Earth",
cost := 20,
}),
}
} | test_edgeql_for_in_computable_02 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_in_computable_02d(self):
await self.con.execute(
"""
UPDATE User
FILTER .name = "Alice"
SET {
deck += {
(INSERT Card {
name := "Ice Elemental",
element := "Water",
cost := 10,
}),
(INSERT Card {
name := "Basilisk",
element := "Earth",
cost := 20,
}),
}
}
"""
)
await self.assert_query_result(
r'''
SELECT User {
select_deck := assert_distinct((
WITH cards := (
FOR letter IN {'I', 'B'}
UNION (
FOR cost IN {1, 2, 10, 20}
UNION (
SELECT User.deck {
name,
letter := letter ++ <str>cost
}
FILTER
.name[0] = letter AND .cost = cost
)
)
)
SELECT cards {name, letter} ORDER BY .name THEN .letter
))
} FILTER .name = 'Alice';
''',
[
{
'select_deck': [
{'name': 'Basilisk', 'letter': 'B20'},
{'name': 'Bog monster', 'letter': 'B2'},
{'name': 'Ice Elemental', 'letter': 'I10'},
{'name': 'Imp', 'letter': 'I1'},
]
}
]
) | UPDATE User
FILTER .name = "Alice"
SET {
deck += {
(INSERT Card {
name := "Ice Elemental",
element := "Water",
cost := 10,
}),
(INSERT Card {
name := "Basilisk",
element := "Earth",
cost := 20,
}),
}
} | test_edgeql_for_in_computable_02d | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_in_computable_05(self):
await self.assert_query_result(
r'''
SELECT User {
select_deck := (
FOR letter IN {'X'}
UNION (
(SELECT .deck.name)
)
)
} FILTER .name = 'Alice';
''',
[{"select_deck":
tb.bag(["Bog monster", "Dragon", "Giant turtle", "Imp"])}],
)
# This one caused a totally nonsense type error.
await self.assert_query_result(
r'''
SELECT User {
select_deck := (
FOR letter IN 'X'
UNION (
((SELECT .deck).name)
)
)
} FILTER .name = 'Alice';
''',
[{"select_deck":
tb.bag(["Bog monster", "Dragon", "Giant turtle", "Imp"])}],
) | ,
[{"select_deck":
tb.bag(["Bog monster", "Dragon", "Giant turtle", "Imp"])}],
)
# This one caused a totally nonsense type error.
await self.assert_query_result(
r | test_edgeql_for_in_computable_05 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_correlated_01(self):
await self.assert_query_result(
r'''
SELECT count((
WITH X := {1, 2}
SELECT (X, (FOR x in {X} UNION (SELECT x)))
));
''',
[4],
)
await self.assert_query_result(
r'''
SELECT count((
WITH X := {1, 2}
SELECT ((FOR x in {X} UNION (SELECT x)), X)
));
''',
[4],
) | ,
[4],
)
await self.assert_query_result(
r | test_edgeql_for_correlated_01 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_tuple_optional_01(self):
await self.assert_query_result(
r'''
for user in User union (
((select (1,) filter false) ?? (2,)).0
);
''',
[2, 2, 2, 2],
)
await self.assert_query_result(
r'''
for user in User union (
((select (1,) filter user.name = 'Alice') ?? (2,)).0
);
''',
tb.bag([1, 2, 2, 2]),
) | ,
[2, 2, 2, 2],
)
await self.assert_query_result(
r | test_edgeql_for_tuple_optional_01 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_optional_01(self):
# Lol FOR OPTIONAL doesn't work for object-type iterators
# but it does work for 1-ary tuples
await self.assert_query_result(
r'''
for optional x in
((select User filter .name = 'George'),)
union x.0.deck_cost ?? 0;
''',
[0],
)
await self.assert_query_result(
r'''
for optional x in
((select User filter .name = 'George'),)
union x.0
''',
[],
)
await self.assert_query_result(
r'''
for optional x in
((select User filter .name = 'George'),)
union x
''',
[],
)
await self.assert_query_result(
r'''
for optional x in
((select User filter .name = 'Alice'),)
union x.0.deck_cost ?? 0;
''',
[11],
)
await self.assert_query_result(
r'''
for optional x in
((select User filter .name = 'George'),)
union (insert Award { name := "Participation" })
''',
[{}],
)
await self.assert_query_result(
r'''
for optional x in (<bool>{})
union (insert Award { name := "Participation!" })
''',
[{}],
)
await self.assert_query_result(
r'''
for user in (select User filter .name = 'Alice') union (
for optional x in (<Card>{},) union (
1
)
);
''',
[1],
)
await self.assert_query_result(
r'''
for user in (select User filter .name = 'Alice') union (
for optional x in (<Card>{},) union (
user.name
)
);
''',
['Alice'],
)
await self.assert_query_result(
r'''
for user in (select User filter .name = 'Alice') union (
for optional x in (<Card>{},) union (
user.name ++ (x.0.name ?? "!")
)
);
''',
['Alice!'],
) | ,
[0],
)
await self.assert_query_result(
r | test_edgeql_for_optional_01 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_optional_02(self):
await self.assert_query_result(
r'''
for optional x in
(select User filter .name = 'George')
union x.deck_cost ?? 0;
''',
[0],
)
await self.assert_query_result(
r'''
for optional x in
(select User filter .name = 'Alice')
union x.deck_cost ?? 0;
''',
[11],
)
await self.assert_query_result(
r'''
for optional x in
(select User filter .name = 'George')
union (insert Award { name := "Participation" })
''',
[{}],
) | ,
[0],
)
await self.assert_query_result(
r | test_edgeql_for_optional_02 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_lprop_01(self):
await self.assert_query_result(
'''
SELECT User {
cards := (
SELECT (FOR d IN .deck SELECT (d.name, d@count))
ORDER BY .0
),
}
filter .name = 'Carol';
''',
[
{
"cards": [
["Bog monster", 3],
["Djinn", 1],
["Dwarf", 4],
["Giant eagle", 3],
["Giant turtle", 2],
["Golem", 2],
["Sprite", 4]
]
}
]
)
await self.assert_query_result(
'''
SELECT User {
cards := (
SELECT (FOR d IN .deck[is SpecialCard]
SELECT (d.name, d@count))
ORDER BY .0
),
}
filter .name = 'Carol';
''',
[
{
"cards": [
["Djinn", 1],
]
}
]
) | SELECT User {
cards := (
SELECT (FOR d IN .deck SELECT (d.name, d@count))
ORDER BY .0
),
}
filter .name = 'Carol';
''',
[
{
"cards": [
["Bog monster", 3],
["Djinn", 1],
["Dwarf", 4],
["Giant eagle", 3],
["Giant turtle", 2],
["Golem", 2],
["Sprite", 4]
]
}
]
)
await self.assert_query_result( | test_edgeql_for_lprop_01 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_edgeql_for_lprop_02(self):
await self.assert_query_result(
'''
SELECT Card {
users := (
SELECT (FOR u IN .<deck[is User] SELECT (u.name, u@count))
ORDER BY .0
),
}
filter .name = 'Dragon'
''',
[{"users": [["Alice", 2], ["Dave", 1]]}],
)
await self.assert_query_result(
'''
SELECT Card {
users := (
SELECT (FOR u IN .owners SELECT (u.name, u@count))
ORDER BY .0
),
}
filter .name = 'Dragon'
''',
[{"users": [["Alice", 2], ["Dave", 1]]}],
) | SELECT Card {
users := (
SELECT (FOR u IN .<deck[is User] SELECT (u.name, u@count))
ORDER BY .0
),
}
filter .name = 'Dragon'
''',
[{"users": [["Alice", 2], ["Dave", 1]]}],
)
await self.assert_query_result( | test_edgeql_for_lprop_02 | python | geldata/gel | tests/test_edgeql_for.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_for.py | Apache-2.0 |
async def test_server_proto_config_objects(self):
await self.assert_query_result(
"""SELECT cfg::InstanceConfig IS cfg::AbstractConfig""",
[True],
)
await self.assert_query_result(
"""SELECT cfg::InstanceConfig IS cfg::DatabaseConfig""",
[False],
)
await self.assert_query_result(
"""SELECT cfg::InstanceConfig IS cfg::InstanceConfig""",
[True],
)
await self.assert_query_result(
"""
SELECT cfg::AbstractConfig {
tname := .__type__.name
}
ORDER BY .__type__.name
""",
[{
"tname": "cfg::Config",
}, {
"tname": "cfg::DatabaseConfig",
}, {
"tname": "cfg::InstanceConfig",
}]
) | SELECT cfg::InstanceConfig IS cfg::AbstractConfig""",
[True],
)
await self.assert_query_result(
"""SELECT cfg::InstanceConfig IS cfg::DatabaseConfig""",
[False],
)
await self.assert_query_result(
"""SELECT cfg::InstanceConfig IS cfg::InstanceConfig""",
[True],
)
await self.assert_query_result( | test_server_proto_config_objects | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_01(self):
with self.assertRaisesRegex(
edgedb.ConfigurationError,
'invalid setting value type'):
await self.con.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 'test';
''')
with self.assertRaisesRegex(
edgedb.QueryError,
'cannot be executed in a transaction block'):
await self.con.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 10;
CONFIGURE INSTANCE SET __internal_testvalue := 1;
''')
with self.assertRaisesRegex(
edgedb.QueryError,
'cannot be executed in a transaction block'):
await self.con.execute('''
CONFIGURE INSTANCE SET __internal_testvalue := 1;
CONFIGURE SESSION SET __internal_sess_testvalue := 10;
''')
with self.assertRaisesRegex(
edgedb.QueryError,
'cannot be executed in a transaction block'):
async with self.con.transaction():
await self.con.query('''
CONFIGURE INSTANCE SET __internal_testvalue := 1;
''')
with self.assertRaisesRegex(
edgedb.UnsupportedFeatureError,
'CONFIGURE SESSION INSERT is not supported'):
await self.con.query('''
CONFIGURE SESSION INSERT TestSessionConfig { name := 'foo' };
''')
with self.assertRaisesRegex(
edgedb.ConfigurationError,
'unrecognized configuration object'):
await self.con.query('''
CONFIGURE INSTANCE INSERT cf::TestInstanceConfig {
name := 'foo'
};
''')
props = {str(x) for x in range(500)}
with self.assertRaisesRegex(
edgedb.ConfigurationError,
'too large'):
await self.con.query(f'''
CONFIGURE SESSION SET multiprop := {props};
''') | )
with self.assertRaisesRegex(
edgedb.QueryError,
'cannot be executed in a transaction block'):
await self.con.execute( | test_server_proto_configure_01 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_02(self):
conf = await self.con.query_single('''
SELECT cfg::Config.__internal_testvalue LIMIT 1
''')
self.assertEqual(conf, 0)
jsonconf = await self.con.query_single('''
SELECT cfg::get_config_json()
''')
all_conf = json.loads(jsonconf)
conf = all_conf['__internal_testvalue']
self.assertEqual(conf['value'], 0)
self.assertEqual(conf['source'], 'default')
try:
await self.con.query('''
CONFIGURE SESSION SET multiprop := {"one", "two"};
''')
# The "Configure" is spelled the way it's spelled on purpose
# to test that we handle keywords in a case-insensitive manner
# in constant extraction code.
await self.con.query('''
Configure INSTANCE SET __internal_testvalue := 1;
''')
conf = await self.con.query_single('''
SELECT cfg::Config.__internal_testvalue LIMIT 1
''')
self.assertEqual(conf, 1)
jsonconf = await self.con.query_single('''
SELECT cfg::get_config_json()
''')
all_conf = json.loads(jsonconf)
conf = all_conf['__internal_testvalue']
self.assertEqual(conf['value'], 1)
self.assertEqual(conf['source'], 'system override')
conf = all_conf['multiprop']
self.assertEqual(set(conf['value']), {'one', 'two'})
self.assertEqual(conf['source'], 'session')
finally:
await self.con.execute('''
CONFIGURE INSTANCE RESET __internal_testvalue
''')
await self.con.execute('''
CONFIGURE SESSION RESET multiprop
''') | )
self.assertEqual(conf, 0)
jsonconf = await self.con.query_single( | test_server_proto_configure_02 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def _server_proto_configure_03(self, scope, base_result=None):
# scope is either INSTANCE or CURRENT DATABASE
# when scope is CURRENT DATABASE, base_result can be an INSTANCE
# config that should be shadowed whenever there is a database config
if base_result is None:
base_result = []
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj { name } FILTER .name LIKE 'test_03%';
''',
base_result,
)
await self.con.query(f'''
CONFIGURE {scope} INSERT TestInstanceConfig {{
name := 'test_03'
}};
''')
await self.con.query(f'''
CONFIGURE {scope} INSERT cfg::TestInstanceConfig {{
name := 'test_03_01'
}};
''')
with self.assertRaisesRegex(
edgedb.InterfaceError,
r'it does not return any data',
):
await self.con.query_required_single(f'''
CONFIGURE {scope} INSERT cfg::TestInstanceConfig {{
name := 'test_03_0122222222'
}};
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj { name }
FILTER .name LIKE 'test_03%'
ORDER BY .name;
''',
[
{
'name': 'test_03',
},
{
'name': 'test_03_01',
}
]
)
await self.con.query(f'''
CONFIGURE {scope}
RESET TestInstanceConfig FILTER .name = 'test_03';
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj { name }
FILTER .name LIKE 'test_03%';
''',
[
{
'name': 'test_03_01',
},
],
)
await self.con.query(f'''
CONFIGURE {scope}
RESET TestInstanceConfig FILTER .name = 'test_03_01';
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj { name }
FILTER .name LIKE 'test_03%';
''',
base_result,
)
# Repeat reset that doesn't match anything this time.
await self.con.query(f'''
CONFIGURE {scope}
RESET TestInstanceConfig FILTER .name = 'test_03_01';
''')
await self.con.query(f'''
CONFIGURE {scope} INSERT TestInstanceConfig {{
name := 'test_03',
obj := (INSERT Subclass1 {{ name := 'foo', sub1 := 'sub1' }})
}}
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj {
name,
obj[IS cfg::Subclass1]: {
name,
sub1,
},
}
FILTER .name LIKE 'test_03%';
''',
[
{
'name': 'test_03',
'obj': {
'name': 'foo',
'sub1': 'sub1',
},
},
],
)
await self.con.query(f'''
CONFIGURE {scope} INSERT TestInstanceConfig {{
name := 'test_03_01',
obj := (INSERT Subclass2 {{ name := 'bar', sub2 := 'sub2' }})
}}
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj {
name,
obj: {
__type__: {name},
name,
},
}
FILTER .name LIKE 'test_03%'
ORDER BY .name;
''',
[
{
'name': 'test_03',
'obj': {
'__type__': {'name': 'cfg::Subclass1'},
'name': 'foo',
},
},
{
'name': 'test_03_01',
'obj': {
'__type__': {'name': 'cfg::Subclass2'},
'name': 'bar',
},
},
],
)
await self.con.query(f'''
CONFIGURE {scope} RESET TestInstanceConfig
FILTER .obj.name IN {{'foo', 'bar'}} AND .name ILIKE 'test_03%';
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj { name }
FILTER .name LIKE 'test_03%';
''',
base_result,
)
await self.con.query(f'''
CONFIGURE {scope} INSERT TestInstanceConfig {{
name := 'test_03_' ++ <str>count(DETACHED TestInstanceConfig),
}}
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj {
name,
}
FILTER .name LIKE 'test_03%'
ORDER BY .name;
''',
[
{
'name': 'test_03_0',
},
],
)
await self.con.query(f'''
CONFIGURE {scope} INSERT TestInstanceConfigStatTypes {{
name := 'test_03_02',
memprop := <cfg::memory>'108MiB',
durprop := <duration>'108 seconds',
}}
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj {
name,
[IS cfg::TestInstanceConfigStatTypes].memprop,
[IS cfg::TestInstanceConfigStatTypes].durprop,
}
FILTER .name = 'test_03_02';
''',
[
{
'name': 'test_03_02',
'memprop': '108MiB',
'durprop': 'PT1M48S',
},
],
[
{
'name': 'test_03_02',
'memprop': '108MiB',
'durprop': datetime.timedelta(seconds=108),
},
],
)
await self.con.query(f'''
CONFIGURE {scope} RESET TestInstanceConfig
FILTER .name ILIKE 'test_03%';
''')
await self.assert_query_result(
'''
SELECT cfg::Config.sysobj { name }
FILTER .name LIKE 'test_03%';
''',
base_result,
) | SELECT cfg::Config.sysobj { name } FILTER .name LIKE 'test_03%';
''',
base_result,
)
await self.con.query(f | _server_proto_configure_03 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_03c(self):
await self.con.query('''
CONFIGURE INSTANCE INSERT TestInstanceConfig {
name := 'test_03_base'
};
''')
await self._server_proto_configure_03(
'CURRENT DATABASE', [{'name': 'test_03_base'}]
)
await self.con.query('''
CONFIGURE INSTANCE RESET TestInstanceConfig;
''') | )
await self._server_proto_configure_03(
'CURRENT DATABASE', [{'name': 'test_03_base'}]
)
await self.con.query( | test_server_proto_configure_03c | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_04(self):
with self.assertRaisesRegex(
edgedb.UnsupportedFeatureError,
'CONFIGURE SESSION INSERT is not supported'):
await self.con.query('''
CONFIGURE SESSION INSERT TestSessionConfig {name := 'test_04'}
''')
with self.assertRaisesRegex(
edgedb.ConfigurationError,
"unrecognized configuration object 'Unrecognized'"):
await self.con.query('''
CONFIGURE INSTANCE INSERT Unrecognized {name := 'test_04'}
''')
with self.assertRaisesRegex(
edgedb.QueryError,
"must not have a FILTER clause"):
await self.con.query('''
CONFIGURE INSTANCE RESET __internal_testvalue FILTER 1 = 1;
''')
with self.assertRaisesRegex(
edgedb.QueryError,
"non-constant expression"):
await self.con.query('''
CONFIGURE SESSION SET __internal_testmode := (random() = 0);
''')
with self.assertRaisesRegex(
edgedb.ConfigurationError,
"'Subclass1' cannot be configured directly"):
await self.con.query('''
CONFIGURE INSTANCE INSERT Subclass1 {
name := 'foo'
};
''')
await self.con.query('''
CONFIGURE INSTANCE INSERT TestInstanceConfig {
name := 'test_04',
}
''')
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
"TestInstanceConfig.name violates exclusivity constraint"):
await self.con.query('''
CONFIGURE INSTANCE INSERT TestInstanceConfig {
name := 'test_04',
}
''') | )
with self.assertRaisesRegex(
edgedb.ConfigurationError,
"unrecognized configuration object 'Unrecognized'"):
await self.con.query( | test_server_proto_configure_04 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_05(self):
await self.con.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 1;
''')
await self.assert_query_result(
'''
SELECT cfg::Config.__internal_sess_testvalue
''',
[
1
],
)
await self.con.execute('''
CONFIGURE CURRENT DATABASE SET __internal_sess_testvalue := 3;
''')
await self.con.execute('''
CONFIGURE INSTANCE SET __internal_sess_testvalue := 2;
''')
await self.assert_query_result(
'''
SELECT cfg::Config.__internal_sess_testvalue
''',
[
1 # fail
],
)
await self.assert_query_result(
'''
SELECT cfg::InstanceConfig.__internal_sess_testvalue
''',
[
2
],
)
await self.assert_query_result(
'''
SELECT cfg::BranchConfig.__internal_sess_testvalue
''',
[
3
],
)
await self.con.execute('''
CONFIGURE SESSION RESET __internal_sess_testvalue;
''')
await self.assert_query_result(
'''
SELECT cfg::Config.__internal_sess_testvalue
''',
[
3
],
)
await self.con.execute('''
CONFIGURE CURRENT DATABASE RESET __internal_sess_testvalue;
''')
await self.assert_query_result(
'''
SELECT cfg::Config.__internal_sess_testvalue
''',
[
2
],
) | )
await self.assert_query_result( | test_server_proto_configure_05 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_06(self):
con2 = None
try:
await self.con.execute('''
CONFIGURE SESSION SET singleprop := '42';
''')
await self.con.execute('''
CONFIGURE SESSION SET multiprop := {'1', '2', '3'};
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[
'1', '2', '3'
],
)
con2 = await self.connect(database=self.con.dbname)
await con2.execute('''
start transaction
''')
await self.con.execute('''
CONFIGURE INSTANCE SET multiprop := {'4', '5'};
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[
'1', '2', '3'
],
)
await self.con.execute('''
CONFIGURE SESSION RESET multiprop;
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[
'4', '5'
],
)
finally:
await self.con.execute('''
CONFIGURE SESSION RESET multiprop;
''')
await self.con.execute('''
CONFIGURE INSTANCE RESET multiprop;
''')
if con2:
await con2.aclose() | )
await self.con.execute( | test_server_proto_configure_06 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_07(self):
try:
await self.con.execute('''
CONFIGURE SESSION SET multiprop := <str>{};
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[],
)
await self.con.execute('''
CONFIGURE INSTANCE SET multiprop := {'4'};
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[],
)
await self.con.execute('''
CONFIGURE SESSION SET multiprop := {'5'};
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[
'5',
],
)
await self.con.execute('''
CONFIGURE SESSION RESET multiprop;
''')
await self.assert_query_result(
'''
SELECT _ := cfg::Config.multiprop ORDER BY _
''',
[
'4',
],
)
finally:
await self.con.execute('''
CONFIGURE SESSION RESET multiprop;
''')
await self.con.execute('''
CONFIGURE INSTANCE RESET multiprop;
''') | )
await self.assert_query_result( | test_server_proto_configure_07 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_08(self):
with self.assertRaisesRegex(
edgedb.ConfigurationError, 'invalid setting value'
):
await self.con.execute('''
CONFIGURE INSTANCE SET _pg_prepared_statement_cache_size := -5;
''')
with self.assertRaisesRegex(
edgedb.ConfigurationError, 'invalid setting value'
):
await self.con.execute('''
CONFIGURE INSTANCE SET _pg_prepared_statement_cache_size := 0;
''')
try:
await self.con.execute('''
CONFIGURE INSTANCE SET _pg_prepared_statement_cache_size := 42;
''')
conf = await self.con.query_single('''
SELECT cfg::Config._pg_prepared_statement_cache_size LIMIT 1
''')
self.assertEqual(conf, 42)
finally:
await self.con.execute('''
CONFIGURE INSTANCE RESET _pg_prepared_statement_cache_size;
''') | )
with self.assertRaisesRegex(
edgedb.ConfigurationError, 'invalid setting value'
):
await self.con.execute( | test_server_proto_configure_08 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_09(self):
con2 = await self.connect(database=self.con.dbname)
default_value = await con2.query_single(
'SELECT assert_single(cfg::Config).boolprop'
)
try:
for value in [True, False, True, False]:
await self.con.execute(f'''
CONFIGURE SESSION SET boolprop := <bool>'{value}';
''')
# The first immediate query is likely NOT syncing in-memory
# state to the backend connection, so this will test that
# the state in the SQL temp table is correctly set.
await self.assert_query_result(
'''
SELECT cfg::Config.boolprop
''',
[value],
)
# Now change the state on the backend connection, hopefully,
# by running a query with con2 with different state.
self.assertEqual(
await con2.query_single(
'SELECT assert_single(cfg::Config).boolprop'
),
default_value,
)
# The second query shall sync in-memory state to the backend
# connection, so this tests if the statically evaluated bool
# value is correct.
await self.assert_query_result(
'''
SELECT cfg::Config.boolprop
''',
[value],
)
finally:
await con2.aclose() | )
# The first immediate query is likely NOT syncing in-memory
# state to the backend connection, so this will test that
# the state in the SQL temp table is correctly set.
await self.assert_query_result( | test_server_proto_configure_09 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_describe_system_config(self):
try:
conf1 = "CONFIGURE INSTANCE SET singleprop := '1337';"
await self.con.execute(conf1)
conf2 = textwrap.dedent('''\
CONFIGURE INSTANCE INSERT cfg::TestInstanceConfig {
name := 'test_describe',
obj := (
(INSERT cfg::Subclass1 {
name := 'foo',
sub1 := 'sub1',
})
),
};
''')
await self.con.execute(conf2)
conf3 = "CONFIGURE SESSION SET singleprop := '42';"
await self.con.execute(conf3)
conf4 = "CONFIGURE INSTANCE SET memprop := <cfg::memory>'100MiB';"
await self.con.execute(conf4)
conf5 = "CONFIGURE INSTANCE SET enumprop := <cfg::TestEnum>'Two';"
await self.con.execute(conf5)
res = await self.con.query_single('DESCRIBE INSTANCE CONFIG;')
self.assertIn(conf1, res)
self.assertIn(conf2, res)
self.assertNotIn(conf3, res)
self.assertIn(conf4, res)
self.assertIn(conf5, res)
finally:
await self.con.execute('''
CONFIGURE INSTANCE
RESET TestInstanceConfig FILTER .name = 'test_describe'
''')
await self.con.execute('''
CONFIGURE INSTANCE RESET singleprop;
''')
await self.con.execute('''
CONFIGURE INSTANCE RESET memprop;
''') | )
await self.con.execute(conf2)
conf3 = "CONFIGURE SESSION SET singleprop := '42';"
await self.con.execute(conf3)
conf4 = "CONFIGURE INSTANCE SET memprop := <cfg::memory>'100MiB';"
await self.con.execute(conf4)
conf5 = "CONFIGURE INSTANCE SET enumprop := <cfg::TestEnum>'Two';"
await self.con.execute(conf5)
res = await self.con.query_single('DESCRIBE INSTANCE CONFIG;')
self.assertIn(conf1, res)
self.assertIn(conf2, res)
self.assertNotIn(conf3, res)
self.assertIn(conf4, res)
self.assertIn(conf5, res)
finally:
await self.con.execute( | test_server_proto_configure_describe_system_config | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_invalid_duration(self):
with self.assertRaisesRegex(
edgedb.InvalidValueError,
"invalid input syntax for type std::duration: "
"unable to parse '12mse'"):
await self.con.execute('''
configure session set
durprop := <duration>'12mse'
''')
with self.assertRaisesRegex(
edgedb.ConfigurationError,
r"invalid setting value type for durprop: "
r"'std::str' \(expecting 'std::duration"):
await self.con.execute('''
configure instance set
durprop := '12 seconds'
''') | )
with self.assertRaisesRegex(
edgedb.ConfigurationError,
r"invalid setting value type for durprop: "
r"'std::str' \(expecting 'std::duration"):
await self.con.execute( | test_server_proto_configure_invalid_duration | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_compilation(self):
try:
await self.con.execute('''
CREATE TYPE Foo;
''')
async with self._run_and_rollback():
await self.con.execute('''
CONFIGURE SESSION SET allow_bare_ddl :=
cfg::AllowBareDDL.NeverAllow;
''')
async with self.assertRaisesRegexTx(
edgedb.QueryError,
'bare DDL statements are not allowed on this database'
):
await self.con.execute('''
CREATE FUNCTION intfunc() -> int64 USING (1);
''')
async with self._run_and_rollback():
await self.con.execute('''
CONFIGURE SESSION SET store_migration_sdl :=
cfg::StoreMigrationSDL.NeverStore;
''')
await self.con.execute('''
CREATE TYPE Bar;
''')
await self.assert_query_result(
'select schema::Migration { sdl }',
[
{'sdl': None},
{'sdl': None},
]
)
async with self._run_and_rollback():
await self.con.execute('''
CONFIGURE SESSION SET store_migration_sdl :=
cfg::StoreMigrationSDL.AlwaysStore;
''')
await self.con.execute('''
CREATE TYPE Bar;
''')
await self.assert_query_result(
'select schema::Migration { sdl }',
[
{'sdl': None},
{'sdl': (
'module default {\n'
' type Bar;\n'
' type Foo;\n'
'};'
)},
]
)
finally:
await self.con.execute('''
DROP TYPE Foo;
''') | )
async with self._run_and_rollback():
await self.con.execute( | test_server_proto_configure_compilation | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_rollback_state(self):
con1 = self.con
con2 = await self.connect(database=con1.dbname)
try:
await con2.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 2;
''')
await con1.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 1;
''')
self.assertEqual(
await con2.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
'''),
2,
)
self.assertEqual(
await con1.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
'''),
1,
)
with self.assertRaises(edgedb.DivisionByZeroError):
async for tx in con2.retrying_transaction():
async with tx:
await tx.query_single("SELECT 1/0")
self.assertEqual(
await con1.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
'''),
1,
)
finally:
await con2.aclose() | )
await con1.execute( | test_server_proto_rollback_state | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_orphan_rollback_state(self):
con1 = self.con
con2 = await self.connect(database=con1.dbname)
try:
await con2.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 2;
''')
await con1.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 1;
''')
self.assertEqual(
await con2.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
'''),
2,
)
self.assertEqual(
await con1.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
'''),
1,
)
# an orphan ROLLBACK must not change the last_state,
# because the implicit transaction is rolled back
await con2.execute("ROLLBACK")
# ... so that we can actually do the state sync again here
self.assertEqual(
await con2.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
'''),
2,
)
finally:
await con2.aclose() | )
await con1.execute( | test_server_proto_orphan_rollback_state | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_error(self):
con1 = self.con
con2 = await self.connect(database=con1.dbname)
version_str = await con1.query_single('''
select sys::get_version_as_str();
''')
try:
await con2.execute('''
select 1;
''')
err = {
'type': 'SchemaError',
'message': 'danger 1',
'context': {'start': 42},
}
await con1.execute(f'''
configure current database set force_database_error :=
{qlquote.quote_literal(json.dumps(err))};
''')
with self.assertRaisesRegex(edgedb.SchemaError, 'danger 1'):
async for tx in con1.retrying_transaction():
async with tx:
await tx.query('select schema::Object')
with self.assertRaisesRegex(edgedb.SchemaError, 'danger 1',
_position=42):
async for tx in con2.retrying_transaction():
async with tx:
await tx.query('select schema::Object')
# If we change the '_version' to something else we
# should be good
err = {
'type': 'SchemaError',
'message': 'danger 2',
'context': {'start': 42},
'_versions': [version_str + '1'],
}
await con1.execute(f'''
configure current database set force_database_error :=
{qlquote.quote_literal(json.dumps(err))};
''')
await con1.query('select schema::Object')
# It should also be fine if we set a '_scopes' other than 'query'
err = {
'type': 'SchemaError',
'message': 'danger 3',
'context': {'start': 42},
'_scopes': ['restore'],
}
await con1.execute(f'''
configure current database set force_database_error :=
{qlquote.quote_literal(json.dumps(err))};
''')
await con1.query('select schema::Object')
# But if we make it the current version it should still fail
err = {
'type': 'SchemaError',
'message': 'danger 4',
'context': {'start': 42},
'_versions': [version_str],
}
await con1.execute(f'''
configure current database set force_database_error :=
{qlquote.quote_literal(json.dumps(err))};
''')
with self.assertRaisesRegex(edgedb.SchemaError, 'danger 4'):
async for tx in con2.retrying_transaction():
async with tx:
await tx.query('select schema::Object')
with self.assertRaisesRegex(edgedb.SchemaError, 'danger 4'):
async for tx in con1.retrying_transaction():
async with tx:
await tx.query('select schema::Object')
await con2.execute(f'''
configure session set force_database_error := "false";
''')
await con2.query('select schema::Object')
finally:
try:
await con1.execute(f'''
configure current database reset force_database_error;
''')
await con2.execute(f'''
configure session reset force_database_error;
''')
# Make sure both connections are working.
await con2.execute('select 1')
await con1.execute('select 1')
finally:
await con2.aclose() | )
try:
await con2.execute( | test_server_proto_configure_error | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_non_transactional_pg_14_7(self):
con1 = self.con
con2 = await self.connect(database=con1.dbname)
try:
await con2.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 2;
''')
await con1.execute('''
CONFIGURE SESSION SET __internal_sess_testvalue := 1;
''')
await con2.execute('''
CREATE DATABASE pg_14_7;
''')
finally:
await con2.aclose()
await con1.execute('''
CONFIGURE SESSION RESET __internal_sess_testvalue;
''')
await con1.execute('''
DROP DATABASE pg_14_7;
''') | )
await con1.execute( | test_server_proto_non_transactional_pg_14_7 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_recompile_on_db_config(self):
await self.con.execute("create type RecompileOnDBConfig;")
try:
# We need the retries here because the 2 `configure database` may
# race with each other and cause temporary inconsistency
await self.con.execute('''
configure current database set allow_user_specified_id := true;
''')
async for tr in self.try_until_succeeds(
ignore=edgedb.QueryError,
ignore_regexp="cannot assign to property 'id'",
):
async with tr:
await self.con.execute('''
insert RecompileOnDBConfig {
id := <uuid>'8c425e34-d1c3-11ee-8c78-8f34556d1111'
};
''')
await self.con.execute('''
configure current database set allow_user_specified_id := false;
''')
async for tr in self.try_until_fails(
wait_for=edgedb.QueryError,
wait_for_regexp="cannot assign to property 'id'",
):
async with tr:
await self.con.execute('''
insert RecompileOnDBConfig {
id := <uuid>
'8c425e34-d1c3-11ee-8c78-8f34556d2222'
};
''')
await self.con.execute('''
delete RecompileOnDBConfig;
''')
finally:
await self.con.execute('''
configure current database reset allow_user_specified_id;
''')
await self.con.execute("drop type RecompileOnDBConfig;") | )
async for tr in self.try_until_succeeds(
ignore=edgedb.QueryError,
ignore_regexp="cannot assign to property 'id'",
):
async with tr:
await self.con.execute( | test_server_proto_recompile_on_db_config | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_proto_configure_listen_addresses(self):
con1 = con2 = con3 = con4 = con5 = None
async with tb.start_edgedb_server() as sd:
try:
with self.assertRaises(
edgedb.ClientConnectionFailedTemporarilyError
):
await sd.connect(
host="127.0.0.2", timeout=1, wait_until_available=1
)
con1 = await sd.connect()
await con1.execute("""
CONFIGURE INSTANCE SET listen_addresses := {
'127.0.0.2',
};
""")
con2 = await sd.connect(host="127.0.0.2")
self.assertEqual(await con1.query_single("SELECT 1"), 1)
self.assertEqual(await con2.query_single("SELECT 2"), 2)
with self.assertRaises(
edgedb.ClientConnectionFailedTemporarilyError
):
await sd.connect(timeout=1, wait_until_available=1)
await con1.execute("""
CONFIGURE INSTANCE SET listen_addresses := {
'127.0.0.1', '127.0.0.2',
};
""")
con3 = await sd.connect()
for i, con in enumerate((con1, con2, con3)):
self.assertEqual(await con.query_single(f"SELECT {i}"), i)
await con1.execute("""
CONFIGURE INSTANCE SET listen_addresses := {
'0.0.0.0',
};
""")
con4 = await sd.connect()
con5 = await sd.connect(host="127.0.0.2")
for i, con in enumerate((con1, con2, con3, con4, con5)):
self.assertEqual(await con.query_single(f"SELECT {i}"), i)
finally:
closings = []
for con in (con1, con2, con3, con4, con5):
if con is not None:
closings.append(con.aclose())
await asyncio.gather(*closings) | )
con2 = await sd.connect(host="127.0.0.2")
self.assertEqual(await con1.query_single("SELECT 1"), 1)
self.assertEqual(await con2.query_single("SELECT 2"), 2)
with self.assertRaises(
edgedb.ClientConnectionFailedTemporarilyError
):
await sd.connect(timeout=1, wait_until_available=1)
await con1.execute( | test_server_proto_configure_listen_addresses | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_idle_connection_02(self):
from edb import protocol
async with tb.start_edgedb_server(
http_endpoint_security=args.ServerEndpointSecurityMode.Optional,
) as sd:
conn = await sd.connect_test_protocol()
await conn.execute('''
configure system set session_idle_timeout := <duration>'5010ms'
''')
# Check new connections are fed with the new value
async for tr in self.try_until_succeeds(ignore=AssertionError):
async with tr:
con = await sd.connect()
try:
sysconfig = con.get_settings()["system_config"]
self.assertEqual(
sysconfig.session_idle_timeout,
datetime.timedelta(milliseconds=5010),
)
finally:
await con.aclose()
await conn.execute('''
configure system set session_idle_timeout := <duration>'10ms'
''')
await asyncio.sleep(1)
msg = await conn.recv_match(
protocol.ErrorResponse,
message='closing the connection due to idling'
)
# Resolve error code before comparing for better error messages
errcls = errors.EdgeDBError.get_error_class_from_code(
msg.error_code)
self.assertEqual(errcls, errors.IdleSessionTimeoutError) | )
# Check new connections are fed with the new value
async for tr in self.try_until_succeeds(ignore=AssertionError):
async with tr:
con = await sd.connect()
try:
sysconfig = con.get_settings()["system_config"]
self.assertEqual(
sysconfig.session_idle_timeout,
datetime.timedelta(milliseconds=5010),
)
finally:
await con.aclose()
await conn.execute( | test_server_config_idle_connection_02 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_db_config(self):
async with tb.start_edgedb_server(
http_endpoint_security=args.ServerEndpointSecurityMode.Optional,
) as sd:
con1 = await sd.connect()
# Shouldn't be anything in INSTANCE CONFIG, to start.
res = await con1.query_single('DESCRIBE INSTANCE CONFIG;')
self.assertEqual(res, '')
con2 = await sd.connect()
await con1.execute('''
configure current database set __internal_sess_testvalue := 0;
''')
await con2.execute('''
configure current database set __internal_sess_testvalue := 5;
''')
# Check that the DB (Backend) was updated.
conf = await con2.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
''')
self.assertEqual(conf, 5)
# The changes should be immediately visible at EdgeQL level
# in concurrent transactions.
conf = await con1.query_single('''
SELECT assert_single(cfg::Config.__internal_sess_testvalue)
''')
self.assertEqual(conf, 5)
DB = 'main'
# Use `try_until_succeeds` because it might take the server a few
# seconds on slow CI to reload the DB config in the server process.
async for tr in self.try_until_succeeds(
ignore=AssertionError):
async with tr:
info = sd.fetch_server_info()
if 'databases' in info:
databases = info['databases']
else:
databases = info['tenants']['localhost']['databases']
dbconf = databases[DB]['config']
self.assertEqual(
dbconf.get('__internal_sess_testvalue'), 5)
# Now check that the server state is updated when a configure
# command is in a transaction.
async for tx in con1.retrying_transaction():
async with tx:
await tx.execute('''
configure current database set
__internal_sess_testvalue := 10;
''')
async for tr in self.try_until_succeeds(
ignore=AssertionError):
async with tr:
info = sd.fetch_server_info()
if 'databases' in info:
databases = info['databases']
else:
databases = info['tenants']['localhost']['databases']
dbconf = databases[DB]['config']
self.assertEqual(
dbconf.get('__internal_sess_testvalue'), 10) | )
await con2.execute( | test_server_config_db_config | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_default_branch_01(self):
# Test default branch configuration and default branch
# connection fallback behavior.
# TODO: The python bindings don't support the branch argument
# and the __default__ behavior, so we don't test that yet.
# We do test all the different combos for HTTP, though.
DBNAME = 'asdf'
async with tb.start_edgedb_server(
http_endpoint_security=args.ServerEndpointSecurityMode.Optional,
security=args.ServerSecurityMode.InsecureDevMode,
default_branch=DBNAME,
) as sd:
def check(mode, name, current, ok=True):
with self.http_con(sd) as hcon:
res, _, code = self.http_con_request(
hcon,
method='POST',
body=json.dumps(dict(query=qry)).encode(),
headers={'Content-Type': 'application/json'},
path=f'/{mode}/{name}/edgeql',
)
if ok:
self.assertEqual(code, 200, f'Request failed: {res}')
self.assertEqual(
json.loads(res).get('data'),
[current],
)
else:
self.assertEqual(
code, 404, f'Expected 404, got: {code}/{res}')
# Since 'edgedb' doesn't exist, trying to connect to it
# should route to our default database instead.
con = await sd.connect(database='edgedb')
await con.query('CREATE EXTENSION edgeql_http')
qry = '''
select sys::get_current_database()
'''
dbname = await con.query_single(qry)
self.assertEqual(dbname, DBNAME)
check('db', 'edgedb', DBNAME)
check('branch', '__default__', DBNAME)
check('db', '__default__', DBNAME, ok=False)
check('branch', 'edgedb', DBNAME, ok=False)
await con.query_single('''
create database edgedb
''')
await con.aclose()
# Now that 'edgedb' exists, we should connect to it
con = await sd.connect(database='edgedb')
await con.query('CREATE EXTENSION edgeql_http')
dbname = await con.query_single(qry)
self.assertEqual(dbname, 'edgedb')
await con.aclose()
check('db', 'edgedb', 'edgedb')
check('branch', '__default__', DBNAME)
check('db', '__default__', DBNAME, ok=False)
check('branch', 'edgedb', 'edgedb') | dbname = await con.query_single(qry)
self.assertEqual(dbname, DBNAME)
check('db', 'edgedb', DBNAME)
check('branch', '__default__', DBNAME)
check('db', '__default__', DBNAME, ok=False)
check('branch', 'edgedb', DBNAME, ok=False)
await con.query_single( | test_server_config_default_branch_01 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_backend_levels(self):
async def assert_conf(con, name, expected_val):
val = await con.query_single(f'''
select assert_single(cfg::Config.{name})
''')
if isinstance(val, datetime.timedelta):
val //= datetime.timedelta(milliseconds=1)
self.assertEqual(
val,
expected_val
)
with tempfile.TemporaryDirectory() as tmpdir:
async with tb.start_edgedb_server(
data_dir=tmpdir,
security=args.ServerSecurityMode.InsecureDevMode,
) as sd:
c1 = await sd.connect()
c2 = await sd.connect()
await c2.query('create database test')
t1 = await sd.connect(database='test')
t2 = await sd.connect(database='test')
# check that the default was set correctly
await assert_conf(
c1, 'session_idle_transaction_timeout', 10000)
####
await c1.query('''
configure instance set
session_idle_transaction_timeout :=
<duration>'20s'
''')
for c in {c1, c2, t1}:
await assert_conf(
c, 'session_idle_transaction_timeout', 20000)
####
await t1.query('''
configure current database set
session_idle_transaction_timeout :=
<duration>'30000ms'
''')
for c in {c1, c2}:
await assert_conf(
c, 'session_idle_transaction_timeout', 20000)
await assert_conf(
t1, 'session_idle_transaction_timeout', 30000)
####
await c2.query('''
configure session set
session_idle_transaction_timeout :=
<duration>'40000000us'
''')
await assert_conf(
c1, 'session_idle_transaction_timeout', 20000)
await assert_conf(
t1, 'session_idle_transaction_timeout', 30000)
await assert_conf(
c2, 'session_idle_transaction_timeout', 40000)
####
await t1.query('''
configure session set
session_idle_transaction_timeout :=
<duration>'50 seconds'
''')
await assert_conf(
c1, 'session_idle_transaction_timeout', 20000)
await assert_conf(
t1, 'session_idle_transaction_timeout', 50000)
await assert_conf(
c2, 'session_idle_transaction_timeout', 40000)
####
await c1.query('''
configure instance set
session_idle_transaction_timeout :=
<duration>'15000 milliseconds'
''')
await c2.query('''
configure session reset
session_idle_transaction_timeout;
''')
await assert_conf(
c1, 'session_idle_transaction_timeout', 15000)
await assert_conf(
t1, 'session_idle_transaction_timeout', 50000)
await assert_conf(
t2, 'session_idle_transaction_timeout', 30000)
await assert_conf(
c2, 'session_idle_transaction_timeout', 15000)
####
await t1.query('''
configure session reset
session_idle_transaction_timeout;
''')
await assert_conf(
c1, 'session_idle_transaction_timeout', 15000)
await assert_conf(
t1, 'session_idle_transaction_timeout', 30000)
await assert_conf(
c2, 'session_idle_transaction_timeout', 15000)
####
await t2.query('''
configure current database reset
session_idle_transaction_timeout;
''')
await assert_conf(
c1, 'session_idle_transaction_timeout', 15000)
await assert_conf(
t1, 'session_idle_transaction_timeout', 15000)
await assert_conf(
t2, 'session_idle_transaction_timeout', 15000)
await assert_conf(
c2, 'session_idle_transaction_timeout', 15000)
####
cur_shared = await c1.query('''
select <str>cfg::Config.shared_buffers
''')
# not a test, just need to make sure our random value
# does not happen to be the Postgres' default.
assert cur_shared != ['20002KiB']
await c1.query('''
configure instance set
shared_buffers := <cfg::memory>'20002KiB'
''')
# shared_buffers requires a restart, so the value shouldn't
# change just yet
self.assertEqual(
await c1.query_single(f'''
select assert_single(<str>cfg::Config.shared_buffers)
'''),
cur_shared[0]
)
cur_eff = await c1.query_single('''
select assert_single(cfg::Config.effective_io_concurrency)
''')
await c1.query(f'''
configure instance set
effective_io_concurrency := {cur_eff}
''')
await c1.aclose()
await c2.aclose()
await t1.aclose()
async with tb.start_edgedb_server(
data_dir=tmpdir,
security=args.ServerSecurityMode.InsecureDevMode,
) as sd:
c1 = await sd.connect()
# check that the default was set correctly
await assert_conf(
c1, 'session_idle_transaction_timeout', 15000)
self.assertEqual(
await c1.query_single(f'''
select assert_single(<str>cfg::Config.shared_buffers)
'''),
'20002KiB'
)
await c1.aclose() | )
if isinstance(val, datetime.timedelta):
val //= datetime.timedelta(milliseconds=1)
self.assertEqual(
val,
expected_val
)
with tempfile.TemporaryDirectory() as tmpdir:
async with tb.start_edgedb_server(
data_dir=tmpdir,
security=args.ServerSecurityMode.InsecureDevMode,
) as sd:
c1 = await sd.connect()
c2 = await sd.connect()
await c2.query('create database test')
t1 = await sd.connect(database='test')
t2 = await sd.connect(database='test')
# check that the default was set correctly
await assert_conf(
c1, 'session_idle_transaction_timeout', 10000)
####
await c1.query( | test_server_config_backend_levels | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_idle_transaction(self):
from edb import protocol
async with tb.start_edgedb_server(
http_endpoint_security=args.ServerEndpointSecurityMode.Optional,
) as sd:
conn = await sd.connect_test_protocol()
query = '''
configure session set
session_idle_transaction_timeout :=
<duration>'1 second'
'''
await conn.send(
messages.Execute(
annotations=[],
command_text=query,
input_language=messages.InputLanguage.EDGEQL,
output_format=messages.OutputFormat.NONE,
expected_cardinality=messages.Cardinality.MANY,
allowed_capabilities=messages.Capability.ALL,
compilation_flags=messages.CompilationFlag(9),
implicit_limit=0,
input_typedesc_id=b'\0' * 16,
output_typedesc_id=b'\0' * 16,
state_typedesc_id=b'\0' * 16,
arguments=b'',
state_data=b'',
),
messages.Sync(),
)
state_msg = await conn.recv_match(messages.CommandComplete)
await conn.recv_match(messages.ReadyForCommand)
await conn.execute(
'''
start transaction
''',
state_id=state_msg.state_typedesc_id,
state=state_msg.state_data,
)
msg = await asyncio.wait_for(conn.recv_match(
protocol.ErrorResponse,
message='terminating connection due to '
'idle-in-transaction timeout'
), 8)
# Resolve error code before comparing for better error messages
errcls = errors.EdgeDBError.get_error_class_from_code(
msg.error_code)
self.assertEqual(errcls, errors.IdleTransactionTimeoutError)
with self.assertRaises((
edgedb.ClientConnectionFailedTemporarilyError,
edgedb.ClientConnectionClosedError,
)):
await conn.execute('''
select 1
''')
data = sd.fetch_metrics()
# Postgres: ERROR_IDLE_IN_TRANSACTION_TIMEOUT=25P03
self.assertRegex(
data,
r'\nedgedb_server_backend_connections_aborted_total' +
r'\{.*pgcode="25P03"\} 1.0\n',
) | await conn.send(
messages.Execute(
annotations=[],
command_text=query,
input_language=messages.InputLanguage.EDGEQL,
output_format=messages.OutputFormat.NONE,
expected_cardinality=messages.Cardinality.MANY,
allowed_capabilities=messages.Capability.ALL,
compilation_flags=messages.CompilationFlag(9),
implicit_limit=0,
input_typedesc_id=b'\0' * 16,
output_typedesc_id=b'\0' * 16,
state_typedesc_id=b'\0' * 16,
arguments=b'',
state_data=b'',
),
messages.Sync(),
)
state_msg = await conn.recv_match(messages.CommandComplete)
await conn.recv_match(messages.ReadyForCommand)
await conn.execute( | test_server_config_idle_transaction | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_query_timeout(self):
async with tb.start_edgedb_server(
http_endpoint_security=args.ServerEndpointSecurityMode.Optional,
) as sd:
conn = await sd.connect()
KEY = 'edgedb_server_backend_connections_aborted_total'
data = sd.fetch_metrics()
orig_aborted = 0.0
for line in data.split('\n'):
if line.startswith(KEY):
orig_aborted += float(line.split(' ')[1])
await conn.execute('''
configure session set
query_execution_timeout :=
<duration>'1 second'
''')
for _ in range(2):
with self.assertRaisesRegex(
edgedb.QueryError,
'canceling statement due to statement timeout'):
await conn.execute('''
select sys::_sleep(4)
''')
self.assertEqual(
await conn.query_single('select 42'),
42
)
await conn.aclose()
data = sd.fetch_metrics()
new_aborted = 0.0
for line in data.split('\n'):
if line.startswith(KEY):
new_aborted += float(line.split(' ')[1])
self.assertEqual(orig_aborted, new_aborted) | )
for _ in range(2):
with self.assertRaisesRegex(
edgedb.QueryError,
'canceling statement due to statement timeout'):
await conn.execute( | test_server_config_query_timeout | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_custom_enum(self):
async def assert_conf(con, name, expected_val):
val = await con.query_single(f'''
select assert_single(cfg::Config.{name})
''')
self.assertEqual(
str(val),
expected_val
)
async with tb.start_edgedb_server(
security=args.ServerSecurityMode.InsecureDevMode,
) as sd:
c1 = await sd.connect()
c2 = await sd.connect()
await c2.query('create database test')
t1 = await sd.connect(database='test')
# check that the default was set correctly
await assert_conf(
c1, '__check_function_bodies', 'Enabled')
####
await c1.query('''
configure instance set
__check_function_bodies
:= cfg::TestEnabledDisabledEnum.Disabled;
''')
for c in {c1, c2, t1}:
await assert_conf(
c, '__check_function_bodies', 'Disabled')
####
await t1.query('''
configure current database set
__check_function_bodies :=
cfg::TestEnabledDisabledEnum.Enabled;
''')
for c in {c1, c2}:
await assert_conf(
c, '__check_function_bodies', 'Disabled')
await assert_conf(
t1, '__check_function_bodies', 'Enabled')
####
await c2.query('''
configure session set
__check_function_bodies :=
cfg::TestEnabledDisabledEnum.Disabled;
''')
await assert_conf(
c1, '__check_function_bodies', 'Disabled')
await assert_conf(
t1, '__check_function_bodies', 'Enabled')
await assert_conf(
c2, '__check_function_bodies', 'Disabled')
####
await c1.query('''
configure instance reset
__check_function_bodies;
''')
await t1.query('''
configure session set
__check_function_bodies :=
cfg::TestEnabledDisabledEnum.Disabled;
''')
await assert_conf(
c1, '__check_function_bodies', 'Enabled')
await assert_conf(
t1, '__check_function_bodies', 'Disabled')
await assert_conf(
c2, '__check_function_bodies', 'Disabled')
await c1.aclose()
await c2.aclose()
await t1.aclose() | )
self.assertEqual(
str(val),
expected_val
)
async with tb.start_edgedb_server(
security=args.ServerSecurityMode.InsecureDevMode,
) as sd:
c1 = await sd.connect()
c2 = await sd.connect()
await c2.query('create database test')
t1 = await sd.connect(database='test')
# check that the default was set correctly
await assert_conf(
c1, '__check_function_bodies', 'Enabled')
####
await c1.query( | test_server_config_custom_enum | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_config_file_05(self):
class Prop(enum.Enum):
One = "One"
Two = "Two"
Three = "Three"
conf = textwrap.dedent('''
["cfg::Config"]
enumprop = "One"
''')
async with tb.temp_file_with(
conf.encode()
) as config_file, tb.start_edgedb_server(
config_file=config_file.name,
) as sd:
conn = await sd.connect()
try:
self.assertEqual(
await conn.query_single("""\
select assert_single(
cfg::Config.enumprop)
"""),
Prop.One,
)
config_file.seek(0)
config_file.truncate()
config_file.write(textwrap.dedent('''
["cfg::Config"]
enumprop = "Three"
''').encode())
config_file.flush()
os.kill(sd.pid, signal.SIGHUP)
async for tr in self.try_until_succeeds(ignore=AssertionError):
async with tr:
self.assertEqual(
await conn.query_single("""\
select assert_single(
cfg::Config.enumprop)
"""),
Prop.Three,
)
finally:
await conn.aclose() | )
async with tb.temp_file_with(
conf.encode()
) as config_file, tb.start_edgedb_server(
config_file=config_file.name,
) as sd:
conn = await sd.connect()
try:
self.assertEqual(
await conn.query_single("""\
select assert_single(
cfg::Config.enumprop)
"""),
Prop.One,
)
config_file.seek(0)
config_file.truncate()
config_file.write(textwrap.dedent( | test_server_config_file_05 | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def test_server_dynamic_system_config(self):
async with tb.start_edgedb_server(
extra_args=["--disable-dynamic-system-config"]
) as sd:
conn = await sd.connect()
try:
conf, sess = await conn.query_single('''
SELECT (
cfg::Config.__internal_testvalue,
cfg::Config.__internal_sess_testvalue
) LIMIT 1
''')
with self.assertRaisesRegex(
edgedb.ConfigurationError, "cannot change"
):
await conn.query(f'''
CONFIGURE INSTANCE
SET __internal_testvalue := {conf + 1};
''')
await conn.query(f'''
CONFIGURE INSTANCE
SET __internal_sess_testvalue := {sess + 1};
''')
conf2, sess2 = await conn.query_single('''
SELECT (
cfg::Config.__internal_testvalue,
cfg::Config.__internal_sess_testvalue
) LIMIT 1
''')
self.assertEqual(conf, conf2)
self.assertEqual(sess + 1, sess2)
finally:
await conn.aclose() | )
with self.assertRaisesRegex(
edgedb.ConfigurationError, "cannot change"
):
await conn.query(f | test_server_dynamic_system_config | python | geldata/gel | tests/test_server_config.py | https://github.com/geldata/gel/blob/master/tests/test_server_config.py | Apache-2.0 |
async def _ensure_schema_integrity(self):
# Check that index exists
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
indexes: {
expr,
},
properties: {
name,
default,
} FILTER .name != 'id',
} FILTER .name = 'default::Łukasz';
''',
[
{
'name': 'default::Łukasz',
'indexes': [{
'expr': '.`Ł🤞`'
}],
}
]
)
# Check that scalar types exist
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT (
SELECT ScalarType {
name,
} FILTER .name LIKE 'default%'
).name;
''',
{
'default::你好',
'default::مرحبا',
'default::🚀🚀🚀',
}
)
# Check that abstract constraint exists
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT Constraint {
name,
} FILTER .name LIKE 'default%' AND .abstract;
''',
[
{'name': 'default::🚀🍿'},
]
)
# Check that abstract constraint was applied properly
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT Constraint {
name,
params: {
@value
} FILTER .num > 0
}
FILTER
.name = 'default::🚀🍿' AND
NOT .abstract AND
Constraint.<constraints[IS ScalarType].name =
'default::🚀🚀🚀';
''',
[
{
'name': 'default::🚀🍿',
'params': [
{'@value': '100'}
]
},
]
) | ,
[
{
'name': 'default::Łukasz',
'indexes': [{
'expr': '.`Ł🤞`'
}],
}
]
)
# Check that scalar types exist
await self.assert_query_result(
r | _ensure_schema_integrity | python | geldata/gel | tests/test_dump02.py | https://github.com/geldata/gel/blob/master/tests/test_dump02.py | Apache-2.0 |
async def _ensure_data_integrity(self):
await self.assert_query_result(
r'''
SELECT A {
`s p A m 🤞`: {
`🚀`,
c100,
c101 := `💯`(`🙀` := .`🚀` + 1)
}
}
''',
[
{
's p A m 🤞': {
'🚀': 42,
'c100': 58,
'c101': 57,
}
}
]
)
await self.assert_query_result(
r'''
SELECT Łukasz {
`Ł🤞`,
`Ł💯`: {
@`🙀🚀🚀🚀🙀`,
@`🙀مرحبا🙀`,
`s p A m 🤞`: {
`🚀`,
c100,
c101 := `💯`(`🙀` := .`🚀` + 1)
}
}
} ORDER BY .`Ł💯` EMPTY LAST
''',
[
{
'Ł🤞': 'simple 🚀',
'Ł💯': {
'@🙀🚀🚀🚀🙀': None,
'@🙀مرحبا🙀': None,
's p A m 🤞': {
'🚀': 42,
'c100': 58,
'c101': 57,
}
}
},
{
'Ł🤞': '你好🤞',
'Ł💯': None,
},
]
)
await self.assert_query_result(
r'''
SELECT `💯💯💯`::`🚀🙀🚀`('Łink prop 🙀مرحبا🙀');
''',
[
'Łink prop 🙀مرحبا🙀Ł🙀',
]
)
# Check that annotation exists
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT Function {
name,
annotations: {
name,
@value
},
} FILTER .name = 'default::💯';
''',
[
{
'name': 'default::💯',
'annotations': [{
'name': 'default::🍿',
'@value': 'fun!🚀',
}]
}
]
)
# Check the default value
await self.con.execute(r'INSERT Łukasz')
await self.assert_query_result(
r'''
SELECT Łukasz {
`Ł🤞`,
} FILTER NOT EXISTS .`Ł💯`;
''',
[
# We had one before and expect one more now.
{'Ł🤞': '你好🤞'},
{'Ł🤞': '你好🤞'},
]
)
await self.assert_query_result(
r'''
SELECT count(schema::Migration) >= 2
''',
[True],
) | ,
[
{
's p A m 🤞': {
'🚀': 42,
'c100': 58,
'c101': 57,
}
}
]
)
await self.assert_query_result(
r | _ensure_data_integrity | python | geldata/gel | tests/test_dump02.py | https://github.com/geldata/gel/blob/master/tests/test_dump02.py | Apache-2.0 |
async def test_edgeql_filter_flow01(self):
await self.assert_query_result(
r'''
SELECT Issue.number
FILTER TRUE
ORDER BY Issue.number;
''',
['1', '2', '3', '4'],
)
await self.assert_query_result(
r'''
SELECT Issue.number
# obviously irrelevant filter, simply equivalent to TRUE
FILTER Status.name = 'Closed'
ORDER BY Issue.number;
''',
['1', '2', '3', '4'],
) | ,
['1', '2', '3', '4'],
)
await self.assert_query_result(
r | test_edgeql_filter_flow01 | python | geldata/gel | tests/test_edgeql_filter.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_filter.py | Apache-2.0 |
async def test_edgeql_filter_flow02(self):
await self.assert_query_result(
r'''
SELECT Issue.number
FILTER FALSE
ORDER BY Issue.number;
''',
[],
)
await self.assert_query_result(
r'''
SELECT Issue.number
# obviously irrelevant filter, simply equivalent to FALSE
FILTER Status.name = 'XXX'
ORDER BY Issue.number;
''',
[],
) | ,
[],
)
await self.assert_query_result(
r | test_edgeql_filter_flow02 | python | geldata/gel | tests/test_edgeql_filter.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_filter.py | Apache-2.0 |
async def test_edgeql_filter_flow03(self):
await self.assert_query_result(
r'''
# base line for a cross product
SELECT _ := Issue.number ++ Status.name
ORDER BY _;
''',
[
'1Closed', '1Open',
'2Closed', '2Open',
'3Closed', '3Open',
'4Closed', '4Open',
]
)
await self.assert_query_result(
r'''
# interaction of filter and cross product
SELECT _ := (
SELECT Issue
FILTER Issue.owner.name = 'Elvis'
).number ++ Status.name
ORDER BY _;
''',
['1Closed', '1Open', '2Closed', '2Open'],
)
await self.assert_query_result(
r'''
SELECT _ := (
SELECT Issue
FILTER Issue.owner.name = 'Elvis'
).number ++ Status.name
FILTER
# this FILTER is legal, but irrelevant, the same way as
# SELECT
# Issue.number + Status.name FILTER Status.name = 'Open'
Status.name = 'Open'
ORDER BY _;
''',
['1Closed', '1Open', '2Closed', '2Open'],
) | ,
[
'1Closed', '1Open',
'2Closed', '2Open',
'3Closed', '3Open',
'4Closed', '4Open',
]
)
await self.assert_query_result(
r | test_edgeql_filter_flow03 | python | geldata/gel | tests/test_edgeql_filter.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_filter.py | Apache-2.0 |
async def test_edgeql_filter_empty02(self):
await self.assert_query_result(
r"""
# the FILTER clause evaluates to empty, so it can never be true
SELECT Issue{number}
FILTER Issue.number = <str>{};
""",
[],
)
await self.assert_query_result(
r"""
SELECT Issue{number}
FILTER Issue.priority = <Object>{};
""",
[],
)
await self.assert_query_result(
r"""
SELECT Issue{number}
FILTER Issue.priority.name = <str>{};
""",
[],
) | ,
[],
)
await self.assert_query_result(
r | test_edgeql_filter_empty02 | python | geldata/gel | tests/test_edgeql_filter.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_filter.py | Apache-2.0 |
async def test_edgeql_filter_aggregate04(self):
await self.assert_query_result(
r'''
SELECT count(Issue)
# this filter is not related to the aggregate and is allowed
#
FILTER Status.name = 'Open';
''',
[4],
)
await self.assert_query_result(
r'''
SELECT count(Issue)
# this filter is conceptually equivalent to the above
FILTER TRUE;
''',
[4],
) | ,
[4],
)
await self.assert_query_result(
r | test_edgeql_filter_aggregate04 | python | geldata/gel | tests/test_edgeql_filter.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_filter.py | Apache-2.0 |
async def test_edgeql_filter_aggregate06(self):
await self.assert_query_result(
r'''
# regardless of what count evaluates to, FILTER clause is
# impossible to fulfill, so the result is empty
SELECT count(Issue)
FILTER FALSE;
''',
[],
)
await self.assert_query_result(
r'''
SELECT count(Issue)
FILTER {};
''',
[],
) | ,
[],
)
await self.assert_query_result(
r | test_edgeql_filter_aggregate06 | python | geldata/gel | tests/test_edgeql_filter.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_filter.py | Apache-2.0 |
async def test_pgdump02_dump_restore_04(self):
eqlres = await self.con.query('''
select D {
id,
num,
single_link: {*},
multi_link: {*}
}
order by .id
''')
sql = f'''
SELECT
id,
num,
{self.single_link_subquery("D", "single_link", "C")},
{self.multi_link_subquery("D", "multi_link", "C")}
FROM "D"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres) | )
sql = f | test_pgdump02_dump_restore_04 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_pgdump02_dump_restore_05(self):
eqlres = await self.con.query('''
select E {
id,
num,
_single_link := .single_link {
source := E.id,
lp0 := @lp0,
target := .id,
},
_multi_link := .multi_link {
source := E.id,
lp1 := @lp1,
target := .id,
},
}
order by .id
''')
sql = f'''
SELECT
id,
num,
{self.single_link_subquery("E", "single_link", "C", ["lp0"])},
{self.multi_link_subquery("E", "multi_link", "C", ["lp1"])}
FROM "E"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres) | )
sql = f | test_pgdump02_dump_restore_05 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_pgdump02_dump_restore_06(self):
eqlres = await self.con.query('''
select F {
id,
num,
single_link: {*},
multi_link: {*}
}
order by .id
''')
sql = f'''
SELECT
id,
num,
{self.single_link_subquery("F", "single_link", "C")},
{self.multi_link_subquery("F", "multi_link", "C")}
FROM "F"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres) | )
sql = f | test_pgdump02_dump_restore_06 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_pgdump02_dump_restore_12(self):
eqlres = await self.con.query('''
select X {
id,
name,
y: {*},
}
order by .id
''')
sql = f'''
SELECT
id,
name,
{self.single_link_subquery("X", "y", "Y")}
FROM "X"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres)
eqlres = await self.con.query('''
select Y {
id,
name,
x: {*},
}
order by .id
''')
sql = f'''
SELECT
id,
name,
{self.single_link_subquery("Y", "x", "X")}
FROM "Y"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres) | )
sql = f | test_pgdump02_dump_restore_12 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_pgdump02_dump_restore_13(self):
# We're using this type later, so we want to validate its integrity.
eqlres = await self.con.query('select K {*}')
sqlres = await self.scon.fetch('SELECT * FROM "K"')
self.assert_shape(sqlres, eqlres)
# Emulating shapes with union types is messy in SQL and unnecessary
# for validating the data as the individual types have been validated
# in earlier tests.
eqlres = await self.con.query('''
select Z {
id,
ck_id := .ck.id,
stw_ids := (select .stw order by <str>.id).id
}
order by .id
''')
sqlres = await self.scon.fetch(f'''
SELECT
id,
ck_id,
(
SELECT array_agg(x.target ORDER BY x.target::text)
FROM "Z.stw" x
WHERE x.source = "Z".id
) as stw_ids
FROM "Z"
ORDER BY id
''')
self.assert_shape(sqlres, eqlres) | )
sqlres = await self.scon.fetch(f | test_pgdump02_dump_restore_13 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_pgdump03_dump_restore_04(self):
eqlres = await self.con.query('''
select Łukasz {
id,
`Ł🤞`,
`_Ł💯` := .`Ł💯` {
source := Łukasz.id,
`🙀🚀🚀🚀🙀` := @`🙀🚀🚀🚀🙀`,
`🙀مرحبا🙀` := @`🙀مرحبا🙀`,
target := .id,
},
}
order by .id
''')
subquery = self.single_link_subquery(
"Łukasz", "Ł💯", "A", ["🙀🚀🚀🚀🙀", "🙀مرحبا🙀"])
sql = f'''
SELECT
id,
"Ł🤞",
{subquery}
FROM "Łukasz"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres) | )
subquery = self.single_link_subquery(
"Łukasz", "Ł💯", "A", ["🙀🚀🚀🚀🙀", "🙀مرحبا🙀"])
sql = f | test_pgdump03_dump_restore_04 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_pgdump05_dump_restore_03(self):
eqlres = await self.con.query('select TargetA {*} order by .id')
sqlres = await self.scon.fetch('SELECT * FROM "TargetA" ORDER BY id')
self.assert_shape(sqlres, eqlres)
eqlres = await self.con.query('''
select SourceA {
id,
name,
link1: {*},
link2: {*},
}
order by .id
''')
sql = f'''
SELECT
id,
name,
{self.single_link_subquery("SourceA", "link1", "TargetA")},
{self.single_link_subquery("SourceA", "link2", "TargetA")}
FROM "SourceA"
ORDER BY id
'''
sqlres = await self.scon.fetch(sql)
self.assert_shape(sqlres, eqlres) | )
sql = f | test_pgdump05_dump_restore_03 | python | geldata/gel | tests/test_pg_dump.py | https://github.com/geldata/gel/blob/master/tests/test_pg_dump.py | Apache-2.0 |
async def test_sql_query_00(self):
# basic
res = await self.squery_values(
'''
SELECT title FROM "Movie" order by title
'''
)
self.assertEqual(res, [['Forrest Gump'], ['Saving Private Ryan']]) | SELECT title FROM "Movie" order by title | test_sql_query_00 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_01(self):
# table alias
res = await self.scon.fetch(
'''
SELECT mve.title, mve.release_year, director_id FROM "Movie" as mve
'''
)
self.assert_shape(res, 2, 3) | SELECT mve.title, mve.release_year, director_id FROM "Movie" as mve | test_sql_query_01 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_02(self):
# SELECT FROM parent type
res = await self.scon.fetch(
'''
SELECT * FROM "Content"
'''
)
self.assert_shape(res, 5, ['id', '__type__', 'genre_id', 'title']) | SELECT * FROM "Content" | test_sql_query_02 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_03(self):
# SELECT FROM parent type only
res = await self.scon.fetch(
'''
SELECT * FROM ONLY "Content" -- should have only one result
'''
)
self.assert_shape(res, 1, ['id', '__type__', 'genre_id', 'title']) | SELECT * FROM ONLY "Content" -- should have only one result | test_sql_query_03 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_04(self):
# multiple FROMs
res = await self.scon.fetch(
'''
SELECT mve.title, "Person".first_name
FROM "Movie" mve, "Person" WHERE mve.director_id = "Person".id
'''
)
self.assert_shape(res, 1, ['title', 'first_name']) | SELECT mve.title, "Person".first_name
FROM "Movie" mve, "Person" WHERE mve.director_id = "Person".id | test_sql_query_04 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_05(self):
res = await self.scon.fetch(
'''
SeLeCt mve.title as tiT, perSon.first_name
FROM "Movie" mve, "Person" person
'''
)
self.assert_shape(res, 6, ['tit', 'first_name']) | SeLeCt mve.title as tiT, perSon.first_name
FROM "Movie" mve, "Person" person | test_sql_query_05 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_06(self):
# sub relations
res = await self.scon.fetch(
'''
SELECT id, title, prS.first_name
FROM "Movie" mve, (SELECT first_name FROM "Person") prs
'''
)
self.assert_shape(res, 6, ['id', 'title', 'first_name']) | SELECT id, title, prS.first_name
FROM "Movie" mve, (SELECT first_name FROM "Person") prs | test_sql_query_06 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_07(self):
# quoted case sensitive
res = await self.scon.fetch(
'''
SELECT tItLe, release_year "RL year" FROM "Movie" ORDER BY titLe;
'''
)
self.assert_shape(res, 2, ['title', 'RL year']) | SELECT tItLe, release_year "RL year" FROM "Movie" ORDER BY titLe; | test_sql_query_07 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_08(self):
# JOIN
res = await self.scon.fetch(
'''
SELECT "Movie".id, "Genre".id
FROM "Movie" JOIN "Genre" ON "Movie".genre_id = "Genre".id
'''
)
self.assert_shape(res, 2, ['id', 'col~1']) | SELECT "Movie".id, "Genre".id
FROM "Movie" JOIN "Genre" ON "Movie".genre_id = "Genre".id | test_sql_query_08 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_09(self):
# resolve columns without table names
res = await self.scon.fetch(
'''
SELECT "Movie".id, title, name
FROM "Movie" JOIN "Genre" ON "Movie".genre_id = "Genre".id
'''
)
self.assert_shape(res, 2, ['id', 'title', 'name']) | SELECT "Movie".id, title, name
FROM "Movie" JOIN "Genre" ON "Movie".genre_id = "Genre".id | test_sql_query_09 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_10(self):
# wildcard SELECT
res = await self.scon.fetch(
'''
SELECT m.* FROM "Movie" m
'''
)
self.assert_shape(
res,
2,
[
'id',
'__type__',
'director_id',
'genre_id',
'release_year',
'title',
],
) | SELECT m.* FROM "Movie" m | test_sql_query_10 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_11(self):
# multiple wildcard SELECT
res = await self.scon.fetch(
'''
SELECT * FROM "Movie"
JOIN "Genre" g ON "Movie".genre_id = g.id
'''
)
self.assert_shape(
res,
2,
[
'id',
'__type__',
'director_id',
'genre_id',
'release_year',
'title',
'g_id',
'g___type__',
'name',
],
) | SELECT * FROM "Movie"
JOIN "Genre" g ON "Movie".genre_id = g.id | test_sql_query_11 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_12(self):
# JOIN USING
res = await self.scon.fetch(
'''
SELECT * FROM "Movie"
JOIN (SELECT id as genre_id, name FROM "Genre") g USING (genre_id)
'''
)
self.assert_shape(res, 2, 8) | SELECT * FROM "Movie"
JOIN (SELECT id as genre_id, name FROM "Genre") g USING (genre_id) | test_sql_query_12 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_13(self):
# CTE
res = await self.scon.fetch(
'''
WITH g AS (SELECT id as genre_id, name FROM "Genre")
SELECT * FROM "Movie" JOIN g USING (genre_id)
'''
)
self.assert_shape(res, 2, 8) | WITH g AS (SELECT id as genre_id, name FROM "Genre")
SELECT * FROM "Movie" JOIN g USING (genre_id) | test_sql_query_13 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_14(self):
# CASE
res = await self.squery_values(
'''
SELECT title, CASE WHEN title='Forrest Gump' THEN 'forest'
WHEN title='Saving Private Ryan' THEN 'the war film'
ELSE 'unknown' END AS nick_name FROM "Movie"
'''
)
self.assertEqual(
res,
[
['Forrest Gump', 'forest'],
['Saving Private Ryan', 'the war film'],
],
) | SELECT title, CASE WHEN title='Forrest Gump' THEN 'forest'
WHEN title='Saving Private Ryan' THEN 'the war film'
ELSE 'unknown' END AS nick_name FROM "Movie" | test_sql_query_14 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_15(self):
# UNION
res = await self.scon.fetch(
'''
SELECT id, title FROM "Movie" UNION SELECT id, title FROM "Book"
'''
)
self.assert_shape(res, 4, 2) | SELECT id, title FROM "Movie" UNION SELECT id, title FROM "Book" | test_sql_query_15 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_16(self):
# casting
res = await self.scon.fetch(
'''
SELECT 1::bigint, 'accbf276-705b-11e7-b8e4-0242ac120002'::UUID
'''
)
self.assert_shape(res, 1, 2) | SELECT 1::bigint, 'accbf276-705b-11e7-b8e4-0242ac120002'::UUID | test_sql_query_16 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_17(self):
# ORDER BY
res = await self.squery_values(
'''
SELECT first_name, last_name
FROM "Person" ORDER BY last_name DESC NULLS FIRST
'''
)
self.assertEqual(
res, [['Robin', None], ['Steven', 'Spielberg'], ['Tom', 'Hanks']]
)
res = await self.squery_values(
'''
SELECT first_name, last_name
FROM "Person" ORDER BY last_name DESC NULLS LAST
'''
)
self.assertEqual(
res, [['Steven', 'Spielberg'], ['Tom', 'Hanks'], ['Robin', None]]
) | SELECT first_name, last_name
FROM "Person" ORDER BY last_name DESC NULLS FIRST | test_sql_query_17 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_18(self):
# LIMIT & OFFSET
res = await self.squery_values(
'''
SELECT title FROM "Content" ORDER BY title OFFSET 1 LIMIT 2
'''
)
self.assertEqual(res, [['Forrest Gump'], ['Halo 3']]) | SELECT title FROM "Content" ORDER BY title OFFSET 1 LIMIT 2 | test_sql_query_18 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_19(self):
# DISTINCT
res = await self.squery_values(
'''
SELECT DISTINCT name
FROM "Content" c JOIN "Genre" g ON (c.genre_id = g.id)
ORDER BY name
'''
)
self.assertEqual(res, [['Drama'], ['Fiction']])
res = await self.squery_values(
'''
SELECT DISTINCT ON (name) name, title
FROM "Content" c JOIN "Genre" g ON (c.genre_id = g.id)
ORDER BY name, title
'''
)
self.assertEqual(
res,
[['Drama', 'Forrest Gump'], ['Fiction', 'Chronicles of Narnia']],
) | SELECT DISTINCT name
FROM "Content" c JOIN "Genre" g ON (c.genre_id = g.id)
ORDER BY name | test_sql_query_19 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_20(self):
# WHERE
res = await self.squery_values(
'''
SELECT first_name FROM "Person"
WHERE last_name IS NOT NULL AND LENGTH(first_name) < 4
'''
)
self.assertEqual(res, [['Tom']]) | SELECT first_name FROM "Person"
WHERE last_name IS NOT NULL AND LENGTH(first_name) < 4 | test_sql_query_20 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_21(self):
# window functions
res = await self.squery_values(
'''
WITH content AS (
SELECT c.id, c.title, pages
FROM "Content" c LEFT JOIN "Book" USING(id)
),
content2 AS (
SELECT id, COALESCE(pages, 0) as pages FROM content
)
SELECT pages, sum(pages) OVER (ORDER BY pages)
FROM content2 ORDER BY pages DESC
'''
)
self.assertEqual(
res,
[[374, 580], [206, 206], [0, 0], [0, 0], [0, 0]],
) | WITH content AS (
SELECT c.id, c.title, pages
FROM "Content" c LEFT JOIN "Book" USING(id)
),
content2 AS (
SELECT id, COALESCE(pages, 0) as pages FROM content
)
SELECT pages, sum(pages) OVER (ORDER BY pages)
FROM content2 ORDER BY pages DESC | test_sql_query_21 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_22(self):
# IS NULL/true
res = await self.scon.fetch(
'''
SELECT id FROM "Person" WHERE last_name IS NULL
'''
)
self.assert_shape(res, 1, 1)
res = await self.scon.fetch(
'''
SELECT id FROM "Person" WHERE (last_name = 'Hanks') IS NOT TRUE
'''
)
self.assert_shape(res, 2, 1) | SELECT id FROM "Person" WHERE last_name IS NULL | test_sql_query_22 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_23(self):
# ImplicitRow
res = await self.scon.fetch(
'''
SELECT id FROM "Person"
WHERE (first_name, last_name) IN (
('Tom', 'Hanks'), ('Steven', 'Spielberg')
)
'''
)
self.assert_shape(res, 2, 1) | SELECT id FROM "Person"
WHERE (first_name, last_name) IN (
('Tom', 'Hanks'), ('Steven', 'Spielberg')
) | test_sql_query_23 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_24(self):
# SubLink
res = await self.squery_values(
'''
SELECT title FROM "Movie" WHERE id IN (
SELECT id FROM "Movie" ORDER BY title LIMIT 1
)
'''
)
self.assertEqual(res, [['Forrest Gump']])
res = await self.squery_values(
'''
SELECT (SELECT title FROM "Movie" ORDER BY title LIMIT 1)
'''
)
self.assertEqual(res, [['Forrest Gump']]) | SELECT title FROM "Movie" WHERE id IN (
SELECT id FROM "Movie" ORDER BY title LIMIT 1
) | test_sql_query_24 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_27(self):
# FROM LATERAL
await self.scon.fetch(
'''
SELECT name, title
FROM "Movie" m, LATERAL (
SELECT g.name FROM "Genre" g WHERE m.genre_id = g.id
) t
ORDER BY title
'''
) | SELECT name, title
FROM "Movie" m, LATERAL (
SELECT g.name FROM "Genre" g WHERE m.genre_id = g.id
) t
ORDER BY title | test_sql_query_27 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_28(self):
# JOIN LATERAL
res = await self.scon.fetch(
'''
SELECT name, title
FROM "Movie" m CROSS JOIN LATERAL (
SELECT g.name FROM "Genre" g WHERE m.genre_id = g.id
) t
ORDER BY title
'''
)
self.assert_shape(res, 2, ['name', 'title']) | SELECT name, title
FROM "Movie" m CROSS JOIN LATERAL (
SELECT g.name FROM "Genre" g WHERE m.genre_id = g.id
) t
ORDER BY title | test_sql_query_28 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_30(self):
# VALUES
res = await self.scon.fetch(
'''
SELECT * FROM (VALUES (1, 2), (3, 4)) AS vals(c, d)
'''
)
self.assert_shape(res, 2, ['c', 'd'])
with self.assertRaisesRegex(
asyncpg.InvalidColumnReferenceError,
", but the query resolves to 2 columns",
# this points to `1`, because libpg_query does not give better info
position="41",
):
await self.scon.fetch(
'''
SELECT * FROM (VALUES (1, 2), (3, 4)) AS vals(c, d, e)
'''
) | SELECT * FROM (VALUES (1, 2), (3, 4)) AS vals(c, d) | test_sql_query_30 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
async def test_sql_query_31(self):
# column aliases in CTEs
res = await self.scon.fetch(
'''
with common as (SELECT 1 a, 2 b)
SELECT * FROM common
'''
)
self.assert_shape(res, 1, ['a', 'b'])
res = await self.scon.fetch(
'''
with common(c, d) as (SELECT 1 a, 2 b)
SELECT * FROM common
'''
)
self.assert_shape(res, 1, ['c', 'd'])
res = await self.scon.fetch(
'''
with common(c, d) as (SELECT 1 a, 2 b)
SELECT * FROM common as cmn(e, f)
'''
)
self.assert_shape(res, 1, ['e', 'f'])
with self.assertRaisesRegex(
asyncpg.InvalidColumnReferenceError, "query resolves to 2"
):
await self.scon.fetch(
'''
with common(c, d) as (SELECT 1 a, 2 b)
SELECT * FROM common as cmn(e, f, g)
'''
) | with common as (SELECT 1 a, 2 b)
SELECT * FROM common | test_sql_query_31 | python | geldata/gel | tests/test_sql_query.py | https://github.com/geldata/gel/blob/master/tests/test_sql_query.py | Apache-2.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.