import faker from 'faker' ; import { ColumnObj , DummyRecords } from '../BE_types' ; const db = require ( '../models' ) ; const getRandomInt = ( min , max ) => { const minInt = Math . ceil ( min ) ; const maxInt = Math . floor ( max ) ; return Math . floor ( Math . random ( ) * ( maxInt - minInt ) + minInt ) ; } ; const generateDataByType = ( columnObj ) : string | number => { let length ; switch ( columnObj . data_type ) { case 'smallint' : return faker . random . number ( { min : - 32768 , max : 32767 } ) ; case 'integer' : return faker . random . number ( { min : - 2147483648 , max : 2147483647 } ) ; case 'bigint' : return faker . random . number ( { min : - 9223372036854775808 , max : 9223372036854775807 , } ) ; case 'character varying' : length = columnObj . character_maximum_length && columnObj . character_maximum_length < 3 ? Math . floor ( Math . random ( ) * columnObj . character_maximum_length ) : 3 ; return '\'' . concat ( faker . random . alphaNumeric ( length ) ) . concat ( '\'' ) ; case 'date' : { const year = getRandomInt ( 1500 , 2020 ) . toString ( ) ; let month = getRandomInt ( 1 , 13 ) . toString ( ) ; if ( month . length === 1 ) month = `0${ month }` ; let day = getRandomInt ( 1 , 29 ) . toString ( ) ; if ( day . length === 1 ) day = `0${ day }` ; const result = `${ year }/${ month }/${ day }` ; return '\'' . concat ( result ) . concat ( '\'' ) ; } case 'boolean' : { return '\'' . concat ( faker . random . boolean ( ) ) . concat ( '\'' ) ; } default : throw new Error ( 'unhandled data type' ) ; } } ; type GenerateDummyData = ( tableInfo : ColumnObj [ ] , numRows : number ) => Promise < DummyRecords > ; const generateDummyData = async ( tableInfo , numRows ) => { const columnNames = tableInfo . reduce ( ( acc , curr ) => { if ( curr . constraint_type !== 'PRIMARY KEY' ) acc . push ( curr . column_name ) ; return acc ; } , [ ] ) ; const dummyRecords = [ columnNames ] ; for ( let i = 0 ; i < numRows ; i += 1 ) { const row = [ ] ; for ( let j = 0 ; j < tableInfo . length ; j += 1 ) { if ( tableInfo [ j ] . constraint_type !== 'FOREIGN KEY' && tableInfo [ j ] . constraint_type !== 'PRIMARY KEY' ) row . push ( generateDataByType ( tableInfo [ j ] ) ) ; else if ( tableInfo [ j ] . constraint_type === 'FOREIGN KEY' ) { try { const foreignColumn = tableInfo [ j ] . foreign_column ; const foreignTable = tableInfo [ j ] . foreign_table ; const getForeignKeyQuery = `
            SELECT ${ foreignColumn }
            FROM ${ foreignTable } TABLESAMPLE BERNOULLI(50)
            LIMIT 1
          ` ; const foreignKey = await db . query ( getForeignKeyQuery ) ; if ( foreignKey . rows . length ) row . push ( foreignKey . rows [ 0 ] [ '_id' ] ) ; else return new Error ( 'There was an error while retrieving a valid foreign key.' ) ; } catch ( err ) { return err ; } } } dummyRecords . push ( row ) ; } return dummyRecords ; } ; export default generateDummyData ;