Search code examples
databasesurrealdb

Calling function with multi argument on surrealdb


I want to define function in surrealdb to be able to call it later.

Why calling this function (fn::insert_user(...);) fails?

Table:

DEFINE TABLE user SCHEMAFULL;

DEFINE FIELD email ON TABLE user TYPE string
    ASSERT $value != NONE AND is::email($value);

DEFINE INDEX email_unique_index ON TABLE user COLUMNS email UNIQUE;

DEFINE FIELD username ON TABLE user TYPE string;

DEFINE INDEX username_unique_index ON TABLE user COLUMNS username UNIQUE;

DEFINE FIELD name ON TABLE user TYPE string;

DEFINE FIELD hash ON TABLE user TYPE string
    ASSERT $value != NONE;

DEFINE FIELD created_at ON TABLE user TYPE datetime
    ASSERT $value != NONE;

Function:

DEFINE FUNCTION fn::insert_user(
    $email: string,
    $username: string,
    $hash: string,
    $name: string
) {
    RETURN INSERT INTO user {
        email: $email,
        username: $username,
        hash: $hash,
        name: $name,
        created_at: time::now()
    };
};

Calling the function:

RETURN fn::insert_user('[email protected]', 'user0', 'hash', 'name');

The error:

There was a problem with the database: Failed to deserialize a binary response: unknown variant Database index email_unique_indexalready contains '[email protected]', with recorduser:hz34bz2kroymoryx1sld``, expected one of None, Null, False, True, Number, Strand, Duration, Datetime, Uuid, Array, Object, Geometry, Bytes, Param, Idiom, Table, Thing, Model, Regex, Block, Range, Edges, Future, Constant, Function, Subquery, Expression

Keep in mind that the user table is empty.


Solution

  • There might be more than one thing going on here, but the main reason the custom function fails is that custom functions have not been able to write data, only read.

    This has been fixed in the nightly branch and will come in the next release.