Beispiel #1
0
def pretty_print_departments():
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    database = SqliteDatabase('../data/personjob.db')

    logger.info('Print Job class with related departments')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')
        query = (Person.select(Person, Job).join(Job, JOIN.INNER))

        logger.info('View matching records from both tables')
        for person in query:
            d1 = person.job.department.start_date
            # print(d1) # 2001-09-22
            d2 = person.job.department.end_date
            dd1 = datetime.strptime(d1, "%Y-%m-%d")
            dd2 = datetime.strptime(d2, "%Y-%m-%d")
            delta = dd2 - dd1
            # print('days: ', delta.days)
            logger.info(
                f'Person {person.person_name} had job {person.job.job_name} in {person.job.department.name} for {delta.days} days'
            )

    except Exception as e:
        logger.info(f'Error creating = {job[JOB_NAME]}')
        logger.info(e)

    finally:
        logger.info('database closes')
        database.close()
def print_info():
    """
    connects to database and queries/prints list of users, jobs, and departments.
    :return: printed list of users, jobs, and departments
    """
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    database = SqliteDatabase('../data/personjob.db')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')
        query = (Person.select(
            Person.person_name, Job.job_name,
            Department.department_name).join(Job).join(Department).tuples())
        for record in query:
            pprint.pprint(record)

    except Exception as e:
        logger.info(e)

    finally:
        logger.info('database closes')
        database.close()
Beispiel #3
0
def join_classes():
    """
        demonstrate how to join classes together : no matches too
    """

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    database = SqliteDatabase('../data/personjob.db')

    logger.info(
        'View matching records and Persons without Jobs (note LEFT_OUTER)')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')
        query = (Person.select(Person, Job).join(Job, JOIN.LEFT_OUTER))

        for person in query:
            try:
                logger.info(
                    f'Person {person.person_name} had job {person.job.job_name}'
                )

            except Exception as e:
                logger.info(f'Person {person.person_name} had no job')

        logger.info('Example of how to summarize data')
        logger.info('Note select() creates a count and names it job_count')
        logger.info('group_by and order_by control level and sorting')

        query = (Person.select(Person,
                               fn.COUNT(Job.job_name).alias('job_count')).join(
                                   Job,
                                   JOIN.LEFT_OUTER).group_by(Person).order_by(
                                       Person.person_name))

        for person in query:
            logger.info(f'{person.person_name} had {person.job_count} jobs')

    except Exception as e:
        logger.info(e)

    finally:
        database.close()
def join_classes():

    "show all departments a person worked"

    """
        demonstrate how to join classes together : matches
    """

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    database = SqliteDatabase('data/personjob.db')

    logger.info('Now resolve the join and print (INNER shows only jobs that match person and dep that match job)')
    logger.info('Notice how we use a query variable in this case')
    logger.info('We select the classes we need, and we join Person to Job')
    logger.info('Inner join (which is the default) shows only records that match')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')
        query1 = Person.select(Person, Job).join(Job, JOIN.INNER)






        logger.info('View matching records from tables')
        print("{:30s}|{:30s}|{:15}|{:30}|{:4}".format("Name", "Job", "Duration [days]", "Department", "ID"))
        for person in query1:
            job_start = person.job.start_date
            job_end = person.job.end_date
            y1 = int(job_start.split("-")[0])
            y2 = int(job_end.split("-")[0])
            m1 = int(job_start.split("-")[1])
            m2 = int(job_end.split("-")[1])
            d1 = int(job_start.split("-")[2])
            d2 = int(job_end.split("-")[2])
            job_dur = date(y2, m2, d2) - date(y1, m1, d1)
            dep = Department.get(Department.dep_job == person.job.job_name)

            print("{:30s}|{:30s}|{:15}|{:30}|{:4}".format(person.person_name,
                                                          person.job.job_name,
                                                          job_dur.days,
                                                          dep.dep_name,
                                                          dep.dep_num))

    except Exception as e:
        logger.info(e)

    finally:
        logger.info('database closes')
        database.close()
def select_and_update():
    """"
        show how we can select a specific record, and then search and read through several records
    """

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    database = SqliteDatabase('data/personjob.db')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')

        logger.info('Find and display by selecting a spcific Person name...')
        aperson = Person.get(Person.person_name == 'Susan')

        logger.info(f'{aperson.person_name} lives in {aperson.lives_in_town} ' + \
                    f' and likes to be known as {aperson.nickname}')

        logger.info('Search and display all Person with missing nicknames')
        logger.info(
            'Our person class inherits select(). Specify search with .where()')
        logger.info('Peter gets a nickname but noone else')

        for person in Person.select().where(Person.nickname is None):
            logger.info(
                f'{person.person_name} does not have a nickname; see: {person.nickname}'
            )
            if person.person_name == 'Peter':
                logger.info('Changing nickname for Peter')
                logger.info('Update the database')
                person.nickname = 'Painter'
                person.save()
            else:
                logger.info(f'Not giving a nickname to {person.person_name}')

        logger.info(
            'And here is where we prove it by finding Peter and displaying')
        aperson = Person.get(Person.person_name == 'Peter')
        logger.info(
            f'{aperson.person_name} now has a nickname of {aperson.nickname}')

    except Exception as e:
        logger.info(e)

    finally:
        database.close()
def join_classes():
    """
        demonstrate how to join classes together : matches
    """

    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    database = SqliteDatabase('../data/personjob.db')

    logger.info('Working with Job class')

    logger.info(
        'Now resolve the join and print (INNER shows only jobs that match person)...'
    )
    logger.info('Notice how we use a query variable in this case')
    logger.info('We select the classes we need, and we join Person to Job')
    logger.info(
        'Inner join (which is the default) shows only records that match')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')
        query = (Person.select(Person, Job).join(Job, JOIN.INNER))

        logger.info('View matching records from both tables')
        for person in query:
            logger.info(
                f'Person {person.person_name} in department {person.department_id} had job {person.job.job_name}'
            )

    except Exception as e:
        logger.info(f'Error creating = {job[JOB_NAME]}')
        logger.info(e)

    finally:
        logger.info('database closes')
        database.close()
Beispiel #7
0
def select_dept():
    """
	select departments to show they are in database
	"""
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    database = SqliteDatabase('personjob.db')

    try:
        database.connect()
        database.execute_sql('PRAGMA foreign_keys = ON;')
        query = (Person.select(Person, Job,
                               Department).join(Job, JOIN.INNER).join(
                                   Department, JOIN.INNER))
        logger.info('View each department each person has worked in')
        for person in query:
            logger.info(
                f'Person: {person.person_name}, Job: {person.job.job_name}, Department: {person.job.department.department_name}'
            )
    except Exception as e:
        logger.info(e)
    finally:
        database.close()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

database = SqliteDatabase('./data/personjob.db')

logger.info('View matching records and Persons without Jobs (note LEFT_OUTER)')
# person name, department job, duration

try:
    database.connect()
    database.execute_sql('PRAGMA foreign_keys = ON;')

    query = (Person.select(Person.person_name, Job.job_name, Job.start_date,
                           Job.end_date, Job_Department.dept_id).join(
                               Job,
                               JOIN.LEFT_OUTER).join(Job_Department,
                                                     JOIN.LEFT_OUTER))

    for person in query:
        try:
            duration = (
                datetime.strptime(person.job.end_date, '%Y-%m-%d') -
                datetime.strptime(person.job.start_date, '%Y-%m-%d')).days
            logger.info(
                f'Person {person.person_name} had job {person.job.job_name} for {duration} days in dept: {person.job.job_department.dept_id.name}'
            )

            pprint(
                f'{person.person_name} had job {person.job.job_name} for {duration} days in dept: {person.job.job_department.dept_id.name}'
            )