claudevdm commented on code in PR #33841: URL: https://github.com/apache/beam/pull/33841#discussion_r1940258112
########## sdks/python/apache_beam/ml/rag/ingestion/alloydb.py: ########## @@ -0,0 +1,494 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from dataclasses import dataclass +from typing import Any +from typing import Callable +from typing import Dict +from typing import List +from typing import Literal +from typing import NamedTuple +from typing import Optional +from typing import Type +from typing import Union + +import apache_beam as beam +from apache_beam.coders import registry +from apache_beam.coders.row_coder import RowCoder +from apache_beam.io.jdbc import WriteToJdbc +from apache_beam.ml.rag.ingestion.base import VectorDatabaseWriteConfig +from apache_beam.ml.rag.types import Chunk + + +@dataclass +class AlloyDBConnectionConfig: + """Configuration for AlloyDB database connection. + + Provides connection details and options for connecting to an AlloyDB + instance. + + Attributes: + jdbc_url: JDBC URL for the AlloyDB instance. + Example: 'jdbc:postgresql://host:port/database' + username: Database username. + password: Database password. + connection_properties: Optional JDBC connection properties dict. + Example: {'ssl': 'true'} + connection_init_sqls: Optional list of SQL statements to execute when + connection is established. + autosharding: Enable automatic re-sharding of bundles to scale the + number of shards with workers. + max_connections: Optional number of connections in the pool. + Use negative for no limit. + write_batch_size: Optional write batch size for bulk operations. + + Example: + >>> config = AlloyDBConnectionConfig( + ... jdbc_url='jdbc:postgresql://localhost:5432/mydb', + ... username='user', + ... password='pass', + ... connection_properties={'ssl': 'true'}, + ... max_connections=10 + ... ) + """ + jdbc_url: str + username: str + password: str + connection_properties: Optional[Dict[str, str]] = None + connection_init_sqls: Optional[List[str]] = None + autosharding: Optional[bool] = None + max_connections: Optional[int] = None + write_batch_size: Optional[int] = None + + +@dataclass +class ConflictResolution: + """Specification for how to handle conflicts during insert. + + Configures conflict handling behavior when inserting records that may + violate unique constraints. + + Attributes: + on_conflict_fields: Field(s) that determine uniqueness. Can be a single + field name or list of field names for composite constraints. + action: How to handle conflicts - either "UPDATE" or "IGNORE". + UPDATE: Updates existing record with new values. + IGNORE: Skips conflicting records. + update_fields: Optional list of fields to update on conflict. If None, + all non-conflict fields are updated. + + Examples: + Simple primary key: + >>> ConflictResolution("id") + + Composite key with specific update fields: + >>> ConflictResolution( + ... on_conflict_fields=["source", "timestamp"], + ... action="UPDATE", + ... update_fields=["embedding", "content"] + ... ) + + Ignore conflicts: + >>> ConflictResolution( + ... on_conflict_fields="id", + ... action="IGNORE" + ... ) + """ + on_conflict_fields: Union[str, List[str]] + action: Literal["UPDATE", "IGNORE"] = "UPDATE" + update_fields: Optional[List[str]] = None + + def get_conflict_clause(self) -> str: + """Get conflict clause with update fields.""" + fields = [self.on_conflict_fields] \ + if isinstance(self.on_conflict_fields, str) \ + else self.on_conflict_fields + + if self.action == "IGNORE": + return f"ON CONFLICT ({', '.join(fields)}) DO NOTHING" + + # update_fields should be set by query builder before this is called + assert self.update_fields is not None, \ + "update_fields must be set before generating conflict clause" + updates = [f"{field} = EXCLUDED.{field}" for field in self.update_fields] + return f"ON CONFLICT " \ + f"({', '.join(fields)}) DO UPDATE SET {', '.join(updates)}" + + +@dataclass +class ColumnSpec: + """Specification for mapping Chunk fields to SQL columns for insertion. + + Defines how to extract and format values from Chunks into database columns, + including type conversion and SQL type casting. + + Attributes: + name: The column name in the database table. + python_type: Python type for the column value (used in NamedTuple field) Review Comment: I think the supported types are anything that RowCoder can handle, I added this to the docstring. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
