2020-09-04 22:15:55 +02:00
import ModelQuery , { WhereOperator } from "../src/db/ModelQuery" ;
import ModelFactory from "../src/db/ModelFactory" ;
import Model from "../src/db/Model" ;
describe ( 'Test ModelQuery' , ( ) = > {
test ( 'groupWhere generates proper query' , ( ) = > {
const query = ModelQuery . select ( { table : 'model' } as unknown as ModelFactory < Model > , '*' ) ;
query . where ( 'f1' , 'v1' ) ;
query . groupWhere ( q = > q . where ( 'f2' , 'v2' ) . where ( 'f3' , 'v3' )
. groupWhere ( q = > q . where ( 'f4' , 'v4' ) , WhereOperator . OR ) )
. where ( 'f5' , 'v5' ) ;
2020-09-05 14:55:19 +02:00
expect ( query . toString ( true ) ) . toBe ( 'SELECT * FROM `model` WHERE `f1`=? AND (`f2`=? AND `f3`=? OR (`f4`=?)) AND `f5`=? ' ) ;
2020-09-04 22:15:55 +02:00
expect ( query . variables . length ) . toBe ( 5 ) ;
} ) ;
2020-09-05 14:55:19 +02:00
test ( 'recursive queries' , ( ) = > {
const query = ModelQuery . select ( { table : 'model' } as unknown as ModelFactory < Model > , '*' ) ;
query . where ( 'f1' , 'v1' ) ;
query . leftJoin ( 'test' ) . on ( 'model.j1' , 'test.j2' ) ;
query . recursive ( { localKey : 'local' , foreignKey : 'foreign' } ) ;
query . sortBy ( 'f2' , 'ASC' ) . limit ( 8 ) ;
expect ( query . toString ( true ) ) . toBe ( "WITH RECURSIVE cte AS (SELECT `model`.* FROM `model` WHERE `f1`=? UNION SELECT o.* FROM `model` AS o, cte AS c WHERE o.`foreign`=c.`local`) SELECT * FROM cte LEFT JOIN `test` ON `model`.`j1`=`test`.`j2` ORDER BY `f2` ASC LIMIT 8" ) ;
expect ( query . variables . length ) . toBe ( 1 ) ;
} ) ;
2020-09-04 22:15:55 +02:00
} ) ;