How can I programmatically restrict node access? I'm using Drupal 8 with the nodeaccess module.

I'm able to set the node grants with the form.

I also have a custom module which imports new nodes. These new nodes should be shown only to certain users.

I know I can insert the corresponding lines into the database tables nodeaccess and node_access. But this might be not consistent.

Is there a way to set the nodeaccess programmatically?
I use a function to build the database rows in node_access and nodeaccess:

  private function set_node_access($nid, $id, $realm='nodeaccess_uid', $view=1, $update=0, $delete=0)
  {
    // ksm("nid: $nid uid: $uid");
    $connection = \Drupal::database();
    $sql = "INSERT INTO nodeaccess (nid, gid, realm, grant_view, grant_update, grant_delete) 
            VALUES($nid,$id,'$realm',$view,$update,$delete) 
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete)";
    $connection-&gt;query($sql);
    $sql = "INSERT INTO node_access(nid, langcode, fallback, gid, realm, grant_view, grant_update, grant_delete) 
            VALUES($nid,'de', 1, $id,'$realm',$view,$update,$delete) 
            ON DUPLICATE KEY UPDATE grant_view=VALUES(grant_view), grant_update=VALUES(grant_update), grant_delete=VALUES(grant_delete);";
    $connection-&gt;query($sql);
  }


That's not the nice way, but it works for me.