code: def _query_db(self, mapping):
          
          model = self.models[mapping.get("table")]
  
          # Use primary key instead of the field mapped to SF Id
          fields = mapping.get("fields", {}).copy()
          if mapping["oid_as_pk"]:
              del fields["Id"]
          id_column = model.__table__.primary_key.columns.keys()[0]
          columns = [getattr(model, id_column)]
  
          for f in fields.values():
              columns.append(model.__table__.columns[f])
          lookups = mapping.get("lookups", {}).copy()
          for lookup in lookups.values():
              lookup["aliased_table"] = aliased(
                  self.metadata.tables["{}_sf_ids".format(lookup["table"])]
              )
              columns.append(lookup["aliased_table"].columns.sf_id)
  
          query = self.session.query(*columns)
          if "record_type" in mapping and hasattr(model, "record_type"):
              query = query.filter(model.record_type == mapping["record_type"])
          if "filters" in mapping:
              filter_args = []
              for f in mapping["filters"]:
                  filter_args.append(text(f))
              query = query.filter(*filter_args)
          for sf_field, lookup in lookups.items():
              # Outer join with lookup ids table:
              # returns main obj even if lookup is null
              key_field = get_lookup_key_field(lookup, sf_field)
              value_column = getattr(model, key_field)
              query = query.outerjoin(
                  lookup["aliased_table"],
                  lookup["aliased_table"].columns.id == value_column,
              )
              # Order by foreign key to minimize lock contention
              # by trying to keep lookup targets in the same batch
              lookup_column = getattr(model, key_field)
              query = query.order_by(lookup_column)
          self.logger.info(str(query))
          return query
docs: Build a query to retrieve data from the local db.
  
          Includes columns from the mapping
          as well as joining to the id tables to get real SF ids
          for lookups.