Exemple #1
0
def test_upsert_individual_values1(pandabase_loaded_db, constants):
    """upsert to update rows with only 1 of 5 values (and index) from full dataframe"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)

    df = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    df2 = pd.DataFrame(index=df.index, columns=df.columns)
    for col in df2.columns:
        df2[col] = df2[col].astype(df[col].dtype)

    df2.loc[df2.index[0], 'float'] = 9.9
    df2.loc[df2.index[1], 'integer'] = 999
    df2.loc[df2.index[2], 'string'] = 'nah'
    df2.loc[df2.index[3], 'date'] = pd.to_datetime('1968-01-01', utc=True)

    pb.to_sql(df2,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert')

    # check against pandabase read
    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)

    df.loc[df.index[0], 'float'] = 9.9
    df.loc[df.index[1], 'integer'] = 999
    df.loc[df.index[2], 'string'] = 'nah'
    df.loc[df.index[3], 'date'] = pd.to_datetime('1968-01-01', utc=True)

    assert companda(df, loaded)
Exemple #2
0
def test_create_select_table_range_datetime_index(empty_db, simple_df,
                                                  constants):
    """add a new table with explicit index, read it back with pandabase, check equality"""
    simple_df.index = simple_df.date
    simple_df = simple_df.drop('date', axis=1)

    table = pb.to_sql(simple_df,
                      table_name='sample',
                      con=empty_db,
                      how='create_only')

    # print(table.columns)
    assert table.columns['date'].primary_key
    assert pb.has_table(empty_db, 'sample')

    loaded0 = pb.read_sql('sample',
                          con=empty_db,
                          lowest=simple_df.index[-1],
                          highest=simple_df.index[0])
    print(loaded0)
    assert len(loaded0) == 0

    loaded = pb.read_sql('sample',
                         con=empty_db,
                         lowest=simple_df.index[0],
                         highest=simple_df.index[-1])
    assert pb.companda(loaded, simple_df, ignore_all_nan_columns=True)
Exemple #3
0
def test_upsert_individual_values2(pandabase_loaded_db, constants):
    """upsert to update rows with only 1 of 5 values (and index) from incomplete DataFrame"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)

    df = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    df2 = pd.DataFrame(index=df.index, columns=df.columns)
    for col in df2.columns:
        df2[col] = df2[col].astype(df[col].dtype)

    df2.loc[df2.index[0], 'float'] = 9.9
    df2.loc[df2.index[3], 'date'] = pd.to_datetime('1968-01-01', utc=True)

    pb.to_sql(pd.DataFrame(index=df2.index[:1], columns=['float'], data=[9.9]),
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert')
    pb.to_sql(pd.DataFrame(index=df2.index[3:4],
                           columns=['date'],
                           data=[pd.to_datetime('1968-01-01', utc=True)]),
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert')

    # check against pandabase read
    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)

    df.loc[df.index[0], 'float'] = 9.9
    df.loc[df.index[3], 'date'] = pd.to_datetime('1968-01-01', utc=True)

    assert companda(df, loaded)
Exemple #4
0
def test_select_fails_multi_index(empty_db, multi_index_df, lowest):
    """add a new minimal table & read it back with pandabase - select all"""
    pb.to_sql(multi_index_df,
              table_name='sample_mi',
              con=empty_db,
              how='create_only',
              )

    with pytest.raises(Exception):
        pb.read_sql(con=empty_db, table_name='sample_mi', highest=(1000, 1000), lowest=lowest)
Exemple #5
0
def test_auto_index_add_valid_bool(minimal_df, empty_db, constants):
    pb.to_sql(
        minimal_df,
        table_name=constants.TABLE_NAME,
        con=empty_db,
        how='create_only',
        auto_index=True,
    )
    assert pb.has_table(empty_db, constants.TABLE_NAME)

    df = pd.DataFrame(index=[101, 102, 103],
                      columns=['boolean'],
                      data=[True, False, None])

    pb.to_sql(
        df,
        table_name=constants.TABLE_NAME,
        con=empty_db,
        how='append',
        auto_index=True,
    )

    df = pb.read_sql(constants.TABLE_NAME, con=empty_db)

    # Int64Dtype is a fine way to store nullable boolean values
    # Stored in database as boolean or NULL so the data can only be 0, 1, or None
    assert is_bool_dtype(df.boolean) or is_integer_dtype(df.boolean)

    # assume values were loaded in order:
    x = len(df)
    assert df.loc[x - 2, 'boolean']
    assert not df.loc[x - 1, 'boolean']
    assert pd.np.isnan(df.loc[x, 'boolean'])
    with pytest.raises(KeyError):
        _ = df.loc[x + 1, 'boolean']
Exemple #6
0
def test_upsert_new_cols(pandabase_loaded_db, constants, col_to_duplicate):
    """upsert new rows with only 1 of 5 values (and index)"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)
    df = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    df['bonus_col'] = df[col_to_duplicate].copy()

    pb.to_sql(df,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert',
              add_new_columns=True)

    # check against pandabase read
    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    assert companda(df, loaded)
    assert 'bonus_col' in df.columns
Exemple #7
0
def test_select_table_range_fails_different_index(empty_db, simple_df,
                                                  constants):
    """add a new table with explicit index, read it back with pandabase, check equality"""
    simple_df.index = simple_df.date
    simple_df = simple_df.drop('date', axis=1)

    pb.to_sql(simple_df, table_name='sample', con=empty_db, how='create_only')

    with pytest.raises(Exception):
        _ = pb.read_sql('sample', con=empty_db, lowest=0, highest=12)
Exemple #8
0
def test_create_table_multi_index(empty_db, multi_index_df_4, how):
    """add a new minimal table & read it back with pandabase"""
    table = pb.to_sql(multi_index_df_4,
                      table_name='sample_mi',
                      con=empty_db,
                      how=how,
                      )

    loaded = pb.read_sql(con=empty_db, table_name='sample_mi')

    assert companda(multi_index_df_4, loaded)
Exemple #9
0
def test_select_some_multi_index(empty_db, multi_index_df, lowest, length):
    """add a new minimal table & read it back with pandabase - select all"""
    table = pb.to_sql(multi_index_df,
                      table_name='sample_mi',
                      con=empty_db,
                      how='create_only',
                      )

    loaded = pb.read_sql(con=empty_db, table_name='sample_mi', highest=(1000, 1000), lowest=lowest)
    print('\n', loaded)

    assert len(loaded) == length
Exemple #10
0
def test_upsert_complete_rows(pandabase_loaded_db, constants):
    """upsert, changing individual values"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)
    df = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    assert df.date.dt.tz == UTC

    df.loc[778, 'float'] = 9.9
    df.loc[779, 'integer'] = 999
    df.loc[780, 'string'] = 'nah'
    df.loc[781, 'date'] = pd.to_datetime('1968-01-01', utc=True)

    # check that all values still exist
    assert df.loc[1, 'integer'] == 778
    assert df.date.dt.tz == UTC

    pb.to_sql(df,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert')

    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    assert companda(df, loaded)
Exemple #11
0
def test_create_select_table_index(session_db, simple_df, constants):
    """add a new table with explicit index, read it back with pandabase, check equality"""
    table = pb.to_sql(simple_df,
                      table_name='sample',
                      con=session_db,
                      how='create_only')

    # print(table.columns)
    assert table.columns[constants.SAMPLE_INDEX_NAME].primary_key
    assert pb.has_table(session_db, 'sample')

    loaded = pb.read_sql('sample', con=session_db)
    assert pb.companda(loaded, simple_df, ignore_all_nan_columns=True)
Exemple #12
0
def test_upsert_incomplete_rows(pandabase_loaded_db, constants):
    """upsert new rows with only 1 of 5 values (and index)"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)
    df = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)

    df.loc[11, 'float'] = 9.9
    df.loc[12, 'integer'] = 999
    df.loc[13, 'string'] = 'nah'
    df.loc[14, 'date'] = pd.to_datetime('1968-01-01', utc=True)

    # check that these values exist
    assert df.loc[1, 'integer'] == 778
    assert pd.isna(df.loc[11, 'integer'])
    assert df.loc[13, 'string'] == 'nah'

    pb.to_sql(df,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert')

    # check against pandabase read
    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    assert companda(df, loaded)
Exemple #13
0
def test_create_read_table_no_index(empty_db, minimal_df):
    """add a new minimal table & read it back with pandabase"""
    table = pb.to_sql(minimal_df,
                      table_name='sample',
                      con=empty_db,
                      how='create_only',
                      auto_index=True,
                      )

    # print(table.columns)
    assert table.columns[PANDABASE_DEFAULT_INDEX].primary_key
    loaded = pb.read_sql('sample', con=empty_db)

    assert pb.has_table(empty_db, 'sample')
    assert pb.companda(loaded, minimal_df, ignore_index=True)
Exemple #14
0
def test_add_column_to_database(pandabase_loaded_db, actually_do, constants):
    """possibly add new column to db"""
    name = 'a_new_column'
    col = sqa.Column(name, primary_key=False, type_=Integer, nullable=True)
    if actually_do:
        pb.add_columns_to_db(col,
                             table_name=constants.TABLE_NAME,
                             con=pandabase_loaded_db)
    df = pb.read_sql(table_name=constants.TABLE_NAME, con=pandabase_loaded_db)

    if actually_do:
        assert name in df.columns
        assert is_integer_dtype(df[name])
    else:
        assert name not in df.columns
Exemple #15
0
def test_select_all_multi_index(empty_db, multi_index_df):
    """add a new minimal table & read it back with pandabase - select all"""
    table = pb.to_sql(multi_index_df,
                      table_name='sample_mi',
                      con=empty_db,
                      how='create_only',
                      )

    # print(table.columns)
    assert table.columns['this'].primary_key
    assert table.columns['that'].primary_key

    loaded = pb.read_sql(con=empty_db, table_name='sample_mi', highest=(100, 100), lowest=(0, 0))
    print('\n', loaded)

    assert companda(multi_index_df, loaded)
Exemple #16
0
def test_create_table_multi_index(empty_db, multi_index_df, how):
    """add a new minimal table & read it back with pandabase"""
    table = pb.to_sql(multi_index_df,
                      table_name='sample_mi',
                      con=empty_db,
                      how=how,
                      )

    # print(table.columns)
    assert table.columns['this'].primary_key
    assert table.columns['that'].primary_key

    loaded = pb.read_sql(con=empty_db, table_name='sample_mi')
    print('\n', loaded)

    assert companda(multi_index_df, loaded)
Exemple #17
0
def test_coerce_integer(pandabase_loaded_db, how, constants):
    """insert an integer into float column"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)

    df = pd.DataFrame(index=[1], columns=['integer'], data=[[77.0]])
    df.index.name = constants.SAMPLE_INDEX_NAME
    types = df.dtypes

    pb.to_sql(df,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how='upsert')

    for col in df.columns:
        assert types[col] == df.dtypes[col]

    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    assert loaded.loc[1, 'integer'] == 77
Exemple #18
0
def test_add_new_rows(pandabase_loaded_db, simple_df, how, constants):
    """upsert or append new complete rows"""
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)

    df = simple_df.copy()
    df.index = df.index + 100

    pb.to_sql(df,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how=how)

    loaded = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)
    # print('loaded post-upsert by pandabase:')
    # print(loaded)

    assert loaded.isna().sum().sum() == 0
    assert companda(simple_df, loaded.loc[simple_df.index])
    assert companda(df, loaded.loc[df.index])
Exemple #19
0
def test_create_read_table_with_different_index(session_db, simple_df, table_name, index_col_name):
    """create new tables in empty db, using different col types as index, read with pandabase"""
    orig_df = simple_df.copy()
    orig_df.index = orig_df[index_col_name]
    print(orig_df[index_col_name])
    print(orig_df.index)
    orig_df = orig_df.drop(index_col_name, axis=1)

    table = pb.to_sql(orig_df,
                      table_name=table_name,
                      con=session_db,
                      how='create_only')

    assert table.columns[index_col_name].primary_key
    assert pb.has_table(session_db, table_name)

    loaded = pb.read_sql(table_name, con=session_db)
    c = pb.companda(loaded, orig_df, ignore_all_nan_columns=True)
    if not c:
        raise ValueError(c.message)
Exemple #20
0
def test_append_auto_index(empty_db, minimal_df):
    """add a new minimal table; add it again"""
    pb.to_sql(minimal_df,
              table_name='sample',
              con=empty_db,
              auto_index=True,
              how='create_only')
    table2 = pb.to_sql(minimal_df,
                       table_name='sample',
                       con=empty_db,
                       auto_index=True,
                       how='append')

    assert table2.columns[PANDABASE_DEFAULT_INDEX].primary_key
    loaded = pb.read_sql('sample', con=empty_db)

    assert pb.has_table(empty_db, 'sample')
    double_df = pd.concat([minimal_df, minimal_df], ignore_index=True)
    assert pb.companda(loaded, double_df, ignore_index=True)
    assert len(loaded) == len(minimal_df) * 2
Exemple #21
0
def test_coerce_float_to_integer_multi(multi_index_df, empty_db, constants):
    """insert a float into integer column"""
    mi = multi_index_df.copy().index
    assert mi.names[0] is not None
    assert mi.names[1] is not None
    pb.to_sql(multi_index_df, con=empty_db, table_name=constants.TABLE_NAME)

    df = pd.DataFrame(columns=['integer'], data=[[77.0]], index=mi[:1])
    assert df.index.names[0] is not None
    assert df.index.names[1] is not None
    print('\n', df)
    print()
    types = df.dtypes

    pb.to_sql(df, table_name=constants.TABLE_NAME, con=empty_db, how='upsert')

    for col in df.columns:
        assert types[col] == df.dtypes[col]

    loaded = pb.read_sql(constants.TABLE_NAME, con=empty_db)
    assert loaded.loc[mi[0], 'integer'] == 77
Exemple #22
0
def test_select_pandas_table(pandas_loaded_db, simple_df, constants):
    """using pandabase.read_sql:
    read pandas-written table containing simple_df,

    this test fails because: when pandas writes the entry, it does not create
    an explicit primary key. the table is treated as a multiindex"""
    assert has_table(pandas_loaded_db, constants.TABLE_NAME)

    df = pb.read_sql(constants.TABLE_NAME, pandas_loaded_db)

    # line up pk since Pandas doesn't deal with it well
    simple_df[simple_df.index.name] = simple_df.index
    simple_df.index.name = None
    orig_columns = make_clean_columns_dict(simple_df)

    loaded_columns = make_clean_columns_dict(df)
    for key in orig_columns.keys():
        print(key)
        if key == 'nan':
            continue
        assert_sqla_types_equivalent(orig_columns[key], loaded_columns[key])
    assert companda(df, simple_df)
Exemple #23
0
def test_upsert_valid_bool(pandabase_loaded_db, how, constants):
    assert pb.has_table(pandabase_loaded_db, constants.TABLE_NAME)

    df = pd.DataFrame(index=[101, 102, 103],
                      columns=['boolean'],
                      data=[True, False, None])
    df.index.name = constants.SAMPLE_INDEX_NAME

    pb.to_sql(df,
              table_name=constants.TABLE_NAME,
              con=pandabase_loaded_db,
              how=how)

    df = pb.read_sql(constants.TABLE_NAME, con=pandabase_loaded_db)

    # Int64Dtype is a fine way to store nullable boolean values
    # Stored in database as boolean or NULL so the data can only be 0, 1, or None
    assert is_bool_dtype(df.boolean) or is_integer_dtype(df.boolean)
    assert df.loc[101, 'boolean']
    assert not df.loc[102, 'boolean']
    assert pd.np.isnan(df.loc[103, 'boolean'])
    with pytest.raises(KeyError):
        _ = df.loc[104, 'boolean']