all files / src/ database.js

95.29% Statements 283/297
72.41% Branches 42/58
98.48% Functions 65/66
95.27% Lines 282/296
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 9071× 1× 1× 1×       1× 1974× 1× 1× 1×                                           1×                 1×                   1×                 1×                   1× 8×   8× 2× 2×   6× 6×         5× 1× 1× 1× 1×     5× 5×   4× 4× 4×                   1× 1× 1×       1× 1× 1×       8×                       1× 4× 4× 3× 3×   4× 4×                   1×                     1× 1088× 1085×   3×                   1× 1083× 1083× 1× 1×   1082×                       1× 4× 4×                     1× 4×   4×                   1× 6× 6×                   1× 4× 3×   1×         1× 1× 1×           1× 1× 1× 1×   1×   1×                         1× 307× 307× 307× 307× 307× 307× 2×     2× 2×               2×   1× 1× 1× 1× 1× 1×             2× 4× 4×           307×     307× 307× 307× 307×   307×     307×   307×                       1×   308× 308×     308× 308× 308× 308×   308×   308×     1× 58× 58×       58× 58× 58× 58×   58×   58×               1× 7× 7×                   7× 7× 7× 7×   7×     7×   7×                   1× 307× 307×         307× 307× 307×   307×   307×         307×         307×         307×     307× 307×                                     1× 7× 7× 7× 7×             7× 7× 7× 7×   7×       1× 1× 1×                   1× 1× 1× 1×   1×                           1× 2× 2× 2×       2× 1×         1×     1× 1×         1× 1×           1× 1×                                 1× 5× 5×       5× 5× 5× 6×   5×   5×                           1× 1× 1×         1× 1× 1× 1×   1×   1×                 1× 1× 1×   1× 1× 1× 5×   1×   1×                             1×   25×     25× 25× 25×           25×       25× 25× 2× 1× 1×     24×   25×                             1× 1× 1×                 1× 1×   1×                                 1× 20× 20× 20×                     20× 20×   20×                                                   1×   1× 1×                         1× 1× 1× 3×   1×   1×                   1× 1× 1×                               1× 1× 1× 1×   1×   1×               1× 1× 1×               1× 1× 1× 4×   1×   1×                             1× 2× 2×   2× 2×               2× 2×               2× 2× 2× 38×   2×   2×                           1× 2× 2×   2× 2×                 2× 2× 2× 6×   2×     2×     1×
var neo4j = require('neo4j-driver').v1;
var utils = require('./utils');
var log = require('electron-log');
var parse = require('exif-date').parse;
 
//var config = require('../config.json');
 
function log_error_and_close_session(session) {
    return function(err) {
        log.error(err);
        session.close();
        return err;
    }
}
 
/**
* Database wrapper functions for Neo4J
*
* @module Database
* @requires neo4j-driver
*/
 
/**
 *
 * Database
 * --------
 * Contains all the database access methods
 * <br>
 * <b>Caution: The responses are promises</b>
 * <p>Singleton because...</p>
*
 * @class Database
*/
var Database = Database || {};
 
/**
 * The development flag controls the basic auth credentials
 *
 * @property development
 * @type {boolean}
 * @default false
 */
Database.development = false;
 
/**
 * Stores the neo4j-driver for the method <_get_driver>
 *
 * @property _driver
 * @type {driver}
 * @private
 * @default null
 */
Database._driver = null;
 
/**
 * Stores whether a successful login took place
 *
 * @property _logged_in
 * @type {boolean}
 * @default false
 */
Database.logged_in = false;
 
/**
* Try to fetch a neo4j driver with the given credentials
 * if that works, the Database._driver is not null anymore.
 * It also set the Database.logged_in to true
 *
* @method login
* @return {boolean|error}
*/
Database.login = function (url, user, password){
    var p = new Promise(function(resolve, reject) {
        // the _driver is the actual flag for the state
        if (Database._driver !== null) {
            Database.logged_in = true;
            resolve();
        } else {
            try {
                Database._driver = neo4j.driver(url, neo4j.auth.basic(user, password));
                /*Database._driver.onCompleted = function () {
                    console.log("ON COMP");
                };*/
 
                Database._driver.onError = function (error) {
                    Database._driver = null;
                    Database.logged_in = false;
                    Database._driver = null;
                    return reject(error);
                };
 
                var session = Database._get_session();
                return session.run('return 1').then(
                    function() {
                        Database.logged_in = true;
                        return Database._hygiene().then(function(res) {
                            return resolve();
                        },
                        function(err){
                            Database._driver = null;
                            Database.logged_in = false;
                            log.error(err);
                            return reject(err);
                        });
                    },
                    function(err) {
                        Database._driver = null;
                        Database.logged_in = false;
                        reject(err);
                    }
                );
            } catch (err) {
                Database._driver = null;
                Database.logged_in = false;
                return reject(err);
            }
        }
    });
    return p;
};
 
 
 
/**
 * Logout from the current database neo4j session.
 * Delete the saved neo4j session and set the Database.logged_in flag to false.
 *
* @method logout
* @return {boolean}
*/
Database.logout = function (){
    var driver = Database._get_driver();
    if (driver) {
        log.info("... neo4j driver closed")
        driver.close();
    }
    Database._driver = null;
    Database.logged_in = false;
};
 
/**
 * Generic catch error function for database promises
 * Logs the error and closes the db session
 *
* @method log_error_and_close_session
* @return {error}
*/
Database.log_error_and_close_session = log_error_and_close_session;
 
/**
* Get the database driver
 * stores the instance in _driver
 * makes use of the development flag in order to use or not use basic auth
 *
* @method _get_driver
 * @private
* @return {driver} Returns a bolt:// driver instance
*/
Database._get_driver = function (){
    if (this._driver !== null) {
        return this._driver;
    }
    return false;
};
 
/**
 * Get a session to execute Neo4J Cypher code on
 *
 * @method _get_session
 * @private
 * @return {session}
 */
Database._get_session = function () {
    var driver = Database._get_driver();
    if (!driver) {
        log.error("Could not fetch driver");
        return null;
    } else {
        return driver.session();
    }
 
};
 
/**
 * Add the necessary constraints to create something like a schema
 * 1) The file_path of an image is unique
 *
 * @method add_constraints
 * @return {session}
 */
Database._add_constraints = function() {
    var session = this._get_session();
    return session.run("CREATE CONSTRAINT ON (i:Image) ASSERT i.file_path IS UNIQUE; ");
};
 
/**
 * Clean up the database on login
 *
 * 1) remove nodes without edges (-> MetaGroups that are not referenced)
 *
* @method _hygiene
* @return {Promise}
*/
Database._hygiene = function (){
    var session = Database._get_session();
    // this query removes all free swimming nodes (without any edges)
    return session.run("match (n) where not (n)--() delete (n);");
};
 
/**
 * Remove the constraints
 *
 * @method _remove_constraints
 * @private
 * @return {Promise}
 */
Database._remove_constraints = function() {
    var session = Database._get_session();
    return session.run("DROP CONSTRAINT ON (i:Image) ASSERT i.file_path IS UNIQUE; ");
};
 
/**
 * Do the initialization on start
 * 1) drop and then create constraint
 *
 * @method init
 * @return {session}
 */
Database.init = function(callback) {
    return Database._remove_constraints().then(function(){
        return Database._add_constraints()
    }, function(){
        return Database._add_constraints()
    });
};
 
 
Database.toggle_fragment_completed = function(image_id, fragment_id) {
    var session = Database._get_session();
    var prom = session.run("MATCH (a:Fragment)-[r:image]->(i:Image) " +
        "WHERE ID(a) = toInteger({fragment_id}) AND ID(i) = toInteger({image_id}) " +
        "SET a.completed = NOT a.completed " +
        "RETURN a;",
        {image_id: Number(image_id), fragment_id: Number(fragment_id)})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records[0];
        }, log_error_and_close_session(session));
    return prom;
};
 
 
/**
 * Adds an image to the database
 * Sets the upload_date to now in seconds (Math.round(d.getTime() / 1000))
 *
 * @method add_image
 * @param file_path {string} The unique identifier for an image
 * @param exif_data
 * @return {Promise}
 */
Database.add_image = function(file_path, exif_data) {
    var session = this._get_session();
    var d = new Date();
    var upload_date = Math.round(d.getTime());
    var cql = "CREATE (a:Image {file_path: {file_path}, upload_date: {upload_date}}) RETURN ID(a) as ident;";
    var meta_data = null;
    if (exif_data) {
        cql = "CREATE (a:Image {file_path: {file_path}, upload_date: {upload_date}}) " +
            "SET a += {meta_data} " +
            "RETURN ID(a) as ident;";
        meta_data =  exif_data['gps'] || {};
        Iif (exif_data.hasOwnProperty('exif') && exif_data['exif'].hasOwnProperty('ExifImageWidth')
            && exif_data['exif'].hasOwnProperty('ExifImageHeight')) {
            Object.assign(meta_data, {
                width:  exif_data.exif.ExifImageWidth,
                height: exif_data.exif.ExifImageHeight
            });
        }
        // Get the upload_date from the creation date exif tag
        if (exif_data && exif_data.hasOwnProperty('exif') && exif_data['exif'].hasOwnProperty('CreateDate')) {
            // might look like this 2017:05:28 19:46:49
            try {
                var raw_format = exif_data['exif']['CreateDate'];
                Eif (raw_format.indexOf(" ") >= 0) {
                    var parsed_date = parse(raw_format);
                    Eif (parsed_date) {
                        upload_date = Math.round(parsed_date.getTime());
                    }
                }
            } catch (e) {
                log.error(e);
            }
        }
        Object.keys(meta_data).forEach(function(key) {
            meta_data[key] = meta_data[key].valueOf();
            Iif  (meta_data[key] instanceof Buffer) {
                meta_data[key] = meta_data[key].toString();
            }
        });
    }
 
    var p = session.run(cql,
        {file_path: file_path, upload_date: upload_date, meta_data: meta_data})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            Iif (records.length === 0) {
                throw Error('Zero elements created');
            }
            return records[0];
        }, log_error_and_close_session(session));
    return p;
};
 
/**
 * Get image from database by file_path
 *
 * Promise: success: Contains record for the image
 *
 * @method get_image
 * @param file_path {string} The unique identifier for an image
 * @return {Promise}
 */
Database.get_image = function(file_path){
    // Duplications are silent for some reason
    var session = this._get_session();
    var prom = session
        .run("MATCH (a:Image {file_path: {file_path}}) return ID(a) as ident, a;", {file_path: file_path})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records[0];
        }, log_error_and_close_session(session));
    return prom;
};
 
Database.get_image_of_token = function(token_id){
    var session = this._get_session();
    var prom = session
        .run("MATCH (t:Token)-[]-(f:Fragment)-[]-(i:Image) WHERE ID(t) = toInteger({token_id}) RETURN i, ID(f) as fragment_id, ID(i) AS image_id;",
            {token_id: Number(token_id)})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records[0];
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 *
 * @param token_id
 * @returns {*|Promise}
 */
Database.get_fragment_bounding_box = function(token_id){
    var session = this._get_session();
    var prom = session
        .run("MATCH (t:Token)-[]-(f:Fragment) WHERE ID(t) = toInteger({token_id}) "+
            "WITH f " +
            "MATCH (x:Token)-[]-(f) " +
            "WITH x, f "+
            "WHERE EXISTS(x.x) AND EXISTS(x.y) AND EXISTS(x.width) AND EXISTS(x.height) "+
            "RETURN MIN(toInteger(x.x)) as x, MIN(toInteger(x.y)) as y, " +
            "MAX(toInteger(x.x)+toInteger(x.width)) as width, MAX(toInteger(x.y)+toInteger(x.height)) as height, ID(f) AS fragment_id;",
            {token_id: Number(token_id)})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            Iif (records.length === 0) {
                return null;
            }
            return records[0];
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 * Removes an image by ID
 *
 * @method remove_image_by_id
 * @param id_ {String|Number}
 * @return {Promise}
 */
Database.remove_image_by_id = function (id_) {
    var session = this._get_session();
    return session.run(
        "MATCH (n:Image) " +
        "WHERE ID(n) = toInteger({ident}) " +
        "RETURN n.file_path as file_path", {ident: Number(id_)})
        .then(function (result) {
            var file_path = result.records[0].get("file_path");
            try {
                utils.remove_image(file_path);
            } catch (e) {
                log.warn("Image node is being deleted but there was an error finding the local image file: "+e);
            }
            return session
                .run("MATCH (n:Image)<-[:image]-(f:Fragment)<-[:fragment]-(t) " +
                    "WHERE ID(n) = toInteger({ident}) " +
                    "DETACH DELETE t;", {ident: Number(id_)})
                .then(function (result) {
                    return session.run(
                        "MATCH (n:Image)-[:image]-(f:Fragment) " +
                        "WHERE ID(n) = toInteger({ident}) " +
                        "DETACH DELETE n,f", {ident: Number(id_)})
                        .then(function (result) {
                            return session.run(
                                "MATCH (n:Image) " +
                                "WHERE ID(n) = toInteger({ident}) " +
                                "DETACH DELETE n;", {ident: Number(id_)})
                                .then(function (result) {
                                    return session.run(
                                        "MATCH (a:MetaGroup) WHERE not ((a)--()) DELETE a;")
                                        .then(function (result) {
                                            session.close();
                                            return result;
                                        }, log);
                                }, log_error_and_close_session(session));
 
                        }, log_error_and_close_session(session));
                }, log_error_and_close_session(session));
        }, log_error_and_close_session(session));
};
 
/**
 * Adds a fragment to an image
 * Every image can have multiple fragments
 * the name of the fragment is unique
 *
 * @method add_fragment
 * @param image_id
 * @param fragment_name The identifier for the fragment
 * @return {Promise}
 */
Database.add_fragment = function(image_id, fragment_name) {
    var session = this._get_session();
    var d = new Date();
    var upload_date = Math.round(d.getTime());
    return session.run("MATCH (i:Image) " +
        "WHERE ID(i) = toInteger({image_id}) " +
        "WITH i " +
        "CREATE (f:Fragment {fragment_name: {fragment_name}, upload_date: {upload_date}, completed:false, comment:{comment}})-[:image]->(i) " +
        "RETURN ID(f) as ident, ID(i) AS image_ident;",
        {fragment_name: fragment_name, upload_date: upload_date, image_id: Number(image_id), comment: ''})
        .then(function(result){
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records[0];
        }, log_error_and_close_session(session))
};
 
Database.add_comment_to_fragment = function(fragment_id, comment) {
    var session = this._get_session();
    return session.run(
        "MATCH (f:Fragment) " +
        "WHERE ID(f) = toInteger({fragment_id}) " +
        "SET f += {comment: {comment}} " +
        "RETURN ID(f) as ident;",
        {
            fragment_id: fragment_id,
            comment: comment
        }
    ).then(function(result){
        session.close();
        var records = [];
        for (var i = 0; i < result.records.length; i++) {
            records.push(result.records[i]);
        }
        return records[0];
    }, log_error_and_close_session(session));
 
};
 
/**
 * Removes all fragments of an image with a given name
 *
 * @method remove_fragment
 * @param image_id
 * @param fragment_id
 * @param dont_delete_fragment
 * @return {Promise}
 */
Database.remove_fragment = function(image_id, fragment_id, dont_delete_fragment) {
    if (dont_delete_fragment === undefined) {dont_delete_fragment=true;}
    var session = this._get_session();
    return session.run("MATCH (i:Image)<-[:image]-(f:Fragment)-[:fragment]-(t) " +
        "WHERE ID(i) = toInteger({image_id}) AND ID(f) = toInteger({fragment_id}) " +
        "DETACH DELETE t;", {image_id: Number(image_id), fragment_id:Number(fragment_id)})
        .then(function(success) {
                if (!dont_delete_fragment) {
                    return session.run("MATCH (i:Image)<-[:image]-(f:Fragment) " +
                        "WHERE ID(i) = toInteger({image_id}) AND ID(f) = toInteger({fragment_id}) " +
                        "DETACH DELETE f;", {image_id: Number(image_id), fragment_id: Number(fragment_id)})
                        .then(
                            function (result) {
                                return session.run(
                                    "MATCH (a:MetaGroup) WHERE not ((a)--()) DELETE a;")
                                    .then(function (result) {
                                        session.close();
                                        return result;
                                    }, log_error_and_close_session(session));
                            }, log_error_and_close_session(session)
                        );
                } else {
                    var hash = utils.hash_xml_fragment(fragment_id);
                    return session.run("MATCH (i:Image)<-[:image]-(f:Fragment) " +
                        "WHERE ID(i) = toInteger({image_id}) AND ID(f) = toInteger({fragment_id}) " +
                        "SET f.hash = {hash};", {image_id: Number(image_id), fragment_id: Number(fragment_id),
                                                hash: hash})
                        .then(
                            function (result) {
                                session.close();
                                return result;
                            }, log_error_and_close_session(session)
                        );
                }
            }, log_error_and_close_session(session)
 
        );
};
 
/**
 * Get the fragment of an image by name
 *
 * @method get_fragment
 * @param image_file_path {String}  The unique id for the image
 * @param fragment_name The identifier for the fragments
 * @return {Promise}
 */
Database.get_fragment = function(image_file_path, fragment_name) {
    var session = this._get_session();
    var prom = session.run("MATCH (a:Fragment {fragment_name: {fragment_name}})-[r:image]->(i:Image {file_path:{file_path}}) " +
        "RETURN ID(a) as ident, ID(i) as image_id, a.fragment_name AS fragment_name, a.upload_date AS upload_date, a.completed AS completed, a.comment as comment;",
        {fragment_name: fragment_name, file_path: image_file_path})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records[0];
        });
    return prom;
};
 
 
 
 
/**
 * Get the fragment of an image by name
 *
 * @method get_fragment_by_id
 * @param image_id
 * @param fragment_id
 * @return {Promise}
 */
Database.get_fragment_by_id = function(image_id, fragment_id) {
    var session = this._get_session();
    var prom = session.run("MATCH (a:Fragment)-[r:image]->(i:Image) " +
        "WHERE ID(a) = toInteger({fragment_id}) AND ID(i) = toInteger({image_id}) " +
        "RETURN ID(a) as ident, ID(i) as image_id, a.fragment_name AS fragment_name, a.upload_date AS upload_date, a.completed AS completed, a.comment AS comment;",
        {image_id: Number(image_id), fragment_id: Number(fragment_id)})
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records[0];
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 * Get the fragment of an image by name
 *
 * @method get_all_fragments
 * @return {Promise}
 */
Database.get_all_fragments = function() {
    var session = this._get_session();
    var prom = session.run("MATCH (f:Fragment) RETURN ID(f) as identifier;")
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(Number(result.records[i].get('identifier')));
            }
            return records;
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 * Adds a node to a fragment of an image
 *
 * Promise:success  number_of_created_nodes
 *
 * @method add_node
 * @param image_id
 * @param fragment_id
 * @param node_label
 * @param node_attributes
 * @return {Promise}
 */
Database.add_node = function(image_id, fragment_id, node_label, node_attributes) {
    // check if all the necessary attributes are there
    Iif (!['Token', 'Group'].includes(node_label)) {
        throw Error('Invalid node label (add_node)');
    }
    var enumerator = node_attributes.id;
    var session = this._get_session();
    var query = "MATCH (i:Image)<-[:image]-(f:Fragment) " +
        "WHERE ID(i) = toInteger({image_id}) AND ID(f) = toInteger({fragment_id}) " +
        "WITH f " +
        "CREATE (n:" + node_label + " {enumerator:{enumerator}})-[:fragment]->(f) " +
        "SET n += {props} " +
        "RETURN ID(n) as ident;";
    var prom = session.run(query,
        {fragment_id: Number(fragment_id), image_id: Number(image_id), enumerator:Number(enumerator),
        props:node_attributes, node_label: node_label})
        .then(function (result) {
            session.close();
            if (node_attributes.hasOwnProperty('groupType')) {
                if (node_attributes.groupType === 'frame') {
                    var group_id = Number(result.records[0].get('ident'));
                    return Database.add_frame_edge(group_id, node_attributes.value, 'MetaFrame');
                }
            }
            return result;
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 * Adds an edge between a frame from a group and a global frame
 * so called 'meta frame'
 *
 * Also creates the 'meta frame' if it does not exist *
 *
 * @method add_edge
 * @return {Promise}
 * @param node_id
 * @param frame_name
 * @param groupType
 */
Database.add_frame_edge = function(node_id, frame_name, groupType) {
    var session = this._get_session();
    var prom = session.run(
        "MATCH (b:Group) " +
        "WHERE ID(b) = toInteger({node_id}) " +
        "WITH b " +
        "MERGE (m:MetaGroup {value:{frame_name}, groupType:{groupType}}) " +
        "CREATE (m)<-[n:PartOf]-(b) " +
        "",
        {node_id: node_id, frame_name:frame_name, groupType:groupType})
        .then(function (result) {
            session.close();
            return result;
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 * Adds an edge between two nodes
 * in a fragment of an image
 *
 * Promise:success  number_of_created_edges
 *
 * @method add_edge
 * @param image_id
 * @param fragment_id
 * @param source_enum
 * @param target_enum
 * @param edge_attributes
 * @return {Promise}
 */
Database.add_edge = function(image_id, fragment_id, source_enum, target_enum, edge_attributes) {
    var enumerator = edge_attributes.id;
    var session = this._get_session();
    var prom = session.run("MATCH (i:Image)<-[:image]-(f:Fragment) " +
        "WHERE ID(i) = toInteger({image_id}) AND ID(f) = toInteger({fragment_id}) " +
        "WITH f " +
        "MATCH (f)<-[:fragment]-(a {enumerator: {source_enum} }), (f)<-[:fragment]-(b {enumerator: {target_enum} }) " +
        "CREATE (a)-[n:edge]->(b) " +
        "SET n += {props};",
        {fragment_id: Number(fragment_id), image_id: Number(image_id),
            source_enum:Number(source_enum), target_enum:Number(target_enum),
            props:edge_attributes
        })
        .then(function (result) {
            session.close();
            return result;
        }, log_error_and_close_session(session));
    return prom;
};
 
 
/**
 * Returns a promise with an array of records of images
 * ordered by last_edit_date, upload_date
 *
 * @example
       database.get_all_images().then(function (results) {
            var row_data = [];
            results.forEach(function (r) {
                row_data.push([r.get('ident'), r.get('file_path'), r.get('upload_date'), r.get('completed')]);
            });
            res.render('table',
                {
                    title: 'Hey',
                    message: 'Hello there!',
                    rows: row_data
                });
            }
        );
 *
 * @method get_all_images
 * @return {Promise}
 */
Database.get_all_images = function() {
    // pagination is not necessary so far (the page behaved well with 300 images in a test)
    var session = this._get_session();
    var prom = session
        .run("MATCH (a:Image) " +
            "OPTIONAL MATCH (a)-[]-(f1:Fragment {completed:false}) " +
            "OPTIONAL MATCH (a)-[]-(f2:Fragment {completed:true}) " +
            "WITH a, f1, f2 " +
            "ORDER BY a.last_edit_date, a.upload_date " +
            "RETURN " +
            "ID(a) as ident," +
            "a.file_path as file_path, " +
            "a.upload_date as upload_date, " +
            "COUNT(f1) AS num_uncompleted_fragments," +
            "COUNT(f2) AS num_completed_fragments;")
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records;
        });
    return prom;
};
 
/**
 * Get all fragments of one image
 *
 * @method get_fragments_by_image_id
 * @param image_id
 * @returns {*|Promise}
 */
Database.get_fragments_by_image_id = function(image_id) {
    var session = this._get_session();
    var prom = session
        .run("MATCH (a:Image)-[r]-(f:Fragment) " +
            "WHERE ID(a) = toInteger({image_id})" +
            "WITH a,f " +
            "ORDER BY f.upload_date " +
            "RETURN " +
            "ID(a) as image_id," +
            "a.file_path as file_path, " +
            "ID(f) as fragment_id, " +
            "f.fragment_name as fragment_name, " +
            "f.upload_date as upload_date, " +
            "f.completed as completed, " +
            "f.comment as comment;",
            {image_id: Number(image_id)}
        )
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records;
        });
    return prom;
};
 
/**
 * Get all completed fragments
 *
 * @returns {*|Promise}
 */
Database.get_all_completed_fragments = function() {
    var session = this._get_session();
    var prom = session
        .run("MATCH (a:Image)-[r]-(f:Fragment {completed:true}) " +
            "WITH a,f " +
            "RETURN " +
            "ID(a) as image_id, " +
            "f.hash as hash, " +
            "ID(f) as fragment_id; ")
        .then(function (result) {
            session.close();
            var records = [];
            for (var i = 0; i < result.records.length; i++) {
                records.push(result.records[i]);
            }
            return records;
        }, log_error_and_close_session(session));
    return prom;
};
 
/**
 * Returns all possible property keys for tokens filtered by search_string
 * Is used for the autocomplete function of the add-property-input
 *
 * Promise:success: Array of strings
 *
 * @method get_all_property_keys_for_token
 * @param search_string {string} Empty string gives all possible values
 * @param label
 * @param token_type
 * @return {Promise}
 */
Database.get_all_property_keys_for_token = function(search_string, label, token_type) {
    Eif (label === undefined) {
        label = 'Token'
    }
    var extra_check = "";
    Iif (token_type !== undefined) {
        if (label === 'Token') {
            extra_check = ' {tokenType:"'+token_type+'"}';
        } else if (label === 'Group') {
            extra_check = ' {groupType:"'+token_type+'"}';
        }
    }
 
    var session = this._get_session();
    var prom = session
        .run("MATCH (p:"+ label +""+ extra_check +")  WITH DISTINCT keys(p) AS keys " +
            "UNWIND keys AS keyslisting WITH DISTINCT keyslisting AS allfields " +
            "WHERE allfields CONTAINS {search_string}" +
            "RETURN allfields;", {search_string: search_string || '',
                                  token_type: token_type
        })
        .then(function (result) {
            session.close();
            var keys = [];
            for (var i = 0; i < result.records.length; i++) {
                keys.push(result.records[i]['_fields'][0]);
            }
            return keys;
        });
    return prom;
};
 
/**
 * Returns all distinct values for the given property in a string list in a promise
 * Is used for the autocomplete function of the property values
 *
 * Promise:success: Array of strings *
 *
 * @method get_all_property_values_for_token
 * @param property {string} the name of a property of tokens
 * @param search_string {string} that filters the result (empty string is not filter)
 * @return {Promise}
 */
Database.get_all_property_values_for_token = function(property, search_string, label) {
    Eif (label === undefined) {
        label = 'Token'
    }
    var session = this._get_session();
    var prom = session
        .run("MATCH (n:"+label+") " +
            "WHERE n[{property}] IS NOT NULL " +
            "AND n[{property}] CONTAINS {search_string} " +
            "RETURN distinct n[{property}];",
            {property: property,
            search_string: search_string || ''}
        )
        .then(function (result) {
            session.close();
            var values = [];
            for (var i = 0; i < result.records.length; i++) {
                values.push(result.records[i]['_fields'][0]);
            }
            return values;
        },
        log_error_and_close_session(session));
    return prom;
};
 
module.exports = Database;