35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211 | @support_hooks
class DBWriter(FrozenModel):
"""Class specifies schema and table where you can write your dataframe. [](/hooks/)
!!! success "Added in 0.1.0"
!!! info "Changed in 0.8.0"
Moved `onetl.core.DBReader` → `onetl.db.DBReader`
Parameters
----------
connection : [onetl.connection.DBConnection][]
Class which contains DB connection properties. See [db-connections][] section.
target : str
Table/collection/etc name to write data to.
If connection has schema support, you need to specify the full name of the source
including the schema, e.g. `schema.name`.
!!! info "Changed in 0.7.0"
Renamed `table` → `target`
options : dict | WriteOptions, default: `None`
Spark write options. Can be in form of special `WriteOptions` object or a dict.
For example:
`{"if_exists": "replace_entire_table", "compression": "snappy"}`
or
`Hive.WriteOptions(if_exists="replace_entire_table", compression="snappy")`
!!! note
Some sources does not support writing options.
Examples
--------
=== "Minimal example"
```python
from onetl.connection import Postgres
from onetl.db import DBWriter
postgres = Postgres(...)
writer = DBWriter(
connection=postgres,
target="fiddle.dummy",
)
```
=== "With custom write options"
```python
from onetl.connection import Postgres
from onetl.db import DBWriter
postgres = Postgres(...)
options = Postgres.WriteOptions(if_exists="replace_entire_table", batchsize=1000)
writer = DBWriter(
connection=postgres,
target="fiddle.dummy",
options=options,
)
```
"""
connection: BaseDBConnection
target: str = Field(alias=avoid_alias("table")) # type: ignore[literal-required]
options: Optional[GenericOptions] = None
_connection_checked: bool = PrivateAttr(default=False)
@validator("target", always=True)
def validate_target(cls, value: str, values):
if "connection" not in values:
return value
connection: BaseDBConnection = values["connection"]
return connection.dialect.validate_name(value)
@validator("options", pre=True, always=True)
def validate_options(cls, options, values):
connection = values.get("connection")
write_options_class = getattr(connection, "WriteOptions", None)
if write_options_class:
return write_options_class.parse(options)
if options:
msg = f"{connection.__class__.__name__} does not implement WriteOptions, but {options!r} is passed"
raise ValueError(msg)
return None
@slot
def run(self, df: DataFrame) -> None:
"""
Method for writing your df to specified target. [](/hooks/)
!!! note
Method does support only **batching** DataFrames.
!!! success "Added in 0.1.0"
Parameters
----------
df : pyspark.sql.dataframe.DataFrame
Spark dataframe
Examples
--------
Write dataframe to target:
```python
writer.run(df)
```
"""
if df.isStreaming:
msg = f"DataFrame is streaming. {self.__class__.__name__} supports only batch DataFrames."
raise ValueError(msg)
entity_boundary_log(log, msg=f"{self.__class__.__name__}.run() starts")
if not self._connection_checked:
self._log_parameters()
log_dataframe_schema(log, df)
self.connection.check()
self._connection_checked = True
with SparkMetricsRecorder(self.connection.spark) as recorder:
try:
job_description = f"{self.__class__.__name__}.run({self.target}) -> {self.connection}"
with override_job_description(self.connection.spark, job_description):
self.connection.write_df_to_target(
df=df,
target=str(self.target),
**self._get_write_kwargs(),
)
except Exception:
metrics = recorder.metrics()
# SparkListener is not a reliable source of information, metrics may or may not be present.
# Because of this we also do not return these metrics as method result
if metrics.output.is_empty:
log.error( # noqa: TRY400
"|%s| Error while writing dataframe.",
self.__class__.__name__,
)
else:
log.error( # noqa: TRY400
"|%s| Error while writing dataframe. Target MAY contain partially written data!",
self.__class__.__name__,
)
self._log_metrics(metrics)
raise
finally:
self._log_metrics(recorder.metrics())
entity_boundary_log(log, msg=f"{self.__class__.__name__}.run() ends", char="-")
def _log_parameters(self) -> None:
log.info("|Spark| -> |%s| Writing DataFrame to target using parameters:", self.connection.__class__.__name__)
log_with_indent(log, "target = '%s'", self.target)
options = self.options.dict(by_alias=True, exclude_none=True) if self.options else None
log_options(log, options)
def _get_write_kwargs(self) -> dict:
if self.options:
return {"options": self.options}
return {}
def _log_metrics(self, metrics: SparkCommandMetrics) -> None:
if not metrics.is_empty:
log.debug("|%s| Recorded metrics (some values may be missing!):", self.__class__.__name__)
log_lines(log, str(metrics), level=logging.DEBUG)
|