(cls)
| 101 | |
| 102 | @classmethod |
| 103 | def setup_session(cls): |
| 104 | global sharded_session |
| 105 | shard_lookup = { |
| 106 | "North America": "north_america", |
| 107 | "Asia": "asia", |
| 108 | "Europe": "europe", |
| 109 | "South America": "south_america", |
| 110 | } |
| 111 | |
| 112 | def shard_chooser(mapper, instance, clause=None): |
| 113 | if isinstance(instance, WeatherLocation): |
| 114 | return shard_lookup[instance.continent] |
| 115 | else: |
| 116 | return shard_chooser(mapper, instance.location) |
| 117 | |
| 118 | def identity_chooser( |
| 119 | mapper, |
| 120 | primary_key, |
| 121 | *, |
| 122 | lazy_loaded_from, |
| 123 | execution_options, |
| 124 | bind_arguments, |
| 125 | **kw, |
| 126 | ): |
| 127 | return ["north_america", "asia", "europe", "south_america"] |
| 128 | |
| 129 | def execute_chooser(orm_context): |
| 130 | ids = [] |
| 131 | |
| 132 | query = orm_context.statement |
| 133 | |
| 134 | class FindContinent(sql.ClauseVisitor): |
| 135 | def visit_binary(self, binary): |
| 136 | if binary.left.shares_lineage( |
| 137 | weather_locations.c.continent |
| 138 | ): |
| 139 | if binary.operator == operators.eq: |
| 140 | ids.append(shard_lookup[binary.right.value]) |
| 141 | elif binary.operator == operators.in_op: |
| 142 | for value in binary.right.value: |
| 143 | ids.append(shard_lookup[value]) |
| 144 | |
| 145 | if isinstance(query, Select) and query.whereclause is not None: |
| 146 | FindContinent().traverse(query.whereclause) |
| 147 | if len(ids) == 0: |
| 148 | return ["north_america", "asia", "europe", "south_america"] |
| 149 | else: |
| 150 | return ids |
| 151 | |
| 152 | sharded_session = sessionmaker(class_=ShardedSession, autoflush=True) |
| 153 | sharded_session.configure( |
| 154 | shards={ |
| 155 | "north_america": db1, |
| 156 | "asia": db2, |
| 157 | "europe": db3, |
| 158 | "south_america": db4, |
| 159 | }, |
| 160 | shard_chooser=shard_chooser, |
no test coverage detected