/*-------------------------------------------------------------------------
*
* pg_hint_plan.c
- * Track statement execution in current/last transaction.
+ * do instructions or hints to the planner using C-style block comments
+ * of the SQL.
*
- * Copyright (c) 2011, PostgreSQL Global Development Group
- *
- * IDENTIFICATION
- * contrib/pg_hint_plan/pg_hint_plan.c
+ * Copyright (c) 2012, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
-#include "fmgr.h"
-#include "utils/elog.h"
-#include "utils/builtins.h"
-#include "utils/memutils.h"
+#include "commands/prepare.h"
+#include "miscadmin.h"
+#include "nodes/nodeFuncs.h"
+#include "optimizer/clauses.h"
#include "optimizer/cost.h"
+#include "optimizer/geqo.h"
#include "optimizer/joininfo.h"
#include "optimizer/pathnode.h"
#include "optimizer/paths.h"
+#include "optimizer/plancat.h"
+#include "optimizer/planner.h"
+#include "optimizer/prep.h"
+#include "optimizer/restrictinfo.h"
+#include "tcop/utility.h"
+#include "utils/lsyscache.h"
+#include "utils/memutils.h"
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
-#define HASH_ENTRIES 201
+#if PG_VERSION_NUM < 90100
+#error unsupported PostgreSQL version
+#endif
+
+#define BLOCK_COMMENT_START "/*"
+#define BLOCK_COMMENT_END "*/"
+#define HINT_COMMENT_KEYWORD "+"
+#define HINT_START BLOCK_COMMENT_START HINT_COMMENT_KEYWORD
+#define HINT_END BLOCK_COMMENT_END
+
+/* hint keywords */
+#define HINT_SEQSCAN "SeqScan"
+#define HINT_INDEXSCAN "IndexScan"
+#define HINT_BITMAPSCAN "BitmapScan"
+#define HINT_TIDSCAN "TidScan"
+#define HINT_NOSEQSCAN "NoSeqScan"
+#define HINT_NOINDEXSCAN "NoIndexScan"
+#define HINT_NOBITMAPSCAN "NoBitmapScan"
+#define HINT_NOTIDSCAN "NoTidScan"
+#define HINT_NESTLOOP "NestLoop"
+#define HINT_MERGEJOIN "MergeJoin"
+#define HINT_HASHJOIN "HashJoin"
+#define HINT_NONESTLOOP "NoNestLoop"
+#define HINT_NOMERGEJOIN "NoMergeJoin"
+#define HINT_NOHASHJOIN "NoHashJoin"
+#define HINT_LEADING "Leading"
+#define HINT_SET "Set"
+
+
+#define HINT_ARRAY_DEFAULT_INITSIZE 8
+
+#define parse_ereport(str, detail) \
+ ereport(pg_hint_plan_parse_messages, \
+ (errmsg("hint syntax error at or near \"%s\"", (str)), \
+ errdetail detail))
+
+#define skip_space(str) \
+ while (isspace(*str)) \
+ str++;
enum
{
- ENABLE_SEQSCAN = 0x01,
- ENABLE_INDEXSCAN = 0x02,
- ENABLE_BITMAPSCAN = 0x04,
- ENABLE_TIDSCAN = 0x08,
- ENABLE_NESTLOOP = 0x10,
- ENABLE_MERGEJOIN = 0x20,
- ENABLE_HASHJOIN = 0x40
-} TYPE_BITS;
+ ENABLE_SEQSCAN = 0x01,
+ ENABLE_INDEXSCAN = 0x02,
+ ENABLE_BITMAPSCAN = 0x04,
+ ENABLE_TIDSCAN = 0x08,
+} SCAN_TYPE_BITS;
-typedef struct tidlist
+enum
+{
+ ENABLE_NESTLOOP = 0x01,
+ ENABLE_MERGEJOIN = 0x02,
+ ENABLE_HASHJOIN = 0x04
+} JOIN_TYPE_BITS;
+
+#define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | ENABLE_BITMAPSCAN \
+ | ENABLE_TIDSCAN)
+#define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
+#define DISABLE_ALL_SCAN 0
+#define DISABLE_ALL_JOIN 0
+
+typedef struct Hint Hint;
+typedef struct PlanHint PlanHint;
+
+typedef Hint *(*HintCreateFunction) (const char *hint_str,
+ const char *keyword);
+typedef void (*HintDeleteFunction) (Hint *hint);
+typedef void (*HintDumpFunction) (Hint *hint, StringInfo buf);
+typedef int (*HintCmpFunction) (const Hint *a, const Hint *b);
+typedef const char *(*HintParseFunction) (Hint *hint, PlanHint *plan,
+ Query *parse, const char *str);
+
+/* hint types */
+#define NUM_HINT_TYPE 4
+typedef enum HintType
+{
+ HINT_TYPE_SCAN_METHOD,
+ HINT_TYPE_JOIN_METHOD,
+ HINT_TYPE_LEADING,
+ HINT_TYPE_SET
+} HintType;
+
+/* hint status */
+typedef enum HintStatus
{
- int nrels;
- Oid *oids;
-} TidList;
+ HINT_STATE_NOTUSED = 0, /* specified relation not used in query */
+ HINT_STATE_USED, /* hint is used */
+ HINT_STATE_DUPLICATION, /* specified hint duplication */
+ HINT_STATE_ERROR /* execute error (parse error does not include
+ * it) */
+} HintStatus;
+
+#define hint_state_enabled(hint) ((hint)->base.state == HINT_STATE_NOTUSED || \
+ (hint)->base.state == HINT_STATE_USED)
+
+/* common data for all hints. */
+struct Hint
+{
+ const char *hint_str; /* must not do pfree */
+ const char *keyword; /* must not do pfree */
+ HintType type;
+ HintStatus state;
+ HintDeleteFunction delete_func;
+ HintDumpFunction dump_func;
+ HintCmpFunction cmp_func;
+ HintParseFunction parser_func;
+};
+
+/* scan method hints */
+typedef struct ScanMethodHint
+{
+ Hint base;
+ char *relname;
+ List *indexnames;
+ unsigned char enforce_mask;
+} ScanMethodHint;
+
+/* join method hints */
+typedef struct JoinMethodHint
+{
+ Hint base;
+ int nrels;
+ char **relnames;
+ unsigned char enforce_mask;
+ Relids joinrelids;
+} JoinMethodHint;
+
+/* join order hints */
+typedef struct LeadingHint
+{
+ Hint base;
+ List *relations; /* relation names specified in Leading hint */
+} LeadingHint;
-typedef struct hash_entry
+/* change a run-time parameter hints */
+typedef struct SetHint
{
- TidList tidlist;
- unsigned char enforce_mask;
- struct hash_entry *next;
-} HashEntry;
+ Hint base;
+ char *name; /* name of variable */
+ char *value;
+} SetHint;
-static HashEntry *hashent[HASH_ENTRIES];
-#ifdef NOT_USED
-static bool (*org_cost_hook)(CostHookType type, PlannerInfo *root, Path *path1, Path *path2);
-#endif
-static bool print_log = false;
-static bool tweak_enabled = true;
+/*
+ * Describes a context of hint processing.
+ */
+struct PlanHint
+{
+ char *hint_str; /* original hint string */
+
+ /* all hint */
+ int nall_hints; /* # of valid all hints */
+ int max_all_hints; /* # of slots for all hints */
+ Hint **all_hints; /* parsed all hints */
+
+ /* # of each hints */
+ int num_hints[NUM_HINT_TYPE];
+
+ /* for scan method hints */
+ ScanMethodHint **scan_hints; /* parsed scan hints */
+ int init_scan_mask; /* initial value scan parameter */
+ Index parent_relid; /* inherit parent table relid */
+ ScanMethodHint *parent_hint; /* inherit parent table scan hint */
+
+ /* for join method hints */
+ JoinMethodHint **join_hints; /* parsed join hints */
+ int init_join_mask; /* initial value join parameter */
+ List **join_hint_level;
+
+ /* for Leading hint */
+ LeadingHint *leading_hint; /* parsed last specified Leading hint */
+
+ /* for Set hints */
+ SetHint **set_hints; /* parsed Set hints */
+ GucContext context; /* which GUC parameters can we set? */
+};
+
+/*
+ * Describes a hint parser module which is bound with particular hint keyword.
+ */
+typedef struct HintParser
+{
+ char *keyword;
+ HintCreateFunction create_func;
+} HintParser;
/* Module callbacks */
void _PG_init(void);
void _PG_fini(void);
-Datum pg_add_hint(PG_FUNCTION_ARGS);
-Datum pg_clear_hint(PG_FUNCTION_ARGS);
-Datum pg_dump_hint(PG_FUNCTION_ARGS);
-Datum pg_enable_hint(bool arg, bool *isnull);
-Datum pg_enable_log(bool arg, bool *isnull);
-
-#ifdef NOT_USED
-static char *rels_str(PlannerInfo *root, Path *path);
-static void dump_rels(char *label, PlannerInfo *root, Path *path, bool found, bool enabled);
-static void dump_joinrels(char *label, PlannerInfo *root, Path *inpath, Path *outpath, bool found, bool enabled);
-static bool my_cost_hook(CostHookType type, PlannerInfo *root, Path *path1, Path *path2);
-#endif
-static void free_hashent(HashEntry *head);
-static unsigned int calc_hash(TidList *tidlist);
-#ifdef NOT_USED
-static HashEntry *search_ent(TidList *tidlist);
-#endif
-static join_search_hook_type org_join_search = NULL;
-
-static void build_join_hints(PlannerInfo *root, int level, List *initial_rels);
-static RelOptInfo *my_make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2);
-static RelOptInfo *my_join_search(PlannerInfo *root, int levels_needed,
- List *initial_rels);
-static void my_join_search_one_level(PlannerInfo *root, int level);
-static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel, ListCell *other_rels);
-static void make_rels_by_clauseless_joins(PlannerInfo *root, RelOptInfo *old_rel, ListCell *other_rels);
+static void pg_hint_plan_ProcessUtility(Node *parsetree,
+ const char *queryString,
+ ParamListInfo params, bool isTopLevel,
+ DestReceiver *dest,
+ char *completionTag);
+static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
+ ParamListInfo boundParams);
+static void pg_hint_plan_get_relation_info(PlannerInfo *root,
+ Oid relationObjectId,
+ bool inhparent, RelOptInfo *rel);
+static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root,
+ int levels_needed,
+ List *initial_rels);
+
+static Hint *ScanMethodHintCreate(const char *hint_str, const char *keyword);
+static void ScanMethodHintDelete(ScanMethodHint *hint);
+static void ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf);
+static int ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b);
+static const char *ScanMethodHintParse(ScanMethodHint *hint, PlanHint *plan,
+ Query *parse, const char *str);
+static Hint *JoinMethodHintCreate(const char *hint_str, const char *keyword);
+static void JoinMethodHintDelete(JoinMethodHint *hint);
+static void JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf);
+static int JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b);
+static const char *JoinMethodHintParse(JoinMethodHint *hint, PlanHint *plan,
+ Query *parse, const char *str);
+static Hint *LeadingHintCreate(const char *hint_str, const char *keyword);
+static void LeadingHintDelete(LeadingHint *hint);
+static void LeadingHintDump(LeadingHint *hint, StringInfo buf);
+static int LeadingHintCmp(const LeadingHint *a, const LeadingHint *b);
+static const char *LeadingHintParse(LeadingHint *hint, PlanHint *plan,
+ Query *parse, const char *str);
+static Hint *SetHintCreate(const char *hint_str, const char *keyword);
+static void SetHintDelete(SetHint *hint);
+static void SetHintDump(SetHint *hint, StringInfo buf);
+static int SetHintCmp(const SetHint *a, const SetHint *b);
+static const char *SetHintParse(SetHint *hint, PlanHint *plan, Query *parse,
+ const char *str);
+
+RelOptInfo *pg_hint_plan_standard_join_search(PlannerInfo *root,
+ int levels_needed,
+ List *initial_rels);
+void pg_hint_plan_join_search_one_level(PlannerInfo *root, int level);
+static void make_rels_by_clause_joins(PlannerInfo *root, RelOptInfo *old_rel,
+ ListCell *other_rels);
+static void make_rels_by_clauseless_joins(PlannerInfo *root,
+ RelOptInfo *old_rel,
+ ListCell *other_rels);
static bool has_join_restriction(PlannerInfo *root, RelOptInfo *rel);
+static void set_append_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
+ Index rti, RangeTblEntry *rte);
+static List *accumulate_append_subpath(List *subpaths, Path *path);
+static void set_dummy_rel_pathlist(RelOptInfo *rel);
+RelOptInfo *pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1,
+ RelOptInfo *rel2);
+
+
+/* GUC variables */
+static bool pg_hint_plan_enable = true;
+static bool pg_hint_plan_debug_print = false;
+static int pg_hint_plan_parse_messages = INFO;
+
+static const struct config_enum_entry parse_messages_level_options[] = {
+ {"debug", DEBUG2, true},
+ {"debug5", DEBUG5, false},
+ {"debug4", DEBUG4, false},
+ {"debug3", DEBUG3, false},
+ {"debug2", DEBUG2, false},
+ {"debug1", DEBUG1, false},
+ {"log", LOG, false},
+ {"info", INFO, false},
+ {"notice", NOTICE, false},
+ {"warning", WARNING, false},
+ {"error", ERROR, false},
+ /*
+ * {"fatal", FATAL, true},
+ * {"panic", PANIC, true},
+ */
+ {NULL, 0, false}
+};
+
+/* Saved hook values in case of unload */
+static ProcessUtility_hook_type prev_ProcessUtility = NULL;
+static planner_hook_type prev_planner = NULL;
+static get_relation_info_hook_type prev_get_relation_info = NULL;
+static join_search_hook_type prev_join_search = NULL;
-PG_FUNCTION_INFO_V1(pg_add_hint);
-PG_FUNCTION_INFO_V1(pg_clear_hint);
+/* フック関数をまたがって使用する情報を管理する */
+static PlanHint *global = NULL;
+
+/*
+ * EXECUTEコマンド実行時に、ステートメント名を格納する。
+ * その他のコマンドの場合は、NULLに設定する。
+ */
+static char *stmt_name = NULL;
+
+static const HintParser parsers[] = {
+ {HINT_SEQSCAN, ScanMethodHintCreate},
+ {HINT_INDEXSCAN, ScanMethodHintCreate},
+ {HINT_BITMAPSCAN, ScanMethodHintCreate},
+ {HINT_TIDSCAN, ScanMethodHintCreate},
+ {HINT_NOSEQSCAN, ScanMethodHintCreate},
+ {HINT_NOINDEXSCAN, ScanMethodHintCreate},
+ {HINT_NOBITMAPSCAN, ScanMethodHintCreate},
+ {HINT_NOTIDSCAN, ScanMethodHintCreate},
+ {HINT_NESTLOOP, JoinMethodHintCreate},
+ {HINT_MERGEJOIN, JoinMethodHintCreate},
+ {HINT_HASHJOIN, JoinMethodHintCreate},
+ {HINT_NONESTLOOP, JoinMethodHintCreate},
+ {HINT_NOMERGEJOIN, JoinMethodHintCreate},
+ {HINT_NOHASHJOIN, JoinMethodHintCreate},
+ {HINT_LEADING, LeadingHintCreate},
+ {HINT_SET, SetHintCreate},
+ {NULL, NULL}
+};
/*
* Module load callbacks
void
_PG_init(void)
{
- int i;
-
-#ifdef NOT_USED
- org_cost_hook = cost_hook;
- cost_hook = my_cost_hook;
-#endif
- org_join_search = join_search_hook;
- join_search_hook = my_join_search;
-
- for (i = 0 ; i < HASH_ENTRIES ; i++)
- hashent[i] = NULL;
+ /* Define custom GUC variables. */
+ DefineCustomBoolVariable("pg_hint_plan.enable",
+ "Instructions or hints to the planner using block comments.",
+ NULL,
+ &pg_hint_plan_enable,
+ true,
+ PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomBoolVariable("pg_hint_plan.debug_print",
+ "Logs each query's parse results of the hint.",
+ NULL,
+ &pg_hint_plan_debug_print,
+ false,
+ PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ DefineCustomEnumVariable("pg_hint_plan.parse_messages",
+ "Messege level of the parse error.",
+ NULL,
+ &pg_hint_plan_parse_messages,
+ INFO,
+ parse_messages_level_options,
+ PGC_USERSET,
+ 0,
+ NULL,
+ NULL,
+ NULL);
+
+ /* Install hooks. */
+ prev_ProcessUtility = ProcessUtility_hook;
+ ProcessUtility_hook = pg_hint_plan_ProcessUtility;
+ prev_planner = planner_hook;
+ planner_hook = pg_hint_plan_planner;
+ prev_get_relation_info = get_relation_info_hook;
+ get_relation_info_hook = pg_hint_plan_get_relation_info;
+ prev_join_search = join_search_hook;
+ join_search_hook = pg_hint_plan_join_search;
}
/*
* Module unload callback
+ * XXX never called
*/
void
_PG_fini(void)
{
- int i;
-
-#ifdef NOT_USED
- cost_hook = org_cost_hook;
-#endif
- join_search_hook = org_join_search;
+ /* Uninstall hooks. */
+ ProcessUtility_hook = prev_ProcessUtility;
+ planner_hook = prev_planner;
+ get_relation_info_hook = prev_get_relation_info;
+ join_search_hook = prev_join_search;
+}
- for (i = 0 ; i < HASH_ENTRIES ; i++)
- {
- free_hashent(hashent[i]);
- hashent[i] = NULL;
+/*
+ * create and delete functions the hint object
+ */
- }
+static Hint *
+ScanMethodHintCreate(const char *hint_str, const char *keyword)
+{
+ ScanMethodHint *hint;
+
+ hint = palloc(sizeof(ScanMethodHint));
+ hint->base.hint_str = hint_str;
+ hint->base.keyword = keyword;
+ hint->base.type = HINT_TYPE_SCAN_METHOD;
+ hint->base.state = HINT_STATE_NOTUSED;
+ hint->base.delete_func = (HintDeleteFunction) ScanMethodHintDelete;
+ hint->base.dump_func = (HintDumpFunction) ScanMethodHintDump;
+ hint->base.cmp_func = (HintCmpFunction) ScanMethodHintCmp;
+ hint->base.parser_func = (HintParseFunction) ScanMethodHintParse;
+ hint->relname = NULL;
+ hint->indexnames = NIL;
+ hint->enforce_mask = 0;
+
+ return (Hint *) hint;
}
-#ifdef NOT_USED
-char *rels_str(PlannerInfo *root, Path *path)
+static void
+ScanMethodHintDelete(ScanMethodHint *hint)
{
- char buf[4096];
- int relid;
- int first = 1;
- Bitmapset *tmpbms;
-
- if (path->pathtype == T_Invalid) return strdup("");
-
- tmpbms = bms_copy(path->parent->relids);
+ if (!hint)
+ return;
- buf[0] = 0;
- while ((relid = bms_first_member(tmpbms)) >= 0)
- {
- char idbuf[8];
- snprintf(idbuf, sizeof(idbuf), first ? "%d" : ", %d",
- root->simple_rte_array[relid]->relid);
- if (strlen(buf) + strlen(idbuf) < sizeof(buf))
- strcat(buf, idbuf);
- first = 0;
- }
-
- return strdup(buf);
+ if (hint->relname)
+ pfree(hint->relname);
+ list_free_deep(hint->indexnames);
+ pfree(hint);
}
-#endif
-static int oidsortcmp(const void *a, const void *b)
+static Hint *
+JoinMethodHintCreate(const char *hint_str, const char *keyword)
{
- const Oid oida = *((const Oid *)a);
- const Oid oidb = *((const Oid *)b);
-
- return oida - oidb;
+ JoinMethodHint *hint;
+
+ hint = palloc(sizeof(JoinMethodHint));
+ hint->base.hint_str = hint_str;
+ hint->base.keyword = keyword;
+ hint->base.type = HINT_TYPE_JOIN_METHOD;
+ hint->base.state = HINT_STATE_NOTUSED;
+ hint->base.delete_func = (HintDeleteFunction) JoinMethodHintDelete;
+ hint->base.dump_func = (HintDumpFunction) JoinMethodHintDump;
+ hint->base.cmp_func = (HintCmpFunction) JoinMethodHintCmp;
+ hint->base.parser_func = (HintParseFunction) JoinMethodHintParse;
+ hint->nrels = 0;
+ hint->relnames = NULL;
+ hint->enforce_mask = 0;
+ hint->joinrelids = NULL;
+
+ return (Hint *) hint;
}
-#ifdef NOT_USED
-static TidList *maketidlist(PlannerInfo *root, Path *path1, Path *path2)
+static void
+JoinMethodHintDelete(JoinMethodHint *hint)
{
- int relid;
- Path *paths[2] = {path1, path2};
- int i;
- int j = 0;
- int nrels = 0;
- TidList *ret = (TidList *)malloc(sizeof(TidList));
-
- for (i = 0 ; i < 2 ; i++)
- {
- if (paths[i] != NULL)
- nrels += bms_num_members(paths[i]->parent->relids);
- }
-
- ret->nrels = nrels;
- ret->oids = (Oid *)malloc(nrels * sizeof(Oid));
+ if (!hint)
+ return;
- for (i = 0 ; i < 2 ; i++)
+ if (hint->relnames)
{
- Bitmapset *tmpbms;
-
- if (paths[i] == NULL) continue;
-
- tmpbms= bms_copy(paths[i]->parent->relids);
+ int i;
- while ((relid = bms_first_member(tmpbms)) >= 0)
- ret->oids[j++] = root->simple_rte_array[relid]->relid;
+ for (i = 0; i < hint->nrels; i++)
+ pfree(hint->relnames[i]);
+ pfree(hint->relnames);
}
+ bms_free(hint->joinrelids);
+ pfree(hint);
+}
+
+static Hint *
+LeadingHintCreate(const char *hint_str, const char *keyword)
+{
+ LeadingHint *hint;
+
+ hint = palloc(sizeof(LeadingHint));
+ hint->base.hint_str = hint_str;
+ hint->base.keyword = keyword;
+ hint->base.type = HINT_TYPE_LEADING;
+ hint->base.state = HINT_STATE_NOTUSED;
+ hint->base.delete_func = (HintDeleteFunction)LeadingHintDelete;
+ hint->base.dump_func = (HintDumpFunction) LeadingHintDump;
+ hint->base.cmp_func = (HintCmpFunction) LeadingHintCmp;
+ hint->base.parser_func = (HintParseFunction) LeadingHintParse;
+ hint->relations = NIL;
+
+ return (Hint *) hint;
+}
- if (nrels > 1)
- qsort(ret->oids, nrels, sizeof(Oid), oidsortcmp);
+static void
+LeadingHintDelete(LeadingHint *hint)
+{
+ if (!hint)
+ return;
- return ret;
+ list_free_deep(hint->relations);
+ pfree(hint);
}
-static void free_tidlist(TidList *tidlist)
+static Hint *
+SetHintCreate(const char *hint_str, const char *keyword)
{
- if (tidlist)
- {
- if (tidlist->oids)
- free(tidlist->oids);
- free(tidlist);
- }
+ SetHint *hint;
+
+ hint = palloc(sizeof(SetHint));
+ hint->base.hint_str = hint_str;
+ hint->base.keyword = keyword;
+ hint->base.type = HINT_TYPE_SET;
+ hint->base.state = HINT_STATE_NOTUSED;
+ hint->base.delete_func = (HintDeleteFunction) SetHintDelete;
+ hint->base.dump_func = (HintDumpFunction) SetHintDump;
+ hint->base.cmp_func = (HintCmpFunction) SetHintCmp;
+ hint->base.parser_func = (HintParseFunction) SetHintParse;
+ hint->name = NULL;
+ hint->value = NULL;
+
+ return (Hint *) hint;
}
-int n = 0;
-static void dump_rels(char *label, PlannerInfo *root, Path *path, bool found, bool enabled)
+static void
+SetHintDelete(SetHint *hint)
{
- char *relsstr;
+ if (!hint)
+ return;
+
+ if (hint->name)
+ pfree(hint->name);
+ if (hint->value)
+ pfree(hint->value);
+ pfree(hint);
+}
- if (!print_log) return;
- relsstr = rels_str(root, path);
- ereport(LOG, (errmsg_internal("%04d: %s for relation %s (%s, %s)\n",
- n++, label, relsstr,
- found ? "found" : "not found",
- enabled ? "enabled" : "disabled")));
- free(relsstr);
+static PlanHint *
+PlanHintCreate(void)
+{
+ PlanHint *hint;
+
+ hint = palloc(sizeof(PlanHint));
+ hint->hint_str = NULL;
+ hint->nall_hints = 0;
+ hint->max_all_hints = 0;
+ hint->all_hints = NULL;
+ memset(hint->num_hints, 0, sizeof(hint->num_hints));
+ hint->scan_hints = NULL;
+ hint->init_scan_mask = 0;
+ hint->parent_relid = 0;
+ hint->parent_hint = NULL;
+ hint->join_hints = NULL;
+ hint->init_join_mask = 0;
+ hint->join_hint_level = NULL;
+ hint->leading_hint = NULL;
+ hint->context = superuser() ? PGC_SUSET : PGC_USERSET;
+ hint->set_hints = NULL;
+
+ return hint;
}
-void dump_joinrels(char *label, PlannerInfo *root, Path *inpath, Path *outpath,
- bool found, bool enabled)
+static void
+PlanHintDelete(PlanHint *hint)
{
- char *irelstr, *orelstr;
+ int i;
- if (!print_log) return;
- irelstr = rels_str(root, inpath);
- orelstr = rels_str(root, outpath);
+ if (!hint)
+ return;
- ereport(LOG, (errmsg_internal("%04d: %s for relation ((%s),(%s)) (%s, %s)\n",
- n++, label, irelstr, orelstr,
- found ? "found" : "not found",
- enabled ? "enabled" : "disabled")));
- free(irelstr);
- free(orelstr);
+ if (hint->hint_str)
+ pfree(hint->hint_str);
+
+ for (i = 0; i < hint->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
+ hint->all_hints[i]->delete_func(hint->all_hints[i]);
+ if (hint->all_hints)
+ pfree(hint->all_hints);
}
+/*
+ * dump functions
+ */
-bool my_cost_hook(CostHookType type, PlannerInfo *root, Path *path1, Path *path2)
+static void
+dump_quote_value(StringInfo buf, const char *value)
{
- TidList *tidlist;
- HashEntry *ent;
- bool ret = false;
+ bool need_quote = false;
+ const char *str;
- if (!tweak_enabled)
+ for (str = value; *str != '\0'; str++)
{
- switch (type)
+ if (isspace(*str) || *str == ')' || *str == '"')
{
- case COSTHOOK_seqscan:
- return enable_seqscan;
- case COSTHOOK_indexscan:
- return enable_indexscan;
- case COSTHOOK_bitmapscan:
- return enable_bitmapscan;
- case COSTHOOK_tidscan:
- return enable_tidscan;
- case COSTHOOK_nestloop:
- return enable_nestloop;
- case COSTHOOK_mergejoin:
- return enable_mergejoin;
- case COSTHOOK_hashjoin:
- return enable_hashjoin;
- default:
- ereport(LOG, (errmsg_internal("Unknown cost type")));
- break;
+ need_quote = true;
+ appendStringInfoCharMacro(buf, '"');
+ break;
}
}
- switch (type)
+
+ for (str = value; *str != '\0'; str++)
{
- case COSTHOOK_seqscan:
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_SEQSCAN) :
- enable_seqscan);
- dump_rels("cost_seqscan", root, path1, ent != NULL, ret);
- return ret;
- case COSTHOOK_indexscan:
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_INDEXSCAN) :
- enable_indexscan);
- dump_rels("cost_indexscan", root, path1, ent != NULL, ret);
- return ret;
- case COSTHOOK_bitmapscan:
- if (path1->pathtype != T_BitmapHeapScan)
- {
- ent = NULL;
- ret = enable_bitmapscan;
- }
- else
- {
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_BITMAPSCAN) :
- enable_bitmapscan);
- }
- dump_rels("cost_bitmapscan", root, path1, ent != NULL, ret);
-
- return ret;
- case COSTHOOK_tidscan:
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_TIDSCAN) :
- enable_tidscan);
- dump_rels("cost_tidscan", root, path1, ent != NULL, ret);
- return ret;
- case COSTHOOK_nestloop:
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_NESTLOOP) :
- enable_nestloop);
- dump_joinrels("cost_nestloop", root, path1, path2,
- ent != NULL, ret);
- return ret;
- case COSTHOOK_mergejoin:
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_MERGEJOIN) :
- enable_mergejoin);
- dump_joinrels("cost_mergejoin", root, path1, path2,
- ent != NULL, ret);
- return ret;
- case COSTHOOK_hashjoin:
- tidlist = maketidlist(root, path1, path2);
- ent = search_ent(tidlist);
- free_tidlist(tidlist);
- ret = (ent ? (ent->enforce_mask & ENABLE_HASHJOIN) :
- enable_hashjoin);
- dump_joinrels("cost_hashjoin", root, path1, path2,
- ent != NULL, ret);
- return ret;
- default:
- ereport(LOG, (errmsg_internal("Unknown cost type")));
- break;
+ if (*str == '"')
+ appendStringInfoCharMacro(buf, '"');
+
+ appendStringInfoCharMacro(buf, *str);
}
-
- return true;
+
+ if (need_quote)
+ appendStringInfoCharMacro(buf, '"');
}
-#endif
-static void free_hashent(HashEntry *head)
+static void
+ScanMethodHintDump(ScanMethodHint *hint, StringInfo buf)
{
- HashEntry *next = head;
+ ListCell *l;
- while (next)
+ appendStringInfo(buf, "%s(", hint->base.keyword);
+ dump_quote_value(buf, hint->relname);
+ foreach(l, hint->indexnames)
{
- HashEntry *last = next;
- if (next->tidlist.oids != NULL) free(next->tidlist.oids);
- next = next->next;
- free(last);
+ appendStringInfoCharMacro(buf, ' ');
+ dump_quote_value(buf, (char *) lfirst(l));
}
+ appendStringInfoString(buf, ")\n");
}
-static HashEntry *parse_tidlist(char **str)
+static void
+JoinMethodHintDump(JoinMethodHint *hint, StringInfo buf)
{
- char tidstr[8];
- char *p0;
- Oid tid[20]; /* ^^; */
- int ntids = 0;
- int i, len;
- HashEntry *ret;
+ int i;
- while (isdigit(**str) && ntids < 20)
+ appendStringInfo(buf, "%s(", hint->base.keyword);
+ dump_quote_value(buf, hint->relnames[0]);
+ for (i = 1; i < hint->nrels; i++)
{
- p0 = *str;
- while (isdigit(**str)) (*str)++;
- len = *str - p0;
- if (len >= 8) return NULL;
- strncpy(tidstr, p0, len);
- tidstr[len] = 0;
-
- /* Tis 0 is valid? I don't know :-p */
- if ((tid[ntids++] = atoi(tidstr)) == 0) return NULL;
-
- if (**str == ',') (*str)++;
+ appendStringInfoCharMacro(buf, ' ');
+ dump_quote_value(buf, hint->relnames[i]);
}
+ appendStringInfoString(buf, ")\n");
- if (ntids > 1)
- qsort(tid, ntids, sizeof(Oid), oidsortcmp);
- ret = (HashEntry*)malloc(sizeof(HashEntry));
- ret->next = NULL;
- ret->enforce_mask = 0;
- ret->tidlist.nrels = ntids;
- ret->tidlist.oids = (Oid *)malloc(ntids * sizeof(Oid));
- for (i = 0 ; i < ntids ; i++)
- ret->tidlist.oids[i] = tid[i];
- return ret;
-}
-
-static int parse_phrase(HashEntry **head, char **str)
-{
- char *cmds[] = {"seq", "index", "nest", "merge", "hash", NULL};
- unsigned char masks[] = {ENABLE_SEQSCAN, ENABLE_INDEXSCAN|ENABLE_BITMAPSCAN,
- ENABLE_NESTLOOP, ENABLE_MERGEJOIN, ENABLE_HASHJOIN};
- char req[12];
- int cmd;
- HashEntry *ent = NULL;
- char *p0;
- int len;
-
- p0 = *str;
- while (isalpha(**str)) (*str)++;
- len = *str - p0;
- if (**str != '(' || len >= 12) return 0;
- strncpy(req, p0, len);
- req[len] = 0;
- for (cmd = 0 ; cmds[cmd] && strcmp(cmds[cmd], req) ; cmd++);
- if (cmds[cmd] == NULL) return 0;
- (*str)++;
- if ((ent = parse_tidlist(str)) == NULL) return 0;
- if (*(*str)++ != ')') return 0;
- if (**str != 0 && **str != ';') return 0;
- if (**str == ';') (*str)++;
- ent->enforce_mask = masks[cmd];
- ent->next = NULL;
- *head = ent;
-
- return 1;
}
-
-static HashEntry* parse_top(char* str)
+static void
+LeadingHintDump(LeadingHint *hint, StringInfo buf)
{
- HashEntry *head = NULL;
- HashEntry *ent = NULL;
+ bool is_first;
+ ListCell *l;
- if (!parse_phrase(&head, &str))
+ appendStringInfo(buf, "%s(", HINT_LEADING);
+ is_first = true;
+ foreach(l, hint->relations)
{
- free_hashent(head);
- return NULL;
- }
- ent = head;
+ if (is_first)
+ is_first = false;
+ else
+ appendStringInfoCharMacro(buf, ' ');
- while (*str)
- {
- if (!parse_phrase(&ent->next, &str))
- {
- free_hashent(head);
- return NULL;
- }
- ent = ent->next;
+ dump_quote_value(buf, (char *) lfirst(l));
}
- return head;
+ appendStringInfoString(buf, ")\n");
}
-static bool ent_matches(TidList *key, HashEntry *ent2)
+static void
+SetHintDump(SetHint *hint, StringInfo buf)
{
- int i;
-
- if (key->nrels != ent2->tidlist.nrels)
- return 0;
-
- for (i = 0 ; i < key->nrels ; i++)
- if (key->oids[i] != ent2->tidlist.oids[i])
- return 0;
-
- return 1;
+ appendStringInfo(buf, "%s(", HINT_SET);
+ dump_quote_value(buf, hint->name);
+ appendStringInfoCharMacro(buf, ' ');
+ dump_quote_value(buf, hint->value);
+ appendStringInfo(buf, ")\n");
}
-static unsigned int calc_hash(TidList *tidlist)
+static void
+all_hint_dump(PlanHint *hint, StringInfo buf, const char *title,
+ HintStatus state)
{
- unsigned int hash = 0;
- int i = 0;
-
- for (i = 0 ; i < tidlist->nrels ; i++)
+ int i;
+
+ appendStringInfo(buf, "%s:\n", title);
+ for (i = 0; i < hint->nall_hints; i++)
{
- int j = 0;
- for (j = 0 ; j < sizeof(Oid) ; j++)
- hash = hash * 2 + ((tidlist->oids[i] >> (j * 8)) & 0xff);
- }
+ if (hint->all_hints[i]->state != state)
+ continue;
- return hash % HASH_ENTRIES;
-;
+ hint->all_hints[i]->dump_func(hint->all_hints[i], buf);
+ }
}
-#ifdef NOT_USED
-static HashEntry *search_ent(TidList *tidlist)
+static void
+PlanHintDump(PlanHint *hint)
{
- HashEntry *ent;
- if (tidlist == NULL) return NULL;
+ StringInfoData buf;
- ent = hashent[calc_hash(tidlist)];
- while(ent)
+ if (!hint)
{
- if (ent_matches(tidlist, ent))
- return ent;
- ent = ent->next;
+ elog(LOG, "pg_hint_plan:\nno hint");
+ return;
}
- return NULL;
-}
-#endif
-
-Datum
-pg_add_hint(PG_FUNCTION_ARGS)
-{
- HashEntry *ret = NULL;
- char *str = NULL;
- int i = 0;
-
- if (PG_NARGS() < 1)
- ereport(ERROR, (errmsg_internal("No argument")));
-
- str = text_to_cstring(PG_GETARG_TEXT_PP(0));
+ initStringInfo(&buf);
- ret = parse_top(str);
+ appendStringInfoString(&buf, "pg_hint_plan:\n");
+ all_hint_dump(hint, &buf, "used hint", HINT_STATE_USED);
+ all_hint_dump(hint, &buf, "not used hint", HINT_STATE_NOTUSED);
+ all_hint_dump(hint, &buf, "duplication hint", HINT_STATE_DUPLICATION);
+ all_hint_dump(hint, &buf, "error hint", HINT_STATE_ERROR);
- if (ret == NULL)
- ereport(ERROR, (errmsg_internal("Parse Error")));
-
- while (ret)
- {
- HashEntry *etmp = NULL;
- HashEntry *next = NULL;
- int hash = calc_hash(&ret->tidlist);
- while (hashent[hash] && ent_matches(&ret->tidlist, hashent[hash]))
- {
- etmp = hashent[hash]->next;
- hashent[hash]->next = NULL;
- free_hashent(hashent[hash]);
- hashent[hash] = etmp;
-
- }
- etmp = hashent[hash];
- while (etmp && etmp->next)
- {
- if (ent_matches(&ret->tidlist, etmp->next))
- {
- HashEntry *etmp2 = etmp->next->next;
- etmp->next->next = NULL;
- free_hashent(etmp->next);
- etmp->next = etmp2;
- } else
- etmp = etmp->next;
- }
+ elog(LOG, "%s", buf.data);
- i++;
- next = ret->next;
- ret->next = hashent[hash];
- hashent[hash] = ret;
- ret = next;
- }
- PG_RETURN_INT32(i);
+ pfree(buf.data);
}
-Datum
-pg_clear_hint(PG_FUNCTION_ARGS)
-{
- int i;
- int n = 0;
+/*
+ * compare functions
+ */
- for (i = 0 ; i < HASH_ENTRIES ; i++)
- {
- free_hashent(hashent[i]);
- hashent[i] = NULL;
- n++;
+static int
+RelnameCmp(const void *a, const void *b)
+{
+ const char *relnamea = *((const char **) a);
+ const char *relnameb = *((const char **) b);
- }
- PG_RETURN_INT32(n);
+ return strcmp(relnamea, relnameb);
}
-Datum
-pg_enable_hint(bool arg, bool *isnull)
+static int
+ScanMethodHintCmp(const ScanMethodHint *a, const ScanMethodHint *b)
{
- tweak_enabled = arg;
- PG_RETURN_INT32(0);
+ return RelnameCmp(&a->relname, &b->relname);
}
-Datum
-pg_enable_log(bool arg, bool *isnull)
+static int
+JoinMethodHintCmp(const JoinMethodHint *a, const JoinMethodHint *b)
{
- print_log = arg;
- PG_RETURN_INT32(0);
-}
+ int i;
-static int putsbuf(char **p, char *bottom, char *str)
-{
- while (*p < bottom && *str)
+ if (a->nrels != b->nrels)
+ return a->nrels - b->nrels;
+
+ for (i = 0; i < a->nrels; i++)
{
- *(*p)++ = *str++;
+ int result;
+ if ((result = RelnameCmp(&a->relnames[i], &b->relnames[i])) != 0)
+ return result;
}
- return (*str == 0);
+ return 0;
}
-static void dump_ent(HashEntry *ent, char **p, char *bottom)
+static int
+LeadingHintCmp(const LeadingHint *a, const LeadingHint *b)
{
- static char typesigs[] = "SIBTNMH";
- char sigs[sizeof(typesigs)];
- int i;
-
- if (!putsbuf(p, bottom, "[(")) return;
- for (i = 0 ; i < ent->tidlist.nrels ; i++)
- {
- if (i && !putsbuf(p, bottom, ", ")) return;
- if (*p >= bottom) return;
- *p += snprintf(*p, bottom - *p, "%d", ent->tidlist.oids[i]);
- }
- if (!putsbuf(p, bottom, "), ")) return;
- strcpy(sigs, typesigs);
- for (i = 0 ; i < 7 ; i++) /* Magic number here! */
- {
- if(((1<<i) & ent->enforce_mask) == 0)
- sigs[i] += 'a' - 'A';
- }
- if (!putsbuf(p, bottom, sigs)) return;
- if (!putsbuf(p, bottom, "]")) return;
+ return 0;
}
-Datum
-pg_dump_hint(PG_FUNCTION_ARGS)
+static int
+SetHintCmp(const SetHint *a, const SetHint *b)
{
- char buf[16384]; /* ^^; */
- char *bottom = buf + sizeof(buf);
- char *p = buf;
- int i;
- int first = 1;
-
- memset(buf, 0, sizeof(buf));
- for (i = 0 ; i < HASH_ENTRIES ; i++)
- {
- if (hashent[i])
- {
- HashEntry *ent = hashent[i];
- while (ent)
- {
- if (first)
- first = 0;
- else
- putsbuf(&p, bottom, ", ");
-
- dump_ent(ent, &p, bottom);
- ent = ent->next;
- }
- }
- }
- if (p >= bottom) p--;
- *p = 0;
-
- PG_RETURN_CSTRING(cstring_to_text(buf));
+ return strcmp(a->name, b->name);
}
-/*
- * pg_add_hint()で登録したヒントから、今回のクエリで使用するもののみ抽出し、
- * 使用しやすい構造に変換する。
- */
-static void
-build_join_hints(PlannerInfo *root, int level, List *initial_rels)
+static int
+AllHintCmp(const void *a, const void *b, bool order)
{
+ const Hint *hinta = *((const Hint **) a);
+ const Hint *hintb = *((const Hint **) b);
+ int result = 0;
+
+ if (hinta->type != hintb->type)
+ return hinta->type - hintb->type;
+
+ if ((result = hinta->cmp_func(hinta, hintb)) != 0 || !order)
+ return result;
+
+ /* ヒント句で指定した順を返す */
+ return hinta->hint_str - hintb->hint_str;
}
-/*
- * src/backend/optimizer/path/joinrels.c
- * export make_join_rel() をラップする関数
- *
- * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
- * 呼び出す。
- */
-static RelOptInfo *
-my_make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
+static int
+AllHintCmpIsOrder(const void *a, const void *b)
{
- return make_join_rel(root, rel1, rel2);
+ return AllHintCmp(a, b, true);
}
/*
- * PostgreSQL 本体から流用した関数
+ * parse functions
*/
-/*
- * src/backend/optimizer/path/allpaths.c
- * export standard_join_search() を流用
- *
- * 変更箇所
- * build_join_hints() の呼び出しを追加
- */
-/*
- * standard_join_search
- * Find possible joinpaths for a query by successively finding ways
- * to join component relations into join relations.
- *
- * 'levels_needed' is the number of iterations needed, ie, the number of
- * independent jointree items in the query. This is > 1.
- *
- * 'initial_rels' is a list of RelOptInfo nodes for each independent
- * jointree item. These are the components to be joined together.
- * Note that levels_needed == list_length(initial_rels).
- *
- * Returns the final level of join relations, i.e., the relation that is
- * the result of joining all the original relations together.
- * At least one implementation path must be provided for this relation and
- * all required sub-relations.
- *
- * To support loadable plugins that modify planner behavior by changing the
- * join searching algorithm, we provide a hook variable that lets a plugin
- * replace or supplement this function. Any such hook must return the same
- * final join relation as the standard code would, but it might have a
- * different set of implementation paths attached, and only the sub-joinrels
- * needed for these paths need have been instantiated.
- *
- * Note to plugin authors: the functions invoked during standard_join_search()
- * modify root->join_rel_list and root->join_rel_hash. If you want to do more
- * than one join-order search, you'll probably need to save and restore the
- * original states of those data structures. See geqo_eval() for an example.
- */
-static RelOptInfo *
-my_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
+static const char *
+parse_keyword(const char *str, StringInfo buf)
{
- int lev;
- RelOptInfo *rel;
-
- /*
- * This function cannot be invoked recursively within any one planning
- * problem, so join_rel_level[] can't be in use already.
- */
- Assert(root->join_rel_level == NULL);
+ skip_space(str);
- /*
- * We employ a simple "dynamic programming" algorithm: we first find all
- * ways to build joins of two jointree items, then all ways to build joins
- * of three items (from two-item joins and single items), then four-item
- * joins, and so on until we have considered all ways to join all the
- * items into one rel.
- *
- * root->join_rel_level[j] is a list of all the j-item rels. Initially we
- * set root->join_rel_level[1] to represent all the single-jointree-item
- * relations.
- */
- root->join_rel_level = (List **) palloc0((levels_needed + 1) * sizeof(List *));
+ while (!isspace(*str) && *str != '(' && *str != '\0')
+ appendStringInfoCharMacro(buf, *str++);
- root->join_rel_level[1] = initial_rels;
+ return str;
+}
- build_join_hints(root, levels_needed, initial_rels);
+static const char *
+skip_opened_parenthesis(const char *str)
+{
+ skip_space(str);
- for (lev = 2; lev <= levels_needed; lev++)
+ if (*str != '(')
{
- ListCell *lc;
+ parse_ereport(str, ("Opened parenthesis is necessary."));
+ return NULL;
+ }
- /*
- * Determine all possible pairs of relations to be joined at this
- * level, and build paths for making each one from every available
- * pair of lower-level relations.
- */
- my_join_search_one_level(root, lev);
+ str++;
- /*
- * Do cleanup work on each just-processed rel.
- */
- foreach(lc, root->join_rel_level[lev])
- {
- rel = (RelOptInfo *) lfirst(lc);
+ return str;
+}
- /* Find and save the cheapest paths for this rel */
- set_cheapest(rel);
+static const char *
+skip_closed_parenthesis(const char *str)
+{
+ skip_space(str);
-#ifdef OPTIMIZER_DEBUG
- debug_print_rel(root, rel);
-#endif
- }
+ if (*str != ')')
+ {
+ parse_ereport(str, ("Closed parenthesis is necessary."));
+ return NULL;
}
- /*
- * We should have a single rel at the final level.
- */
- if (root->join_rel_level[levels_needed] == NIL)
- elog(ERROR, "failed to build any %d-way joins", levels_needed);
- Assert(list_length(root->join_rel_level[levels_needed]) == 1);
-
- rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
+ str++;
- root->join_rel_level = NULL;
-
- return rel;
+ return str;
}
/*
- * src/backend/optimizer/path/joinrels.c
- * static join_search_one_level() を流用
- *
- * 変更箇所
- * make_join_rel() の呼び出しをラップする、my_make_join_rel()の呼び出しに変更
- */
-/*
- * join_search_one_level
- * Consider ways to produce join relations containing exactly 'level'
- * jointree items. (This is one step of the dynamic-programming method
- * embodied in standard_join_search.) Join rel nodes for each feasible
- * combination of lower-level rels are created and returned in a list.
- * Implementation paths are created for each such joinrel, too.
+ * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
+ * で確保したバッファに格納してそのポインタを返す。
*
- * level: level of rels we want to make this time
- * root->join_rel_level[j], 1 <= j < level, is a list of rels containing j items
- *
- * The result is returned in root->join_rel_level[level].
+ * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
+ * 返す。
*/
-static void
-my_join_search_one_level(PlannerInfo *root, int level)
+static const char *
+parse_quote_value(const char *str, char **word, char *value_type)
{
- List **joinrels = root->join_rel_level;
- ListCell *r;
- int k;
+ StringInfoData buf;
+ bool in_quote;
- Assert(joinrels[level] == NIL);
+ /* 先頭のスペースは読み飛ばす。 */
+ skip_space(str);
- /* Set join_cur_level so that new joinrels are added to proper list */
- root->join_cur_level = level;
-
- /*
- * First, consider left-sided and right-sided plans, in which rels of
- * exactly level-1 member relations are joined against initial relations.
- * We prefer to join using join clauses, but if we find a rel of level-1
- * members that has no join clauses, we will generate Cartesian-product
- * joins against all initial rels not already contained in it.
- *
- * In the first pass (level == 2), we try to join each initial rel to each
- * initial rel that appears later in joinrels[1]. (The mirror-image joins
- * are handled automatically by make_join_rel.) In later passes, we try
- * to join rels of size level-1 from joinrels[level-1] to each initial rel
- * in joinrels[1].
- */
- foreach(r, joinrels[level - 1])
+ initStringInfo(&buf);
+ if (*str == '"')
{
- RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
- ListCell *other_rels;
-
- if (level == 2)
- other_rels = lnext(r); /* only consider remaining initial
- * rels */
- else
- other_rels = list_head(joinrels[1]); /* consider all initial
- * rels */
-
- if (old_rel->joininfo != NIL || old_rel->has_eclass_joins ||
- has_join_restriction(root, old_rel))
- {
- /*
- * Note that if all available join clauses for this rel require
- * more than one other rel, we will fail to make any joins against
- * it here. In most cases that's OK; it'll be considered by
- * "bushy plan" join code in a higher-level pass where we have
- * those other rels collected into a join rel.
- *
- * See also the last-ditch case below.
- */
- make_rels_by_clause_joins(root,
- old_rel,
- other_rels);
- }
- else
- {
- /*
- * Oops, we have a relation that is not joined to any other
- * relation, either directly or by join-order restrictions.
- * Cartesian product time.
- */
- make_rels_by_clauseless_joins(root,
- old_rel,
- other_rels);
- }
+ str++;
+ in_quote = true;
}
+ else
+ in_quote = false;
- /*
- * Now, consider "bushy plans" in which relations of k initial rels are
- * joined to relations of level-k initial rels, for 2 <= k <= level-2.
- *
- * We only consider bushy-plan joins for pairs of rels where there is a
- * suitable join clause (or join order restriction), in order to avoid
- * unreasonable growth of planning time.
- */
- for (k = 2;; k++)
+ while (true)
{
- int other_level = level - k;
-
- /*
- * Since make_join_rel(x, y) handles both x,y and y,x cases, we only
- * need to go as far as the halfway point.
- */
- if (k > other_level)
- break;
-
- foreach(r, joinrels[k])
+ if (in_quote)
{
- RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
- ListCell *other_rels;
- ListCell *r2;
+ /* 二重引用符が閉じられていない場合はパース中断 */
+ if (*str == '\0')
+ {
+ pfree(buf.data);
+ parse_ereport(str, ("Unterminated quoted %s.", value_type));
+ return NULL;
+ }
/*
- * We can ignore clauseless joins here, *except* when they
- * participate in join-order restrictions --- then we might have
- * to force a bushy join plan.
+ * エスケープ対象のダブルクウォートをスキップする。
+ * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
+ * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
+ * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
+ * 場合は、エイリアスを指定する必要がある。
*/
- if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
- !has_join_restriction(root, old_rel))
- continue;
-
- if (k == other_level)
- other_rels = lnext(r); /* only consider remaining rels */
- else
- other_rels = list_head(joinrels[other_level]);
-
- for_each_cell(r2, other_rels)
+ if (*str == '"')
{
- RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
-
- if (!bms_overlap(old_rel->relids, new_rel->relids))
- {
- /*
- * OK, we can build a rel of the right level from this
- * pair of rels. Do so if there is at least one usable
- * join clause or a relevant join restriction.
- */
- if (have_relevant_joinclause(root, old_rel, new_rel) ||
- have_join_order_restriction(root, old_rel, new_rel))
- {
- (void) my_make_join_rel(root, old_rel, new_rel);
- }
- }
+ str++;
+ if (*str != '"')
+ break;
}
}
+ else if (isspace(*str) || *str == ')' || *str == '"' || *str == '\0')
+ break;
+
+ appendStringInfoCharMacro(&buf, *str++);
}
- /*
- * Last-ditch effort: if we failed to find any usable joins so far, force
- * a set of cartesian-product joins to be generated. This handles the
- * special case where all the available rels have join clauses but we
- * cannot use any of those clauses yet. An example is
- *
- * SELECT * FROM a,b,c WHERE (a.f1 + b.f2 + c.f3) = 0;
- *
- * The join clause will be usable at level 3, but at level 2 we have no
- * choice but to make cartesian joins. We consider only left-sided and
- * right-sided cartesian joins in this case (no bushy).
- */
- if (joinrels[level] == NIL)
+ if (buf.len == 0)
{
- /*
- * This loop is just like the first one, except we always call
- * make_rels_by_clauseless_joins().
- */
- foreach(r, joinrels[level - 1])
- {
- RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
- ListCell *other_rels;
+ char *type;
- if (level == 2)
- other_rels = lnext(r); /* only consider remaining initial
- * rels */
- else
- other_rels = list_head(joinrels[1]); /* consider all initial
- * rels */
+ type = pstrdup(value_type);
+ type[0] = toupper(type[0]);
+ parse_ereport(str, ("%s is necessary.", type));
- make_rels_by_clauseless_joins(root,
- old_rel,
- other_rels);
- }
+ pfree(buf.data);
+ pfree(type);
- /*----------
- * When special joins are involved, there may be no legal way
- * to make an N-way join for some values of N. For example consider
- *
- * SELECT ... FROM t1 WHERE
- * x IN (SELECT ... FROM t2,t3 WHERE ...) AND
- * y IN (SELECT ... FROM t4,t5 WHERE ...)
- *
- * We will flatten this query to a 5-way join problem, but there are
- * no 4-way joins that join_is_legal() will consider legal. We have
- * to accept failure at level 4 and go on to discover a workable
- * bushy plan at level 5.
- *
- * However, if there are no special joins then join_is_legal() should
- * never fail, and so the following sanity check is useful.
- *----------
- */
- if (joinrels[level] == NIL && root->join_info_list == NIL)
- elog(ERROR, "failed to build any %d-way joins", level);
+ return NULL;
}
+
+ *word = buf.data;
+
+ return str;
}
-/*
- * src/backend/optimizer/path/joinrels.c
- * static make_rels_by_clause_joins() を流用
- *
- * 変更箇所
- * make_join_rel() の呼び出しをラップする、my_make_join_rel()の呼び出しに変更
- */
-/*
- * make_rels_by_clause_joins
- * Build joins between the given relation 'old_rel' and other relations
- * that participate in join clauses that 'old_rel' also participates in
- * (or participate in join-order restrictions with it).
- * The join rels are returned in root->join_rel_level[join_cur_level].
- *
- * Note: at levels above 2 we will generate the same joined relation in
- * multiple ways --- for example (a join b) join c is the same RelOptInfo as
- * (b join c) join a, though the second case will add a different set of Paths
- * to it. This is the reason for using the join_rel_level mechanism, which
- * automatically ensures that each new joinrel is only added to the list once.
- *
- * 'old_rel' is the relation entry for the relation to be joined
- * 'other_rels': the first cell in a linked list containing the other
- * rels to be considered for joining
- *
- * Currently, this is only used with initial rels in other_rels, but it
- * will work for joining to joinrels too.
- */
static void
-make_rels_by_clause_joins(PlannerInfo *root,
- RelOptInfo *old_rel,
- ListCell *other_rels)
+parse_hints(PlanHint *plan, Query *parse, const char *str)
{
- ListCell *l;
+ StringInfoData buf;
+ char *head;
- for_each_cell(l, other_rels)
+ initStringInfo(&buf);
+ while (*str != '\0')
{
- RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
+ const HintParser *parser;
+
+ /* in error message, we output the comment including the keyword. */
+ head = (char *) str;
- if (!bms_overlap(old_rel->relids, other_rel->relids) &&
- (have_relevant_joinclause(root, old_rel, other_rel) ||
- have_join_order_restriction(root, old_rel, other_rel)))
+ /* parse only the keyword of the hint. */
+ resetStringInfo(&buf);
+ str = parse_keyword(str, &buf);
+
+ for (parser = parsers; parser->keyword != NULL; parser++)
{
- (void) my_make_join_rel(root, old_rel, other_rel);
- }
- }
-}
+ char *keyword = parser->keyword;
+ Hint *hint;
+
+ if (strcasecmp(buf.data, keyword) != 0)
+ continue;
+
+ hint = parser->create_func(head, keyword);
+
+ /* parser of each hint does parse in a parenthesis. */
+ if ((str = skip_opened_parenthesis(str)) == NULL ||
+ (str = hint->parser_func(hint, plan, parse, str)) == NULL ||
+ (str = skip_closed_parenthesis(str)) == NULL)
+ {
+ hint->delete_func(hint);
+ pfree(buf.data);
+ return;
+ }
+
+ /*
+ * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張する。
+ */
+ if (plan->nall_hints == 0)
+ {
+ plan->max_all_hints = HINT_ARRAY_DEFAULT_INITSIZE;
+ plan->all_hints = palloc(sizeof(Hint *) * plan->max_all_hints);
+ }
+ else if (plan->nall_hints == plan->max_all_hints)
+ {
+ plan->max_all_hints *= 2;
+ plan->all_hints = repalloc(plan->all_hints,
+ sizeof(Hint *) * plan->max_all_hints);
+ }
+
+ plan->all_hints[plan->nall_hints] = hint;
+ plan->nall_hints++;
+
+ skip_space(str);
+
+ break;
+ }
+
+ if (parser->keyword == NULL)
+ {
+ parse_ereport(head, ("Keyword \"%s\" does not exist.", buf.data));
+ pfree(buf.data);
+ return;
+ }
+ }
+
+ pfree(buf.data);
+}
/*
- * src/backend/optimizer/path/joinrels.c
- * static make_rels_by_clauseless_joins() を流用
- *
- * 変更箇所
- * make_join_rel() の呼び出しをラップする、my_make_join_rel()の呼び出しに変更
+ * Do basic parsing of the query head comment.
*/
+static PlanHint *
+parse_head_comment(Query *parse)
+{
+ const char *p;
+ char *head;
+ char *tail;
+ int len;
+ int i;
+ PlanHint *plan;
+
+ /* get client-supplied query string. */
+ if (stmt_name)
+ {
+ PreparedStatement *entry;
+
+ entry = FetchPreparedStatement(stmt_name, true);
+ p = entry->plansource->query_string;
+ }
+ else
+ p = debug_query_string;
+
+ if (p == NULL)
+ return NULL;
+
+ /* extract query head comment. */
+ len = strlen(HINT_START);
+ skip_space(p);
+ if (strncmp(p, HINT_START, len))
+ return NULL;
+
+ head = (char *) p;
+ p += len;
+ skip_space(p);
+
+ /* find hint end keyword. */
+ if ((tail = strstr(p, HINT_END)) == NULL)
+ {
+ parse_ereport(head, ("Unterminated block comment."));
+ return NULL;
+ }
+
+ /* 入れ子にしたブロックコメントはサポートしない */
+ if ((head = strstr(p, BLOCK_COMMENT_START)) != NULL && head < tail)
+ {
+ parse_ereport(head, ("Block comments nest doesn't supported."));
+ return NULL;
+ }
+
+ /* ヒント句部分を切り出す */
+ len = tail - p;
+ head = palloc(len + 1);
+ memcpy(head, p, len);
+ head[len] = '\0';
+ p = head;
+
+ plan = PlanHintCreate();
+ plan->hint_str = head;
+
+ /* parse each hint. */
+ parse_hints(plan, parse, p);
+
+ /* When nothing specified a hint, we free PlanHint and returns NULL. */
+ if (plan->nall_hints == 0)
+ {
+ PlanHintDelete(plan);
+ return NULL;
+ }
+
+ /* パースしたヒントを並び替える */
+ qsort(plan->all_hints, plan->nall_hints, sizeof(Hint *), AllHintCmpIsOrder);
+
+ /* 重複したヒントを検索する */
+ for (i = 0; i < plan->nall_hints; i++)
+ {
+ Hint *hint = plan->all_hints[i];
+
+ plan->num_hints[hint->type]++;
+
+ if (i + 1 >= plan->nall_hints)
+ break;
+
+ if (AllHintCmp(plan->all_hints + i, plan->all_hints + i + 1, false) ==
+ 0)
+ {
+ const char *HintTypeName[] = {"scan method", "join method",
+ "leading", "set"};
+
+ parse_ereport(plan->all_hints[i]->hint_str,
+ ("Conflict %s hint.", HintTypeName[hint->type]));
+ plan->all_hints[i]->state = HINT_STATE_DUPLICATION;
+ }
+ }
+
+ plan->scan_hints = (ScanMethodHint **) plan->all_hints;
+ plan->join_hints = (JoinMethodHint **) plan->all_hints +
+ plan->num_hints[HINT_TYPE_SCAN_METHOD];
+ plan->leading_hint = (LeadingHint *) plan->all_hints[
+ plan->num_hints[HINT_TYPE_SCAN_METHOD] +
+ plan->num_hints[HINT_TYPE_JOIN_METHOD] +
+ plan->num_hints[HINT_TYPE_LEADING] - 1];
+ plan->set_hints = (SetHint **) plan->all_hints +
+ plan->num_hints[HINT_TYPE_SCAN_METHOD] +
+ plan->num_hints[HINT_TYPE_JOIN_METHOD] +
+ plan->num_hints[HINT_TYPE_LEADING];
+
+ return plan;
+}
+
/*
- * make_rels_by_clauseless_joins
- * Given a relation 'old_rel' and a list of other relations
- * 'other_rels', create a join relation between 'old_rel' and each
- * member of 'other_rels' that isn't already included in 'old_rel'.
- * The join rels are returned in root->join_rel_level[join_cur_level].
- *
- * 'old_rel' is the relation entry for the relation to be joined
- * 'other_rels': the first cell of a linked list containing the
- * other rels to be considered for joining
- *
- * Currently, this is only used with initial rels in other_rels, but it would
- * work for joining to joinrels too.
+ * スキャン方式ヒントのカッコ内をパースする
*/
+static const char *
+ScanMethodHintParse(ScanMethodHint *hint, PlanHint *plan, Query *parse,
+ const char *str)
+{
+ const char *keyword = hint->base.keyword;
+
+ /*
+ * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
+ */
+ if ((str = parse_quote_value(str, &hint->relname, "relation name")) == NULL)
+ return NULL;
+
+ skip_space(str);
+
+ /*
+ * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
+ * する。
+ */
+ if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
+ strcmp(keyword, HINT_BITMAPSCAN) == 0)
+ {
+ while (*str != ')' && *str != '\0')
+ {
+ char *indexname;
+
+ str = parse_quote_value(str, &indexname, "index name");
+ if (str == NULL)
+ return NULL;
+
+ hint->indexnames = lappend(hint->indexnames, indexname);
+ skip_space(str);
+ }
+ }
+
+ /*
+ * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
+ */
+ if (strcasecmp(keyword, HINT_SEQSCAN) == 0)
+ hint->enforce_mask = ENABLE_SEQSCAN;
+ else if (strcasecmp(keyword, HINT_INDEXSCAN) == 0)
+ hint->enforce_mask = ENABLE_INDEXSCAN;
+ else if (strcasecmp(keyword, HINT_BITMAPSCAN) == 0)
+ hint->enforce_mask = ENABLE_BITMAPSCAN;
+ else if (strcasecmp(keyword, HINT_TIDSCAN) == 0)
+ hint->enforce_mask = ENABLE_TIDSCAN;
+ else if (strcasecmp(keyword, HINT_NOSEQSCAN) == 0)
+ hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_SEQSCAN;
+ else if (strcasecmp(keyword, HINT_NOINDEXSCAN) == 0)
+ hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_INDEXSCAN;
+ else if (strcasecmp(keyword, HINT_NOBITMAPSCAN) == 0)
+ hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_BITMAPSCAN;
+ else if (strcasecmp(keyword, HINT_NOTIDSCAN) == 0)
+ hint->enforce_mask = ENABLE_ALL_SCAN ^ ENABLE_TIDSCAN;
+ else
+ {
+ parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
+ return NULL;
+ }
+
+ return str;
+}
+
+static const char *
+JoinMethodHintParse(JoinMethodHint *hint, PlanHint *plan, Query *parse,
+ const char *str)
+{
+ char *relname;
+ const char *keyword = hint->base.keyword;
+
+ skip_space(str);
+
+ hint->relnames = palloc(sizeof(char *));
+
+ while ((str = parse_quote_value(str, &relname, "relation name")) != NULL)
+ {
+ hint->nrels++;
+ hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
+ hint->relnames[hint->nrels - 1] = relname;
+
+ skip_space(str);
+ if (*str == ')')
+ break;
+ }
+
+ if (str == NULL)
+ return NULL;
+
+ /* Join 対象のテーブルは最低でも2つ指定する必要がある */
+ if (hint->nrels < 2)
+ {
+ parse_ereport(str, ("Specified relation more than two."));
+ hint->base.state = HINT_STATE_ERROR;
+ }
+
+ /* テーブル名順にソートする */
+ qsort(hint->relnames, hint->nrels, sizeof(char *), RelnameCmp);
+
+ if (strcasecmp(keyword, HINT_NESTLOOP) == 0)
+ hint->enforce_mask = ENABLE_NESTLOOP;
+ else if (strcasecmp(keyword, HINT_MERGEJOIN) == 0)
+ hint->enforce_mask = ENABLE_MERGEJOIN;
+ else if (strcasecmp(keyword, HINT_HASHJOIN) == 0)
+ hint->enforce_mask = ENABLE_HASHJOIN;
+ else if (strcasecmp(keyword, HINT_NONESTLOOP) == 0)
+ hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP;
+ else if (strcasecmp(keyword, HINT_NOMERGEJOIN) == 0)
+ hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN;
+ else if (strcasecmp(keyword, HINT_NOHASHJOIN) == 0)
+ hint->enforce_mask = ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN;
+ else
+ {
+ parse_ereport(str, ("Unrecognized hint keyword \"%s\".", keyword));
+ return NULL;
+ }
+
+ return str;
+}
+
+static const char *
+LeadingHintParse(LeadingHint *hint, PlanHint *plan, Query *parse,
+ const char *str)
+{
+ skip_space(str);
+
+ while (*str != ')')
+ {
+ char *relname;
+
+ if ((str = parse_quote_value(str, &relname, "relation name")) == NULL)
+ return NULL;
+
+ hint->relations = lappend(hint->relations, relname);
+
+ skip_space(str);
+ }
+
+ /* テーブル指定が2つ未満の場合は、Leading ヒントはエラーとする */
+ if (list_length(hint->relations) < 2)
+ {
+ parse_ereport(hint->base.hint_str,
+ ("In %s hint, specified relation name 2 or more.",
+ HINT_LEADING));
+ hint->base.state = HINT_STATE_ERROR;
+ }
+
+ return str;
+}
+
+static const char *
+SetHintParse(SetHint *hint, PlanHint *plan, Query *parse, const char *str)
+{
+ if ((str = parse_quote_value(str, &hint->name, "parameter name")) == NULL ||
+ (str = parse_quote_value(str, &hint->value, "parameter value")) == NULL)
+ return NULL;
+
+ return str;
+}
+
+/*
+ * set GUC parameter functions
+ */
+
+static int
+set_config_option_wrapper(const char *name, const char *value,
+ GucContext context, GucSource source,
+ GucAction action, bool changeVal, int elevel)
+{
+ int result = 0;
+ MemoryContext ccxt = CurrentMemoryContext;
+
+ PG_TRY();
+ {
+ result = set_config_option(name, value, context, source,
+ action, changeVal);
+ }
+ PG_CATCH();
+ {
+ ErrorData *errdata;
+ MemoryContext ecxt;
+
+ ecxt = MemoryContextSwitchTo(ccxt);
+ errdata = CopyErrorData();
+ FlushErrorState();
+ ereport(elevel, (errcode(errdata->sqlerrcode),
+ errmsg("%s", errdata->message),
+ errdata->detail ? errdetail("%s", errdata->detail) : 0,
+ errdata->hint ? errhint("%s", errdata->hint) : 0));
+ FreeErrorData(errdata);
+
+ MemoryContextSwitchTo(ecxt);
+ }
+ PG_END_TRY();
+
+ return result;
+}
+
+static int
+set_config_options(SetHint **options, int noptions, GucContext context)
+{
+ int i;
+ int save_nestlevel;
+
+ save_nestlevel = NewGUCNestLevel();
+
+ for (i = 0; i < noptions; i++)
+ {
+ SetHint *hint = options[i];
+ int result;
+
+ if (!hint_state_enabled(hint))
+ continue;
+
+ result = set_config_option_wrapper(hint->name, hint->value, context,
+ PGC_S_SESSION, GUC_ACTION_SAVE, true,
+ pg_hint_plan_parse_messages);
+ if (result != 0)
+ hint->base.state = HINT_STATE_USED;
+ else
+ hint->base.state = HINT_STATE_ERROR;
+ }
+
+ return save_nestlevel;
+}
+
+#define SET_CONFIG_OPTION(name, type_bits) \
+ set_config_option_wrapper((name), \
+ (mask & (type_bits)) ? "true" : "false", \
+ context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
+
static void
-make_rels_by_clauseless_joins(PlannerInfo *root,
- RelOptInfo *old_rel,
- ListCell *other_rels)
+set_scan_config_options(unsigned char enforce_mask, GucContext context)
{
- ListCell *l;
+ unsigned char mask;
+
+ if (enforce_mask == ENABLE_SEQSCAN || enforce_mask == ENABLE_INDEXSCAN ||
+ enforce_mask == ENABLE_BITMAPSCAN || enforce_mask == ENABLE_TIDSCAN
+ )
+ mask = enforce_mask;
+ else
+ mask = enforce_mask & global->init_scan_mask;
+
+ SET_CONFIG_OPTION("enable_seqscan", ENABLE_SEQSCAN);
+ SET_CONFIG_OPTION("enable_indexscan", ENABLE_INDEXSCAN);
+ SET_CONFIG_OPTION("enable_bitmapscan", ENABLE_BITMAPSCAN);
+ SET_CONFIG_OPTION("enable_tidscan", ENABLE_TIDSCAN);
+}
+
+static void
+set_join_config_options(unsigned char enforce_mask, GucContext context)
+{
+ unsigned char mask;
+
+ if (enforce_mask == ENABLE_NESTLOOP || enforce_mask == ENABLE_MERGEJOIN ||
+ enforce_mask == ENABLE_HASHJOIN)
+ mask = enforce_mask;
+ else
+ mask = enforce_mask & global->init_join_mask;
+
+ SET_CONFIG_OPTION("enable_nestloop", ENABLE_NESTLOOP);
+ SET_CONFIG_OPTION("enable_mergejoin", ENABLE_MERGEJOIN);
+ SET_CONFIG_OPTION("enable_hashjoin", ENABLE_HASHJOIN);
+}
+
+/*
+ * pg_hint_plan hook functions
+ */
+
+static void
+pg_hint_plan_ProcessUtility(Node *parsetree, const char *queryString,
+ ParamListInfo params, bool isTopLevel,
+ DestReceiver *dest, char *completionTag)
+{
+ Node *node;
+
+ if (!pg_hint_plan_enable)
+ {
+ if (prev_ProcessUtility)
+ (*prev_ProcessUtility) (parsetree, queryString, params,
+ isTopLevel, dest, completionTag);
+ else
+ standard_ProcessUtility(parsetree, queryString, params,
+ isTopLevel, dest, completionTag);
+
+ return;
+ }
+
+ node = parsetree;
+ if (IsA(node, ExplainStmt))
+ {
+ /*
+ * EXPLAIN対象のクエリのパースツリーを取得する
+ */
+ ExplainStmt *stmt;
+ Query *query;
+
+ stmt = (ExplainStmt *) node;
+
+ Assert(IsA(stmt->query, Query));
+ query = (Query *) stmt->query;
+
+ if (query->commandType == CMD_UTILITY && query->utilityStmt != NULL)
+ node = query->utilityStmt;
+ }
+
+ /*
+ * EXECUTEコマンドならば、PREPARE時に指定されたクエリ文字列を取得し、ヒント
+ * 句の候補として設定する
+ */
+ if (IsA(node, ExecuteStmt))
+ {
+ ExecuteStmt *stmt;
+
+ stmt = (ExecuteStmt *) node;
+ stmt_name = stmt->name;
+ }
+
+ if (stmt_name)
+ {
+ PG_TRY();
+ {
+ if (prev_ProcessUtility)
+ (*prev_ProcessUtility) (parsetree, queryString, params,
+ isTopLevel, dest, completionTag);
+ else
+ standard_ProcessUtility(parsetree, queryString, params,
+ isTopLevel, dest, completionTag);
+ }
+ PG_CATCH();
+ {
+ stmt_name = NULL;
+ PG_RE_THROW();
+ }
+ PG_END_TRY();
+
+ stmt_name = NULL;
+
+ return;
+ }
+
+ if (prev_ProcessUtility)
+ (*prev_ProcessUtility) (parsetree, queryString, params,
+ isTopLevel, dest, completionTag);
+ else
+ standard_ProcessUtility(parsetree, queryString, params,
+ isTopLevel, dest, completionTag);
+}
+
+static PlannedStmt *
+pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
+{
+ int save_nestlevel;
+ PlannedStmt *result;
+
+ /*
+ * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
+ * こなう。
+ * 他のフック関数で実行されるhint処理をスキップするために、global 変数をNULL
+ * に設定しておく。
+ */
+ if (!pg_hint_plan_enable || (global = parse_head_comment(parse)) == NULL)
+ {
+ global = NULL;
+
+ if (prev_planner)
+ return (*prev_planner) (parse, cursorOptions, boundParams);
+ else
+ return standard_planner(parse, cursorOptions, boundParams);
+ }
+
+ /* Set hint で指定されたGUCパラメータを設定する */
+ save_nestlevel = set_config_options(global->set_hints,
+ global->num_hints[HINT_TYPE_SET],
+ global->context);
+
+ if (enable_seqscan)
+ global->init_scan_mask |= ENABLE_SEQSCAN;
+ if (enable_indexscan)
+ global->init_scan_mask |= ENABLE_INDEXSCAN;
+ if (enable_bitmapscan)
+ global->init_scan_mask |= ENABLE_BITMAPSCAN;
+ if (enable_tidscan)
+ global->init_scan_mask |= ENABLE_TIDSCAN;
+ if (enable_nestloop)
+ global->init_join_mask |= ENABLE_NESTLOOP;
+ if (enable_mergejoin)
+ global->init_join_mask |= ENABLE_MERGEJOIN;
+ if (enable_hashjoin)
+ global->init_join_mask |= ENABLE_HASHJOIN;
+
+ if (prev_planner)
+ result = (*prev_planner) (parse, cursorOptions, boundParams);
+ else
+ result = standard_planner(parse, cursorOptions, boundParams);
+
+ /*
+ * Restore the GUC variables we set above.
+ */
+ AtEOXact_GUC(true, save_nestlevel);
+
+ /*
+ * Print hint if debugging.
+ */
+ if (pg_hint_plan_debug_print)
+ PlanHintDump(global);
+
+ PlanHintDelete(global);
+ global = NULL;
+
+ return result;
+}
+
+/*
+ * aliasnameと一致するSCANヒントを探す
+ */
+static ScanMethodHint *
+find_scan_hint(PlannerInfo *root, RelOptInfo *rel)
+{
+ RangeTblEntry *rte;
+ int i;
+
+ /*
+ * RELOPT_BASEREL でなければ、scan method ヒントが適用しない。
+ * 子テーブルの場合はRELOPT_OTHER_MEMBER_RELとなるが、サポート対象外とする。
+ * また、通常のリレーション以外は、スキャン方式を選択できない。
+ */
+ if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
+ return NULL;
+
+ rte = root->simple_rte_array[rel->relid];
+
+ /* 外部表はスキャン方式が選択できない。 */
+ if (rte->relkind == RELKIND_FOREIGN_TABLE)
+ return NULL;
+
+ /*
+ * スキャン方式のヒントのリストから、検索対象のリレーションと名称が一致する
+ * ヒントを検索する。
+ */
+ for (i = 0; i < global->num_hints[HINT_TYPE_SCAN_METHOD]; i++)
+ {
+ ScanMethodHint *hint = global->scan_hints[i];
+
+ /* すでに無効となっているヒントは検索対象にしない。 */
+ if (!hint_state_enabled(hint))
+ continue;
+
+ if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
+ return hint;
+ }
+
+ return NULL;
+}
+
+static void
+delete_indexes(ScanMethodHint *hint, RelOptInfo *rel)
+{
+ ListCell *cell;
+ ListCell *prev;
+ ListCell *next;
+
+ /*
+ * We delete all the IndexOptInfo list and prevent you from being usable by
+ * a scan.
+ */
+ if (hint->enforce_mask == ENABLE_SEQSCAN ||
+ hint->enforce_mask == ENABLE_TIDSCAN)
+ {
+ list_free_deep(rel->indexlist);
+ rel->indexlist = NIL;
+ hint->base.state = HINT_STATE_USED;
+
+ return;
+ }
- for_each_cell(l, other_rels)
+ /*
+ * When a list of indexes is not specified, we just use all indexes.
+ */
+ if (hint->indexnames == NIL)
+ return;
+
+ /*
+ * Leaving only an specified index, we delete it from a IndexOptInfo list
+ * other than it.
+ */
+ prev = NULL;
+ for (cell = list_head(rel->indexlist); cell; cell = next)
{
- RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
+ IndexOptInfo *info = (IndexOptInfo *) lfirst(cell);
+ char *indexname = get_rel_name(info->indexoid);
+ ListCell *l;
+ bool use_index = false;
+
+ next = lnext(cell);
- if (!bms_overlap(other_rel->relids, old_rel->relids))
+ foreach(l, hint->indexnames)
{
- (void) my_make_join_rel(root, old_rel, other_rel);
+ if (RelnameCmp(&indexname, &lfirst(l)) == 0)
+ {
+ use_index = true;
+ break;
+ }
+ }
+
+ if (!use_index)
+ rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
+ else
+ prev = cell;
+
+ pfree(indexname);
+ }
+}
+
+static void
+pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
+ bool inhparent, RelOptInfo *rel)
+{
+ ScanMethodHint *hint;
+
+ if (prev_get_relation_info)
+ (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
+
+ /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
+ if (!global)
+ return;
+
+ if (inhparent)
+ {
+ /* store does relids of parent table. */
+ global->parent_relid = rel->relid;
+ }
+ else if (global->parent_relid != 0)
+ {
+ /*
+ * We use the same GUC parameter if this table is the child table of a
+ * table called pg_hint_plan_get_relation_info just before that.
+ */
+ ListCell *l;
+
+ /* append_rel_list contains all append rels; ignore others */
+ foreach(l, root->append_rel_list)
+ {
+ AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
+
+ /* This rel is child table. */
+ if (appinfo->parent_relid == global->parent_relid &&
+ appinfo->child_relid == rel->relid)
+ {
+ if (global->parent_hint)
+ delete_indexes(global->parent_hint, rel);
+
+ return;
+ }
+ }
+
+ /* This rel is not inherit table. */
+ global->parent_relid = 0;
+ global->parent_hint = NULL;
+ }
+
+ /* scan hint が指定されない場合は、GUCパラメータをリセットする。 */
+ if ((hint = find_scan_hint(root, rel)) == NULL)
+ {
+ set_scan_config_options(global->init_scan_mask, global->context);
+ return;
+ }
+ set_scan_config_options(hint->enforce_mask, global->context);
+ hint->base.state = HINT_STATE_USED;
+ if (inhparent)
+ global->parent_hint = hint;
+
+ delete_indexes(hint, rel);
+}
+
+/*
+ * aliasnameがクエリ中に指定した別名と一致する場合は、そのインデックスを返し、一致
+ * する別名がなければ0を返す。
+ * aliasnameがクエリ中に複数回指定された場合は、-1を返す。
+ */
+static int
+find_relid_aliasname(PlannerInfo *root, char *aliasname, List *initial_rels,
+ const char *str)
+{
+ int i;
+ Index found = 0;
+
+ for (i = 1; i < root->simple_rel_array_size; i++)
+ {
+ ListCell *l;
+
+ if (root->simple_rel_array[i] == NULL)
+ continue;
+
+ Assert(i == root->simple_rel_array[i]->relid);
+
+ if (RelnameCmp(&aliasname, &root->simple_rte_array[i]->eref->aliasname)
+ != 0)
+ continue;
+
+ foreach(l, initial_rels)
+ {
+ RelOptInfo *rel = (RelOptInfo *) lfirst(l);
+
+ if (rel->reloptkind == RELOPT_BASEREL)
+ {
+ if (rel->relid != i)
+ continue;
+ }
+ else
+ {
+ Assert(rel->reloptkind == RELOPT_JOINREL);
+
+ if (!bms_is_member(i, rel->relids))
+ continue;
+ }
+
+ if (found != 0)
+ {
+ parse_ereport(str,
+ ("Relation name \"%s\" is ambiguous.",
+ aliasname));
+ return -1;
+ }
+
+ found = i;
+ break;
}
+
}
+
+ return found;
}
/*
- * src/backend/optimizer/path/joinrels.c
- * static has_join_restriction() を流用
- *
- * 変更箇所
- * なし
+ * relidビットマスクと一致するヒントを探す
*/
+static JoinMethodHint *
+find_join_hint(Relids joinrelids)
+{
+ List *join_hint;
+ ListCell *l;
+
+ join_hint = global->join_hint_level[bms_num_members(joinrelids)];
+
+ foreach(l, join_hint)
+ {
+ JoinMethodHint *hint = (JoinMethodHint *) lfirst(l);
+
+ if (bms_equal(joinrelids, hint->joinrelids))
+ return hint;
+ }
+
+ return NULL;
+}
+
/*
- * has_join_restriction
- * Detect whether the specified relation has join-order restrictions
- * due to being inside an outer join or an IN (sub-SELECT).
+ * 結合方式のヒントを使用しやすい構造に変換する。
+ */
+static void
+transform_join_hints(PlanHint *plan, PlannerInfo *root, int nbaserel,
+ List *initial_rels, JoinMethodHint **join_method_hints)
+{
+ int i;
+ int relid;
+ LeadingHint *lhint;
+ Relids joinrelids;
+ int njoinrels;
+ ListCell *l;
+
+ for (i = 0; i < plan->num_hints[HINT_TYPE_JOIN_METHOD]; i++)
+ {
+ JoinMethodHint *hint = plan->join_hints[i];
+ int j;
+
+ if (!hint_state_enabled(hint) || hint->nrels > nbaserel)
+ continue;
+
+ bms_free(hint->joinrelids);
+ hint->joinrelids = NULL;
+ relid = 0;
+ for (j = 0; j < hint->nrels; j++)
+ {
+ char *relname = hint->relnames[j];
+
+ relid = find_relid_aliasname(root, relname, initial_rels,
+ hint->base.hint_str);
+
+ if (relid == -1)
+ hint->base.state = HINT_STATE_ERROR;
+
+ if (relid <= 0)
+ break;
+
+ if (bms_is_member(relid, hint->joinrelids))
+ {
+ parse_ereport(hint->base.hint_str,
+ ("Relation name \"%s\" is duplicate.", relname));
+ hint->base.state = HINT_STATE_ERROR;
+ break;
+ }
+
+ hint->joinrelids = bms_add_member(hint->joinrelids, relid);
+ }
+
+ if (relid <= 0 || hint->base.state == HINT_STATE_ERROR)
+ continue;
+
+ plan->join_hint_level[hint->nrels] =
+ lappend(plan->join_hint_level[hint->nrels], hint);
+ }
+
+ /*
+ * 有効なLeading ヒントが指定されている場合は、結合順にあわせてjoin method hint
+ * のフォーマットに変換する。
+ */
+ if (plan->num_hints[HINT_TYPE_LEADING] == 0)
+ return;
+
+ lhint = plan->leading_hint;
+ if (!hint_state_enabled(lhint))
+ return;
+
+ /* Leading hint は、全ての join 方式が有効な hint として登録する */
+ joinrelids = NULL;
+ njoinrels = 0;
+ foreach(l, lhint->relations)
+ {
+ char *relname = (char *)lfirst(l);
+ JoinMethodHint *hint;
+
+ relid =
+ find_relid_aliasname(root, relname, initial_rels, plan->hint_str);
+
+ if (relid == -1)
+ {
+ bms_free(joinrelids);
+ return;
+ }
+
+ if (relid == 0)
+ continue;
+
+ if (bms_is_member(relid, joinrelids))
+ {
+ parse_ereport(lhint->base.hint_str,
+ ("Relation name \"%s\" is duplicate.", relname));
+ lhint->base.state = HINT_STATE_ERROR;
+ bms_free(joinrelids);
+ return;
+ }
+
+ joinrelids = bms_add_member(joinrelids, relid);
+ njoinrels++;
+
+ if (njoinrels < 2)
+ continue;
+
+ hint = find_join_hint(joinrelids);
+ if (hint == NULL)
+ {
+ /*
+ * Here relnames is not set, since Relids bitmap is sufficient to
+ * control paths of this query afterwards.
+ */
+ hint = (JoinMethodHint *) JoinMethodHintCreate(lhint->base.hint_str,
+ HINT_LEADING);
+ hint->base.state = HINT_STATE_USED;
+ hint->nrels = njoinrels;
+ hint->enforce_mask = ENABLE_ALL_JOIN;
+ hint->joinrelids = bms_copy(joinrelids);
+ }
+
+ join_method_hints[njoinrels] = hint;
+
+ if (njoinrels >= nbaserel)
+ break;
+ }
+
+ bms_free(joinrelids);
+
+ if (njoinrels < 2)
+ return;
+
+ for (i = 2; i <= njoinrels; i++)
+ {
+ /* Leading で指定した組み合わせ以外の join hint を削除する */
+ list_free(plan->join_hint_level[i]);
+
+ plan->join_hint_level[i] = lappend(NIL, join_method_hints[i]);
+ }
+
+ if (hint_state_enabled(lhint))
+ set_join_config_options(DISABLE_ALL_JOIN, global->context);
+
+ lhint->base.state = HINT_STATE_USED;
+
+}
+
+/*
+ * set_plain_rel_pathlist
+ * Build access paths for a plain relation (no subquery, no inheritance)
*
- * Essentially, this tests whether have_join_order_restriction() could
- * succeed with this rel and some other one. It's OK if we sometimes
- * say "true" incorrectly. (Therefore, we don't bother with the relatively
- * expensive has_legal_joinclause test.)
+ * This function was copied and edited from set_plain_rel_pathlist() in
+ * src/backend/optimizer/path/allpaths.c
*/
-static bool
-has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
+static void
+set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte)
+{
+ /* Consider sequential scan */
+ add_path(rel, create_seqscan_path(root, rel));
+
+ /* Consider index scans */
+ create_index_paths(root, rel);
+
+ /* Consider TID scans */
+ create_tidscan_paths(root, rel);
+
+ /* Now find the cheapest of the paths for this rel */
+ set_cheapest(rel);
+}
+
+static void
+rebuild_scan_path(PlanHint *plan, PlannerInfo *root, int level,
+ List *initial_rels)
{
ListCell *l;
- foreach(l, root->join_info_list)
+ foreach(l, initial_rels)
{
- SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
+ RelOptInfo *rel = (RelOptInfo *) lfirst(l);
+ RangeTblEntry *rte;
+ ScanMethodHint *hint;
- /* ignore full joins --- other mechanisms preserve their ordering */
- if (sjinfo->jointype == JOIN_FULL)
+ /*
+ * スキャン方式が選択できるリレーションのみ、スキャンパスを再生成
+ * する。
+ */
+ if (rel->reloptkind != RELOPT_BASEREL || rel->rtekind != RTE_RELATION)
continue;
- /* ignore if SJ is already contained in rel */
- if (bms_is_subset(sjinfo->min_lefthand, rel->relids) &&
- bms_is_subset(sjinfo->min_righthand, rel->relids))
+ rte = root->simple_rte_array[rel->relid];
+
+ /* 外部表はスキャン方式が選択できない。 */
+ if (rte->relkind == RELKIND_FOREIGN_TABLE)
continue;
- /* restricted if it overlaps LHS or RHS, but doesn't contain SJ */
- if (bms_overlap(sjinfo->min_lefthand, rel->relids) ||
- bms_overlap(sjinfo->min_righthand, rel->relids))
- return true;
+ /*
+ * scan method hint が指定されていなければ、初期値のGUCパラメータでscan
+ * path を再生成する。
+ */
+ if ((hint = find_scan_hint(root, rel)) == NULL)
+ set_scan_config_options(plan->init_scan_mask, plan->context);
+ else
+ {
+ set_scan_config_options(hint->enforce_mask, plan->context);
+ hint->base.state = HINT_STATE_USED;
+ }
+
+ list_free_deep(rel->pathlist);
+ rel->pathlist = NIL;
+ if (rte->inh)
+ {
+ /* It's an "append relation", process accordingly */
+ set_append_rel_pathlist(root, rel, rel->relid, rte);
+ }
+ else
+ {
+ set_plain_rel_pathlist(root, rel, rte);
+ }
}
- return false;
+ /*
+ * Restore the GUC variables we set above.
+ */
+ set_scan_config_options(plan->init_scan_mask, plan->context);
}
+
+/*
+ * make_join_rel() をラップする関数
+ *
+ * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
+ * 呼び出す。
+ */
+static RelOptInfo *
+make_join_rel_wrapper(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
+{
+ Relids joinrelids;
+ JoinMethodHint *hint;
+ RelOptInfo *rel;
+ int save_nestlevel;
+
+ joinrelids = bms_union(rel1->relids, rel2->relids);
+ hint = find_join_hint(joinrelids);
+ bms_free(joinrelids);
+
+ if (!hint)
+ return pg_hint_plan_make_join_rel(root, rel1, rel2);
+
+ save_nestlevel = NewGUCNestLevel();
+
+ set_join_config_options(hint->enforce_mask, global->context);
+
+ rel = pg_hint_plan_make_join_rel(root, rel1, rel2);
+ hint->base.state = HINT_STATE_USED;
+
+ /*
+ * Restore the GUC variables we set above.
+ */
+ AtEOXact_GUC(true, save_nestlevel);
+
+ return rel;
+}
+
+static int
+get_num_baserels(List *initial_rels)
+{
+ int nbaserel = 0;
+ ListCell *l;
+
+ foreach(l, initial_rels)
+ {
+ RelOptInfo *rel = (RelOptInfo *) lfirst(l);
+
+ if (rel->reloptkind == RELOPT_BASEREL)
+ nbaserel++;
+ else if (rel->reloptkind ==RELOPT_JOINREL)
+ nbaserel+= bms_num_members(rel->relids);
+ else
+ {
+ /* other values not expected here */
+ elog(ERROR, "unrecognized reloptkind type: %d", rel->reloptkind);
+ }
+ }
+
+ return nbaserel;
+}
+
+static RelOptInfo *
+pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
+ List *initial_rels)
+{
+ JoinMethodHint **join_method_hints;
+ int nbaserel;
+ RelOptInfo *rel;
+ int i;
+
+ /*
+ * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
+ * の処理を行う。
+ */
+ if (!global)
+ {
+ if (prev_join_search)
+ return (*prev_join_search) (root, levels_needed, initial_rels);
+ else if (enable_geqo && levels_needed >= geqo_threshold)
+ return geqo(root, levels_needed, initial_rels);
+ else
+ return standard_join_search(root, levels_needed, initial_rels);
+ }
+
+ /* We apply scan method hint rebuild scan path. */
+ rebuild_scan_path(global, root, levels_needed, initial_rels);
+
+ /*
+ * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
+ * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
+ * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
+ */
+ if (enable_geqo && levels_needed >= geqo_threshold)
+ return geqo(root, levels_needed, initial_rels);
+
+ nbaserel = get_num_baserels(initial_rels);
+ global->join_hint_level = palloc0(sizeof(List *) * (nbaserel + 1));
+ join_method_hints = palloc0(sizeof(JoinMethodHint *) * (nbaserel + 1));
+
+ transform_join_hints(global, root, nbaserel, initial_rels,
+ join_method_hints);
+
+ rel = pg_hint_plan_standard_join_search(root, levels_needed, initial_rels);
+
+ for (i = 2; i <= nbaserel; i++)
+ {
+ list_free(global->join_hint_level[i]);
+
+ /* free Leading hint only */
+ if (join_method_hints[i] != NULL &&
+ join_method_hints[i]->enforce_mask == ENABLE_ALL_JOIN)
+ JoinMethodHintDelete(join_method_hints[i]);
+ }
+ pfree(global->join_hint_level);
+ pfree(join_method_hints);
+
+ if (global->num_hints[HINT_TYPE_LEADING] > 0 &&
+ hint_state_enabled(global->leading_hint))
+ set_join_config_options(global->init_join_mask, global->context);
+
+ return rel;
+}
+
+/*
+ * set_rel_pathlist
+ * Build access paths for a base relation
+ *
+ * This function was copied and edited from set_rel_pathlist() in
+ * src/backend/optimizer/path/allpaths.c
+ */
+static void
+set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
+ Index rti, RangeTblEntry *rte)
+{
+ if (rte->inh)
+ {
+ /* It's an "append relation", process accordingly */
+ set_append_rel_pathlist(root, rel, rti, rte);
+ }
+ else
+ {
+ if (rel->rtekind == RTE_RELATION)
+ {
+ if (rte->relkind == RELKIND_RELATION)
+ {
+ /* Plain relation */
+ set_plain_rel_pathlist(root, rel, rte);
+ }
+ else
+ elog(ERROR, "unexpected relkind: %c", rte->relkind);
+ }
+ else
+ elog(ERROR, "unexpected rtekind: %d", (int) rel->rtekind);
+ }
+}
+
+#define standard_join_search pg_hint_plan_standard_join_search
+#define join_search_one_level pg_hint_plan_join_search_one_level
+#define make_join_rel make_join_rel_wrapper
+#include "core.c"
+
+#undef make_join_rel
+#define make_join_rel pg_hint_plan_make_join_rel
+#define add_paths_to_joinrel(root, joinrel, outerrel, innerrel, jointype, sjinfo, restrictlist) \
+do { \
+ ScanMethodHint *hint = NULL; \
+ if ((hint = find_scan_hint((root), (innerrel))) != NULL) \
+ { \
+ set_scan_config_options(hint->enforce_mask, global->context); \
+ hint->base.state = HINT_STATE_USED; \
+ } \
+ add_paths_to_joinrel((root), (joinrel), (outerrel), (innerrel), (jointype), (sjinfo), (restrictlist)); \
+ if (hint != NULL) \
+ set_scan_config_options(global->init_scan_mask, global->context); \
+} while(0)
+#include "make_join_rel.c"