Python_scripts/3_AZALEE/rpg_to_db.py
2024-07-31 17:10:56 +02:00

70 lines
2.4 KiB
Python

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from pycen import con
import geopandas as gpd
from datetime import datetime as dt
file = '/home/colas/Documents/tmp/rpg/RPG_2-0__SHP_LAMB93_R84_2022-01-01.7z/RPG_2-0__SHP_LAMB93_R84_2022-01-01/RPG/1_DONNEES_LIVRAISON_2023-08-01/RPG_2-0_SHP_LAMB93_R84-2022/PARCELLES_GRAPHIQUES.shp'
name_table = 'rpg_parcelles_graphiques_reg'
name_schema = 'ref_territoire'
thisyear = dt.now().year-2
df = gpd.read_file(file)
df.columns = df.columns.str.lower()
# df = df.set_geometry('geom')
df.rename_geometry('geom', inplace=True)
if not df.crs:
df.set_crs(epsg=2154, inplace=True)
if df.crs.srs != 'epsg:2154':
df.to_crs(epsg=2154, inplace=True)
exist_table = con.dialect.get_table_names(con, schema = name_schema)
if name_table in exist_table:
sql = """ALTER TABLE {sch}.{tab} RENAME TO {sch}.{othertab};
""".format(sch=name_schema,tab=name_table,othertab=name_table.replace('rpg','rpg'+str(thisyear-1)))
with con.begin() as cnx:
cnx.execute(sql)
df.to_postgis(
name = name_table,
con = con,
schema = name_schema,
if_exists = 'replace',
index = False
)
sql = """ALTER TABLE {sch}.{tab} OWNER TO cen_admin;
GRANT ALL ON TABLE {sch}.{tab} TO cen_admin;
GRANT ALL ON TABLE {sch}.{tab} TO grp_admin;
GRANT SELECT ON TABLE {sch}.{tab} TO grp_consult;
""".format(sch=name_schema,tab=name_table)
comment = """COMMENT ON TABLE {sch}.{tab} IS 'Version {v} 2.1 - Table des parcelles graphiques de la région Auvergne Rhône-Alpes.'""".format(sch=name_schema,tab=name_table,v=thisyear)
with con.begin() as cnx:
cnx.execute(sql)
cnx.execute(comment)
if 'rpg' in name_table:
v_tab = 'v_'+name_table.replace('reg','')+'isere'
lst_col = ','.join(tuple('s.'+df.columns))
sql = """CREATE OR REPLACE VIEW {sch}.{v_tab}
AS SELECT {cols}
FROM {sch}.{tab} s,
ref_territoire.dept_isere reg
WHERE st_intersects(s.geom, reg.geom);
ALTER TABLE {sch}.{v_tab} OWNER TO cen_admin;
GRANT ALL ON TABLE {sch}.{v_tab} TO cen_admin;
GRANT ALL ON TABLE {sch}.{v_tab} TO grp_admin;
GRANT SELECT ON TABLE {sch}.{v_tab} TO grp_consult;""".format(sch=name_schema,tab=name_table,v_tab=v_tab,cols=lst_col)
comment = """COMMENT ON VIEW {sch}.{v_tab} IS 'Version {v} 2.1 - Table des parcelles graphiques de l''isere.'""".format(sch=name_schema,v_tab=v_tab,v=thisyear)
with con.begin() as cnx:
cnx.execute(sql)
cnx.execute(comment)