#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import pandas as pd import pyzh zh = pyzh.zh() con = pyzh.con sch = 'zones_humides' lst_site_old = ['38RD0146','38RD0147'] lst_site_new = ['38RD0164','38RD0165'] df = zh.get_fct(id_site=lst_site_old) geomsite = zh.get_sitesGeom(id_site=lst_site_new) aut = pyzh.pers.get_auteur() tab = 'r_site_fctecosociopatri' rtab_aut = 'r_rsitefct_auteur' id_rsiteaut = 'id_sitefct' delim = zh._get_param(param_table='param_fct_eco_socio_patri',type_table='type_param_fct') df.drop( columns=['id','valid', 'date_geom', 'auteur_geom', 'desc_param','type'], inplace=True, errors='ignore') for i, s in enumerate(lst_site_new): df.loc[df.id_site==lst_site_old[i], 'id_site'] = s df.loc[df.id_site==s, ['id_geom_site']] = geomsite.loc[geomsite.id_site==s,'id'].values[0].astype(str) df['id_geom_site'] = df.id_geom_site.astype(int) df['id_fct'] = df['nom_fct'] df['id_fct'] = df['id_fct'].replace(delim.nom.tolist(),delim.id.tolist()) df['date'] = df.date_fctec df.drop(columns=['id_site','nom_fct','date_fctec'], inplace=True) lst_idgeom = df.id_geom_site.unique().astype(str) # check si data in bdd sql = 'select exists(select * from {sch}.{tab} where id_geom_site in ({lst_id}));'.format( sch=sch, tab=tab, lst_id=','.join(lst_idgeom) ) res = pd.read_sql(sql,con) if res.exists[0]: # delete if exist sql = 'delete from {sch}.{tab} where id_geom_site in ({lst_id});'.format( sch=sch, tab=tab, lst_id=','.join(lst_idgeom) ) pd.read_sql(sql,con) # insert new line in bdd col = df.columns[~df.columns.str.contains('auteur')] colaut = df.columns[df.columns.str.contains('auteur')] df[col].to_sql( tab, con, schema=sch, if_exists='append',index=False,method='multi' ) # Récupération des nouveaux ids insérés sql = 'select * from {sch}.{tab} where id_geom_site in ({lst_id});'.format( sch=sch, tab=tab, lst_id=','.join(lst_idgeom) ) res = pd.read_sql(sql,con) df = df.merge(res, how='left', on=[*col]) ins_aut = df[['id',*colaut]].copy() aut['nom_prenom'] = aut.nom + ' ' + aut.prenom aut.loc[aut.nom_prenom.isna(), 'nom_prenom'] = aut.loc[aut.nom_prenom.isna(), 'nom'] ins_aut[colaut] = ins_aut[colaut].replace(aut.nom_prenom.tolist(), aut.id.tolist()) ins_aut.columns = [id_rsiteaut, 'id_auteur'] ins_aut.to_sql( rtab_aut, con, schema=sch, if_exists='append',index=False,method='multi')