### ----------------------------------------------------
### -- UpRooted
### -- Licenses: Artistic-2.0
### -- Authors: Paweł bbkr Pabian
### -- File: t/31-reader-mysql.rakutest
### ----------------------------------------------------
use lib 'lib';
use lib 't/lib';

use Test;

use DBITest;
use UpRooted::Schema::MySQL;
use UpRooted::Tree;
use UpRooted::Reader::MySQL;

my $connection = connect( 'mysql' );
load( $connection, 'mysql', 'cleanup.sql' );
load( $connection, 'mysql', 'schema.sql' );

plan 2;

my $schema = UpRooted::Schema::MySQL.new( :$connection );
my $tree = UpRooted::Tree.new( root-table => $schema.table( 't1' ) );
my $reader = UpRooted::Reader::MySQL.new( :$connection, :$tree );

subtest 'No data' => {

    plan 1;

    my @result = gather $reader.read( );
    ok all( @result ) ~~ UpRooted::Table, 'Empty UpRooted::Tables';
    
};

subtest 'With data' => {

    plan 19;

    load( $connection, 'mysql', 'data.sql' );

    my @result = gather $reader.read( id => 1 );
    
    is @result.shift.name, 't1', 'Root UpRooted::Table';
    is-deeply @result.shift, [
        1,
        'a', '😀😔', Buf.new( 0x61 ), Buf.new( 0x61 ), Buf.new( 0x61 ), Buf.new( 0xF0, 0x9F, 0x98, 0x80, 0xF0, 0x9F, 0x98, 0x94 ),
        -1, 1, 1, 1, 18446744073709551615,
        1.1, -0.33e0, 0.33e0,
        Buf.new( 0x00 ), Buf.new( 0x00 ),  Buf.new( 0x00 ), Buf.new( 0x00 ) 
    ], 'Root data';

    # also confirms if no data from UpRooted::Tree starting at id = 2 leaked
    is @result.shift.name, 't2', 'UpRooted::Table with not nullable UpRooted::Relation with single UpRooted::Column';
    is-deeply @result.shift, [ 1, 1 ], 'Row data';
    is-deeply @result.shift, [ 2, 1 ], 'Row data';
        
    is @result.shift.name, 't6', 'Self loop UpRooted::Table';
    is-deeply @result.shift, [ 1, 1, 1 ], 'Row data';
    
    is @result.shift.name, 't9', 'Horse riddle UpRooted::Table';
    # TODO, behavior not decided yet 
    
    is @result.shift.name, 't3', 'UpRooted::Table with not nullable UpRooted::Relations of different lengths.';
    is-deeply @result.shift, [ 1, 1, 1 ], 'Row data';
    is-deeply @result.shift, [ 2, 1, 2 ], 'Row data';
    
    is @result.shift.name, 't4', 'UpRooted::Table with not nullable UpRooted::Relation longer than nullable one';
    is-deeply @result.shift, [ 1, 1, 1 ], 'Row data';
    
    is @result.shift.name, 't7', 'Long loop UpRooted::Table';
    is-deeply @result.shift, [ 1, 1, 1 ], 'Row data';
    is @result.shift.name, 't8', 'Long loop UpRooted::Table';
    is-deeply @result.shift, [ 1, 1, 1 ], 'Row data';

    is @result.shift.name, 't5', 'UpRooted::Table with UpRooted::Relation with multiple UpRooted::Columns';
    is-deeply @result.shift, [ 1, 1, 1 ], 'Row data';
    
};

load( $connection, 'mysql', 'cleanup.sql' );


