OSDN Git Service

ParseScanMethodをPostgreSQL9.1に対応した。
[pghintplan/pg_hint_plan.git] / pg_hint_plan.c
index 0a9a1d0..b398018 100644 (file)
@@ -9,27 +9,21 @@
  *-------------------------------------------------------------------------
  */
 #include "postgres.h"
-#include "fmgr.h"
-#include "lib/stringinfo.h"
 #include "miscadmin.h"
-#include "nodes/print.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 "tcop/tcopprot.h"
-#include "utils/builtins.h"
-#include "utils/elog.h"
-#include "utils/guc.h"
-#include "utils/memutils.h"
+#include "utils/lsyscache.h"
 
 #ifdef PG_MODULE_MAGIC
 PG_MODULE_MAGIC;
 #endif
 
-#if PG_VERSION_NUM != 90200
+#if PG_VERSION_NUM < 90100
 #error unsupported PostgreSQL version
 #endif
 
@@ -37,26 +31,27 @@ PG_MODULE_MAGIC;
 #define HINT_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_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"
 #if PG_VERSION_NUM >= 90200
-#define        HINT_INDEXONLYSCAN      "IndexonlyScan";
+#define HINT_INDEXONLYSCAN             "IndexonlyScan"
+#define HINT_NOINDEXONLYSCAN   "NoIndexonlyScan"
 #endif
+#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
 
@@ -110,29 +105,39 @@ typedef struct SetHint
        char   *value;
 } SetHint;
 
+/*
+ * Describes a context of hint processing.
+ */
 typedef struct PlanHint
 {
-       char       *hint_str;
+       char       *hint_str;           /* original hint string */
 
-       int                     nscan_hints;
-       int                     max_scan_hints;
-       ScanHint  **scan_hints;
+       /* for scan method hints */
+       int                     nscan_hints;    /* # of valid scan hints */
+       int                     max_scan_hints; /* # of slots for scan hints */
+       ScanHint  **scan_hints;         /* parsed scan hints */
 
-       int                     njoin_hints;
-       int                     max_join_hints;
-       JoinHint  **join_hints;
+       /* for join method hints */
+       int                     njoin_hints;    /* # of valid join hints */
+       int                     max_join_hints; /* # of slots for join hints */
+       JoinHint  **join_hints;         /* parsed join hints */
 
-       int                     nlevel;
+       int                     nlevel;                 /* # of relations to be joined */
        List      **join_hint_level;
 
-       List       *leading;
+       /* for Leading hints */
+       List       *leading;            /* relation names specified in Leading hint */
 
-       GucContext      context;
-       List       *set_hints;
+       /* for Set hints */
+       GucContext      context;                /* which GUC parameters can we set? */
+       List       *set_hints;          /* parsed Set hints */
 } PlanHint;
 
 typedef const char *(*HintParserFunction) (PlanHint *plan, Query *parse, char *keyword, const char *str);
 
+/*
+ * Describes a hint parser module which is bound with particular hint keyword.
+ */
 typedef struct HintParser
 {
        char   *keyword;
@@ -144,61 +149,27 @@ typedef struct HintParser
 void           _PG_init(void);
 void           _PG_fini(void);
 
-
-#define HASH_ENTRIES 201
-typedef struct tidlist
-{
-       int nrels;
-       Oid *oids;
-} TidList;
-typedef struct hash_entry
-{
-       TidList tidlist;
-       unsigned char enforce_mask;
-       struct hash_entry *next;
-} HashEntry;
-static HashEntry *hashent[HASH_ENTRIES];
-static bool print_log = false;
-/* Join Method Hints */
-typedef struct RelIdInfo
-{
-       Index           relid;
-       Oid                     oid;
-       Alias      *eref;
-} RelIdInfo;
-
-typedef struct GucVariables
-{
-       bool    enable_seqscan;
-       bool    enable_indexscan;
-       bool    enable_bitmapscan;
-       bool    enable_tidscan;
-       bool    enable_sort;
-       bool    enable_hashagg;
-       bool    enable_nestloop;
-       bool    enable_material;
-       bool    enable_mergejoin;
-       bool    enable_hashjoin;
-} GucVariables;
-
-
-static PlannedStmt *my_planner(Query *parse, int cursorOptions,
+static PlannedStmt *pg_hint_plan_planner(Query *parse, int cursorOptions,
                                                           ParamListInfo boundParams);
-static void my_get_relation_info(PlannerInfo *root, Oid relationObjectId,
+static void pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
                                                                 bool inhparent, RelOptInfo *rel);
-static RelOptInfo *my_join_search(PlannerInfo *root, int levels_needed,
+static RelOptInfo *pg_hint_plan_join_search(PlannerInfo *root, int levels_needed,
                                                                  List *initial_rels);
 
+static const char *ParseScanMethod(PlanHint *plan, Query *parse, char *keyword, const char *str);
+static const char *ParseJoinMethod(PlanHint *plan, Query *parse, char *keyword, const char *str);
+static const char *ParseLeading(PlanHint *plan, Query *parse, char *keyword, const char *str);
+static const char *ParseSet(PlanHint *plan, Query *parse, char *keyword, const char *str);
+#ifdef NOT_USED
+static const char *Ordered(PlanHint *plan, Query *parse, char *keyword, const char *str);
+#endif
 
-static void backup_guc(GucVariables *backup);
-static void restore_guc(GucVariables *backup);
-static void set_guc(unsigned char enforce_mask);
-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 void my_join_search_one_level(PlannerInfo *root, int level);
+RelOptInfo *standard_join_search_org(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_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte);
 
 
 /* GUC variables */
@@ -234,15 +205,18 @@ static join_search_hook_type prev_join_search = NULL;
 static PlanHint *global = NULL;
 
 static const HintParser parsers[] = {
-/*
        {HINT_SEQSCAN, true, ParseScanMethod},
-       {HINT_INDEXSCAN, true, ParseIndexScanMethod},
-       {HINT_BITMAPSCAN, true, ParseIndexScanMethod},
+       {HINT_INDEXSCAN, true, ParseScanMethod},
+       {HINT_BITMAPSCAN, true, ParseScanMethod},
        {HINT_TIDSCAN, true, ParseScanMethod},
        {HINT_NOSEQSCAN, true, ParseScanMethod},
        {HINT_NOINDEXSCAN, true, ParseScanMethod},
        {HINT_NOBITMAPSCAN, true, ParseScanMethod},
        {HINT_NOTIDSCAN, true, ParseScanMethod},
+#if PG_VERSION_NUM >= 90200
+       {HINT_INDEXONLYSCAN, true, ParseScanMethod},
+       {HINT_NOINDEXONLYSCAN, true, ParseScanMethod},
+#endif
        {HINT_NESTLOOP, true, ParseJoinMethod},
        {HINT_MERGEJOIN, true, ParseJoinMethod},
        {HINT_HASHJOIN, true, ParseJoinMethod},
@@ -251,7 +225,6 @@ static const HintParser parsers[] = {
        {HINT_NOHASHJOIN, true, ParseJoinMethod},
        {HINT_LEADING, true, ParseLeading},
        {HINT_SET, true, ParseSet},
-*/
        {NULL, false, NULL},
 };
 
@@ -298,15 +271,16 @@ _PG_init(void)
 
        /* Install hooks. */
        prev_planner_hook = planner_hook;
-       planner_hook = my_planner;
+       planner_hook = pg_hint_plan_planner;
        prev_get_relation_info = get_relation_info_hook;
-       get_relation_info_hook = my_get_relation_info;
+       get_relation_info_hook = pg_hint_plan_get_relation_info;
        prev_join_search = join_search_hook;
-       join_search_hook = my_join_search;
+       join_search_hook = pg_hint_plan_join_search;
 }
 
 /*
  * Module unload callback
+ * XXX never called
  */
 void
 _PG_fini(void)
@@ -416,9 +390,9 @@ PlanHintCreate(void)
        hint->join_hints = NULL;
        hint->nlevel = 0;
        hint->join_hint_level = NULL;
+       hint->leading = NIL;
        hint->context = superuser() ? PGC_SUSET : PGC_USERSET;
        hint->set_hints = NIL;
-       hint->leading = NIL;
 
        return hint;
 }
@@ -450,12 +424,12 @@ PlanHintDelete(PlanHint *hint)
        if (hint->join_hint_level)
                pfree(hint->join_hint_level);
 
+       list_free_deep(hint->leading);
+
        foreach(l, hint->set_hints)
                SetHintDelete((SetHint *) lfirst(l));
        list_free(hint->set_hints);
 
-       list_free_deep(hint->leading);
-
        pfree(hint);
 }
 
@@ -464,14 +438,14 @@ PlanHintIsempty(PlanHint *hint)
 {
        if (hint->nscan_hints == 0 &&
                hint->njoin_hints == 0 &&
-               hint->set_hints == NIL &&
-               hint->leading == NIL)
+               hint->leading == NIL &&
+               hint->set_hints == NIL)
                return true;
 
        return false;
 }
 
-// TODO オブジェクト名のクォート処理を追加
+/* TODO オブジェクト名のクォート処理を追加 */
 static void
 PlanHintDump(PlanHint *hint)
 {
@@ -606,7 +580,7 @@ ScanHintCmp(const void *a, const void *b, bool order)
        const ScanHint     *hintb = *((const ScanHint **) b);
        int                                     result;
 
-       if ((result = strcmp(hinta->relname, hintb->relname)) != 0)
+       if ((result = RelnameCmp(&hinta->relname, &hintb->relname)) != 0)
                return result;
 
        /* ヒント句で指定した順を返す */
@@ -634,7 +608,7 @@ JoinHintCmp(const void *a, const void *b, bool order)
                for (i = 0; i < hinta->nrels; i++)
                {
                        int     result;
-                       if ((result = strcmp(hinta->relnames[i], hintb->relnames[i])) != 0)
+                       if ((result = RelnameCmp(&hinta->relnames[i], &hintb->relnames[i])) != 0)
                                return result;
                }
 
@@ -654,6 +628,49 @@ JoinHintCmpIsOrder(const void *a, const void *b)
        return JoinHintCmp(a, b, true);
 }
 
+#if PG_VERSION_NUM < 90200
+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;
+
+               if (elevel >= ERROR)
+                       PG_RE_THROW();
+
+               ecxt = MemoryContextSwitchTo(ccxt);
+               errdata = CopyErrorData();
+               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;
+}
+
+#define set_config_option(name, value, context, source, \
+                                                 action, changeVal, elevel) \
+       set_config_option_wrapper(name, value, context, source, \
+                                                         action, changeVal, elevel)
+#endif
+
 static int
 set_config_options(List *options, GucContext context)
 {
@@ -748,12 +765,20 @@ skip_closed_parenthesis(const char *str)
        return str;
 }
 
+/*
+ * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
+ * で確保したバッファに格納してそのポインタを返す。
+ *
+ * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
+ * 返す。
+ */
 static const char *
 parse_quote_value(const char *str, char **word, char *value_type)
 {
        StringInfoData  buf;
        bool                    in_quote;
 
+       /* 先頭のスペースは読み飛ばす。 */
        skip_space(str);
 
        initStringInfo(&buf);
@@ -763,25 +788,13 @@ parse_quote_value(const char *str, char **word, char *value_type)
                in_quote = true;
        }
        else
-       {
-               /*
-                * 1文字目以降の制限の適用
-                */
-               if (!isalpha(*str) && *str != '_')
-               {
-                       pfree(buf.data);
-                       parse_ereport(str, ("Need for %s to be quoted.", value_type));
-                       return NULL;
-               }
-
                in_quote = false;
-               appendStringInfoCharMacro(&buf, *str++);
-       }
 
        while (true)
        {
                if (in_quote)
                {
+                       /* 二重引用符が閉じられていない場合はパース中断 */
                        if (*str == '\0')
                        {
                                pfree(buf.data);
@@ -790,8 +803,11 @@ parse_quote_value(const char *str, char **word, char *value_type)
                        }
 
                        /*
-                        * エスケープ対象をスキップする。
-                        * TODO エスケープ対象の仕様にあわせた処理を行う。
+                        * エスケープ対象のダブルクウォートをスキップする。
+                        * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
+                        * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
+                        * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
+                        * 場合は、エイリアスを指定する必要がある。
                         */
                        if(*str == '"')
                        {
@@ -801,13 +817,8 @@ parse_quote_value(const char *str, char **word, char *value_type)
                        }
                }
                else
-               {
-                       /*
-                        * 2文字目以降の制限の適用
-                        */
-                       if (!isalnum(*str) && *str != '_' && *str != '$')
+                       if (isspace(*str) || *str == ')' || *str == '\0')
                                break;
-               }
 
                appendStringInfoCharMacro(&buf, *str++);
        }
@@ -927,7 +938,6 @@ parse_head_comment(Query *parse)
        if (p == NULL)
                return NULL;
 
-
        /* extract query head comment. */
        len = strlen(HINT_START);
        skip_space(p);
@@ -938,8 +948,10 @@ parse_head_comment(Query *parse)
        skip_space(p);
 
        if ((tail = strstr(p, HINT_END)) == NULL)
-               elog(ERROR, "unterminated /* comment at or near \"%s\"",
-                        debug_query_string);
+       {
+               parse_ereport(debug_query_string, ("unterminated /* comment"));
+               return NULL;
+       }
 
        /* 入れ子にしたブロックコメントはサポートしない */
        if ((head = strstr(p, HINT_START)) != NULL && head < tail)
@@ -996,8 +1008,273 @@ parse_head_comment(Query *parse)
        return plan;
 }
 
+/*
+ * スキャン方式ヒントのカッコ内をパースする
+ */
+static const char *
+ParseScanMethod(PlanHint *plan, Query *parse, char *keyword, const char *str)
+{
+       ScanHint   *hint;
+
+       hint = ScanHintCreate();
+       hint->opt_str = str;
+
+       /*
+        * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
+        */
+       if ((str = parse_quote_value(str, &hint->relname, "ralation name")) == NULL)
+       {
+               ScanHintDelete(hint);
+               return NULL;
+       }
+
+       /*
+        * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
+        * する。
+        */
+       if (strcmp(keyword, HINT_INDEXSCAN) == 0 ||
+#if PG_VERSION_NUM >= 90200
+               strcmp(keyword, HINT_INDEXONLYSCAN) == 0 ||
+#endif
+               strcmp(keyword, HINT_BITMAPSCAN) == 0)
+       {
+               skip_space(str);
+               while (*str != ')' && *str != '\0')
+               {
+                       char       *indexname;
+
+                       str = parse_quote_value(str, &indexname, "index name");
+                       if (str == NULL)
+                       {
+                               ScanHintDelete(hint);
+                               return NULL;
+                       }
+
+                       hint->indexnames = lappend(hint->indexnames, indexname);
+                       skip_space(str);
+               }
+       }
+
+       /* カッコが閉じていなければヒント無効。 */
+       skip_space(str);
+       if (*str != ')')
+       {
+               parse_ereport(str, ("Closed parenthesis is necessary."));
+               ScanHintDelete(hint);
+               return NULL;
+       }
+
+       /*
+        * ヒントごとに決まっている許容スキャン方式をビットマスクとして設定
+        */
+       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
+       {
+               ScanHintDelete(hint);
+               parse_ereport(str, ("unrecognized hint keyword \"%s\"", keyword));
+               return NULL;
+       }
+
+       /*
+        * 出来上がったヒント情報を追加。スロットが足りない場合は二倍に拡張する。
+        */
+       if (plan->nscan_hints == 0)
+       {
+               plan->max_scan_hints = HINT_ARRAY_DEFAULT_INITSIZE;
+               plan->scan_hints = palloc(sizeof(ScanHint *) * plan->max_scan_hints);
+       }
+       else if (plan->nscan_hints == plan->max_scan_hints)
+       {
+               plan->max_scan_hints *= 2;
+               plan->scan_hints = repalloc(plan->scan_hints,
+                                                               sizeof(ScanHint *) * plan->max_scan_hints);
+       }
+       plan->scan_hints[plan->nscan_hints] = hint;
+       plan->nscan_hints++;
+
+       return str;
+}
+
+static const char *
+ParseJoinMethod(PlanHint *plan, Query *parse, char *keyword, const char *str)
+{
+       char       *relname;
+       JoinHint   *hint;
+
+       skip_space(str);
+
+       hint = JoinHintCreate();
+       hint->opt_str = str;
+       hint->relnames = palloc(sizeof(char *));
+
+       while ((str = parse_quote_value(str, &relname, "table 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)
+       {
+               JoinHintDelete(hint);
+               return NULL;
+       }
+
+       /* Join 対象のテーブルは最低でも2つ指定する必要がある */
+       if (hint->nrels < 2)
+       {
+               JoinHintDelete(hint);
+               parse_ereport(str, ("Specified relation more than two."));
+               return NULL;
+       }
+
+       /* テーブル名順にソートする */
+       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
+       {
+               JoinHintDelete(hint);
+               parse_ereport(str, ("unrecognized hint keyword \"%s\"", keyword));
+               return NULL;
+       }
+
+       if (plan->njoin_hints == 0)
+       {
+               plan->max_join_hints = HINT_ARRAY_DEFAULT_INITSIZE;
+               plan->join_hints = palloc(sizeof(JoinHint *) * plan->max_join_hints);
+       }
+       else if (plan->njoin_hints == plan->max_join_hints)
+       {
+               plan->max_join_hints *= 2;
+               plan->join_hints = repalloc(plan->join_hints,
+                                                               sizeof(JoinHint *) * plan->max_join_hints);
+       }
+
+       plan->join_hints[plan->njoin_hints] = hint;
+       plan->njoin_hints++;
+
+       return str;
+}
+
+static const char *
+ParseLeading(PlanHint *plan, Query *parse, char *keyword, const char *str)
+{
+       char   *relname;
+
+       /*
+        * すでに指定済みの場合は、後で指定したヒントが有効にするため、登録済みの
+        * 情報を削除する
+        */
+       list_free_deep(plan->leading);
+       plan->leading = NIL;
+
+       while ((str = parse_quote_value(str, &relname, "relation name")) != NULL)
+       {
+               const char *p;
+
+               plan->leading = lappend(plan->leading, relname);
+
+               p = str;
+               skip_space(str);
+               if (*str == ')')
+                       break;
+
+               if (p == str)
+               {
+                       parse_ereport(str, ("Must be specified space."));
+                       break;
+               }
+       }
+
+       /* テーブル指定が1つのみの場合は、ヒントを無効にし、パースを続ける */
+       if (list_length(plan->leading) == 1)
+       {
+               parse_ereport(str, ("In %s hint, specified relation name 2 or more.", HINT_LEADING));
+               list_free_deep(plan->leading);
+               plan->leading = NIL;
+       }
+
+       return str;
+}
+
+static const char *
+ParseSet(PlanHint *plan, Query *parse, char *keyword, const char *str)
+{
+       SetHint    *hint;
+
+       hint = SetHintCreate();
+
+       if ((str = parse_quote_value(str, &hint->name, "parameter name")) == NULL ||
+               (str = skip_option_delimiter(str)) == NULL ||
+               (str = parse_quote_value(str, &hint->value, "parameter value")) == NULL)
+       {
+               SetHintDelete(hint);
+               return NULL;
+       }
+
+       skip_space(str);
+       if (*str != ')')
+       {
+               parse_ereport(str, ("Closed parenthesis is necessary."));
+               SetHintDelete(hint);
+               return NULL;
+       }
+       plan->set_hints = lappend(plan->set_hints, hint);
+
+       return str;
+}
+
+#ifdef NOT_USED
+/*
+ * Oracle の ORDERD ヒントの実装
+ */
+static const char *
+Ordered(PlanHint *plan, Query *parse, char *keyword, const char *str)
+{
+       SetHint    *hint;
+
+       hint = SetHintCreate();
+       hint->name = pstrdup("join_collapse_limit");
+       hint->value = pstrdup("1");
+       plan->set_hints = lappend(plan->set_hints, hint);
+
+       return str;
+}
+#endif
+
 static PlannedStmt *
-my_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
+pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
 {
        int                             save_nestlevel;
        PlannedStmt        *result;
@@ -1041,7 +1318,7 @@ my_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
                {
                        ScanHint           *hint = global->scan_hints[i];
 
-                       if (strcmp(hint->relname, rte->eref->aliasname) != 0)
+                       if (RelnameCmp(&rte->eref->aliasname, &hint->relname) != 0)
                                parse_ereport(hint->opt_str, ("Relation \"%s\" does not exist.", hint->relname));
 
                        set_scan_config_options(hint->enforce_mask, global->context);
@@ -1061,7 +1338,9 @@ my_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
        if (pg_hint_plan_debug_print)
        {
                PlanHintDump(global);
-               //elog_node_display(INFO, "rtable", parse->rtable, true);
+#ifdef NOT_USED
+               elog_node_display(INFO, "rtable", parse->rtable, true);
+#endif
        }
 
        PlanHintDelete(global);
@@ -1070,164 +1349,124 @@ my_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
        return result;
 }
 
-static void my_get_relation_info(PlannerInfo *root, Oid relationObjectId,
-                                                                bool inhparent, RelOptInfo *rel)
-{
-       if (prev_get_relation_info)
-               (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
-}
-
 /*
- * pg_add_hint()で登録した個別のヒントを、使用しやすい構造に変換する。
+ * aliasnameと一致するSCANヒントを探す
  */
-static JoinHint *
-set_relids(HashEntry *ent, RelIdInfo **relids, int nrels)
+static ScanHint *
+find_scan_hint(RangeTblEntry *rte)
 {
-       int                     i;
-       int                     j;
-       JoinHint   *hint;
+       int     i;
 
-       hint = palloc(sizeof(JoinHint));
-       hint->joinrelids = NULL;
-
-       for (i = 0; i < ent->tidlist.nrels; i++)
+       for (i = 0; i < global->nscan_hints; i++)
        {
-               for (j = 0; j < nrels; j++)
-               {
-                       if (ent->tidlist.oids[i] == relids[j]->oid)
-                       {
-                               hint->joinrelids =
-                                       bms_add_member(hint->joinrelids, relids[j]->relid);
-                               break;
-                       }
-               }
+               ScanHint   *hint = global->scan_hints[i];
 
-               if (j == nrels)
-               {
-                       pfree(hint);
-                       return NULL;
-               }
+               if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
+                       return hint;
        }
 
-       hint->nrels = ent->tidlist.nrels;
-       hint->enforce_mask = ent->enforce_mask;
-
-       return hint;
+       return NULL;
 }
 
-/*
- * pg_add_hint()で登録したヒントから、今回のクエリで使用するもののみ抽出し、
- * 使用しやすい構造に変換する。
- */
 static void
-build_join_hints(PlannerInfo *root, int level, List *initial_rels)
+pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
+                                                                bool inhparent, RelOptInfo *rel)
 {
-       int                     i;
-       int                     nrels;
-       RelIdInfo **relids;
-       JoinHint   *hint;
+       ScanHint   *hint;
+       ListCell   *cell;
+       ListCell   *prev;
+       ListCell   *next;
 
-       if (1)
+       if (prev_get_relation_info)
+               (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
+
+       /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
+       if (!global)
                return;
 
-       relids = palloc(sizeof(RelIdInfo *) * root->simple_rel_array_size);
+       if (rel->reloptkind != RELOPT_BASEREL)
+               return;
 
-       if (print_log)
+       if ((hint = find_scan_hint(root->simple_rte_array[rel->relid])) == NULL)
+               return;
+
+       /* インデックスを全て削除し、スキャンに使えなくする */
+       if (hint->enforce_mask == ENABLE_SEQSCAN)
        {
-               ListCell   *l;
-               foreach(l, initial_rels)
-               {
-                       RelOptInfo *rel = (RelOptInfo *) lfirst(l);
-                       elog_node_display(INFO, "initial_rels", rel, true);
-               }
-               elog_node_display(INFO, "root", root, true);
-               elog(INFO, "%s(simple_rel_array_size:%d, level:%d, query_level:%d, parent_root:%p)",
-                       __func__, root->simple_rel_array_size, level, root->query_level, root->parent_root);
+               list_free_deep(rel->indexlist);
+               rel->indexlist = NIL;
+
+               return;
        }
 
-       for (i = 0, nrels = 0; i < root->simple_rel_array_size; i++)
+       /* 後でパスを作り直すため、ここではなにもしない */
+       if (hint->indexnames == NULL)
+               return;
+
+       /* 指定されたインデックスのみをのこす */
+       prev = NULL;
+       for (cell = list_head(rel->indexlist); cell; cell = next)
        {
-               if (root->simple_rel_array[i] == NULL)
-                       continue;
+               IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
+               char               *indexname = get_rel_name(info->indexoid);
+               ListCell           *l;
+               bool                    use_index = false;
 
-               relids[nrels] = palloc(sizeof(RelIdInfo));
+               next = lnext(cell);
 
-               Assert(i == root->simple_rel_array[i]->relid);
+               foreach(l, hint->indexnames)
+               {
+                       if (RelnameCmp(&indexname, &lfirst(l)) == 0)
+                       {
+                               use_index = true;
+                               break;
+                       }
+               }
 
-               relids[nrels]->relid = i;
-               relids[nrels]->oid = root->simple_rte_array[i]->relid;
-               relids[nrels]->eref = root->simple_rte_array[i]->eref;
-               //elog(INFO, "%d:%d:%d:%s", i, relids[nrels]->relid, relids[nrels]->oid, relids[nrels]->eref->aliasname);
+               if (!use_index)
+                       rel->indexlist = list_delete_cell(rel->indexlist, cell, prev);
+               else
+                       prev = cell;
 
-               nrels++;
+               pfree(indexname);
        }
+}
 
-       global->join_hint_level = palloc0(sizeof(List *) * (root->simple_rel_array_size));
+static Index
+scan_relid_aliasname(PlannerInfo *root, char *aliasname, bool check_ambiguous, const char *str)
+{
+       /* TODO refnameRangeTblEntry を参考 */
+       int             i;
+       Index   find = 0;
 
-       for (i = 0; i < HASH_ENTRIES; i++)
+       for (i = 1; i < root->simple_rel_array_size; i++)
        {
-               HashEntry *next;
+               if (root->simple_rel_array[i] == NULL)
+                       continue;
 
-               for (next = hashent[i]; next; next = next->next)
-               {
-                       int     lv;
-                       if (!(next->enforce_mask & ENABLE_HASHJOIN) &&
-                               !(next->enforce_mask & ENABLE_NESTLOOP) &&
-                               !(next->enforce_mask & ENABLE_MERGEJOIN))
-                               continue;
+               Assert(i == root->simple_rel_array[i]->relid);
 
-                       if ((hint = set_relids(next, relids, nrels)) == NULL)
-                               continue;
+               if (RelnameCmp(&aliasname, &root->simple_rte_array[i]->eref->aliasname)
+                               != 0)
+                       continue;
 
-                       lv = bms_num_members(hint->joinrelids);
-                       global->join_hint_level[lv] = lappend(global->join_hint_level[lv], hint);
-               }
-       }
-}
+               if (!check_ambiguous)
+                       return i;
 
-static void
-backup_guc(GucVariables *backup)
-{
-       backup->enable_seqscan = enable_seqscan;
-       backup->enable_indexscan = enable_indexscan;
-       backup->enable_bitmapscan = enable_bitmapscan;
-       backup->enable_tidscan = enable_tidscan;
-       backup->enable_sort = enable_sort;
-       backup->enable_hashagg = enable_hashagg;
-       backup->enable_nestloop = enable_nestloop;
-       backup->enable_material = enable_material;
-       backup->enable_mergejoin = enable_mergejoin;
-       backup->enable_hashjoin = enable_hashjoin;
-}
+               if (find)
+                       parse_ereport(str, ("relation name \"%s\" is ambiguous", aliasname));
 
-static void
-restore_guc(GucVariables *backup)
-{
-       enable_seqscan = backup->enable_seqscan;
-       enable_indexscan = backup->enable_indexscan;
-       enable_bitmapscan = backup->enable_bitmapscan;
-       enable_tidscan = backup->enable_tidscan;
-       enable_sort = backup->enable_sort;
-       enable_hashagg = backup->enable_hashagg;
-       enable_nestloop = backup->enable_nestloop;
-       enable_material = backup->enable_material;
-       enable_mergejoin = backup->enable_mergejoin;
-       enable_hashjoin = backup->enable_hashjoin;
-}
+               find = i;
+       }
 
-static void
-set_guc(unsigned char enforce_mask)
-{
-       enable_mergejoin = enforce_mask & ENABLE_MERGEJOIN ? true : false;
-       enable_hashjoin = enforce_mask & ENABLE_HASHJOIN ? true : false;
-       enable_nestloop = enforce_mask & ENABLE_NESTLOOP ? true : false;
+       return find;
 }
 
 /*
  * relidビットマスクと一致するヒントを探す
  */
 static JoinHint *
-find_join_hint(Relids joinrelids)
+scan_join_hint(Relids joinrelids)
 {
        List       *join_hint;
        ListCell   *l;
@@ -1243,482 +1482,226 @@ find_join_hint(Relids joinrelids)
        return NULL;
 }
 
-
 /*
- * 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 void
+rebuild_join_hints(PlanHint *plan, PlannerInfo *root, int level, List *initial_rels)
 {
-       GucVariables    guc;
-       Relids                  joinrelids;
-       JoinHint           *hint;
-       RelOptInfo         *rel;
-
-       if (true)
-               return make_join_rel(root, rel1, rel2);
-
-       joinrelids = bms_union(rel1->relids, rel2->relids);
-       hint = find_join_hint(joinrelids);
-       bms_free(joinrelids);
+       int                     i;
+       ListCell   *l;
+       Relids          joinrelids;
+       int                     njoinrels;
 
-       if (hint)
+       plan->nlevel = root->simple_rel_array_size - 1;
+       plan->join_hint_level = palloc0(sizeof(List *) * (root->simple_rel_array_size));
+       for (i = 0; i < plan->njoin_hints; i++)
        {
-               backup_guc(&guc);
-               set_guc(hint->enforce_mask);
-       }
+               JoinHint   *hint = plan->join_hints[i];
+               int                     j;
+               Index           relid = 0;
 
-       rel = make_join_rel(root, rel1, rel2);
+               for (j = 0; j < hint->nrels; j++)
+               {
+                       char   *relname = hint->relnames[j];
 
-       if (hint)
-               restore_guc(&guc);
+                       relid = scan_relid_aliasname(root, relname, true, hint->opt_str);
+                       if (relid == 0)
+                       {
+                               parse_ereport(hint->opt_str, ("Relation \"%s\" does not exist.", relname));
+                               break;
+                       }
 
-       return rel;
-}
+                       hint->joinrelids = bms_add_member(hint->joinrelids, relid);
+               }
 
-/*
- * PostgreSQL 本体から流用した関数
- */
+               if (relid == 0)
+                       continue;
 
-/*
- * 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)
-{
-       int                     lev;
-       RelOptInfo *rel;
+               plan->join_hint_level[hint->nrels] =
+                       lappend(plan->join_hint_level[hint->nrels], hint);
+       }
 
-       /*
-        * 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);
+       /* Leading hint は、全ての join 方式が有効な hint として登録する */
+       joinrelids = NULL;
+       njoinrels = 0;
+       foreach(l, plan->leading)
+       {
+               char       *relname = (char *)lfirst(l);
+               JoinHint   *hint;
 
-       /*
-        * 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 *));
+               i = scan_relid_aliasname(root, relname, true, plan->hint_str);
+               if (i == 0)
+               {
+                       parse_ereport(plan->hint_str, ("Relation \"%s\" does not exist.", relname));
+                       list_free_deep(plan->leading);
+                       plan->leading = NIL;
+                       break;
+               }
 
-       root->join_rel_level[1] = initial_rels;
+               joinrelids = bms_add_member(joinrelids, i);
+               njoinrels++;
 
-       build_join_hints(root, levels_needed, initial_rels);
+               if (njoinrels < 2)
+                       continue;
 
-       for (lev = 2; lev <= levels_needed; lev++)
-       {
-               ListCell   *lc;
-
-               /*
-                * 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);
-
-               /*
-                * Do cleanup work on each just-processed rel.
-                */
-               foreach(lc, root->join_rel_level[lev])
+               if (njoinrels > plan->nlevel)
                {
-                       rel = (RelOptInfo *) lfirst(lc);
-
-                       /* Find and save the cheapest paths for this rel */
-                       set_cheapest(rel);
-
-#ifdef OPTIMIZER_DEBUG
-                       debug_print_rel(root, rel);
-#endif
+                       parse_ereport(plan->hint_str, ("In %s hint, specified relation name %d or less.", HINT_LEADING, plan->nlevel));
+                       break;
                }
-       }
 
-       /*
-        * 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);
+               /* Leading で指定した組み合わせ以外の join hint を削除する */
+               hint = scan_join_hint(joinrelids);
+               list_free(plan->join_hint_level[njoinrels]);
+               if (hint)
+                       plan->join_hint_level[njoinrels] = lappend(NIL, hint);
+               else
+               {
+                       /*
+                        * Here relnames is not set, since Relids bitmap is sufficient to
+                        * control paths of this query afterwards.
+                        */
+                       hint = JoinHintCreate();
+                       hint->nrels = njoinrels;
+                       hint->enforce_mask = ENABLE_ALL_JOIN;
+                       hint->joinrelids = bms_copy(joinrelids);
+                       plan->join_hint_level[njoinrels] = lappend(NIL, hint);
 
-       rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
+                       if (plan->njoin_hints == 0)
+                       {
+                               plan->max_join_hints = HINT_ARRAY_DEFAULT_INITSIZE;
+                               plan->join_hints = palloc(sizeof(JoinHint *) * plan->max_join_hints);
+                       }
+                       else if (plan->njoin_hints == plan->max_join_hints)
+                       {
+                               plan->max_join_hints *= 2;
+                               plan->join_hints = repalloc(plan->join_hints,
+                                                                       sizeof(JoinHint *) * plan->max_join_hints);
+                       }
 
-       root->join_rel_level = NULL;
+                       plan->join_hints[plan->njoin_hints] = hint;
+                       plan->njoin_hints++;
+               }
+       }
 
-       return rel;
+       bms_free(joinrelids);
 }
 
-/*
- * 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.
- *
- * 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].
- */
 static void
-my_join_search_one_level(PlannerInfo *root, int level)
+rebuild_scan_path(PlanHint *plan, PlannerInfo *root, int level, List *initial_rels)
 {
-       List      **joinrels = root->join_rel_level;
-       ListCell   *r;
-       int                     k;
-
-       Assert(joinrels[level] == NIL);
-
-       /* Set join_cur_level so that new joinrels are added to proper list */
-       root->join_cur_level = level;
+       int     i;
+       int     save_nestlevel = 0;
 
-       /*
-        * 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])
+       for (i = 0; i < plan->nscan_hints; i++)
        {
-               RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
-               ListCell   *other_rels;
+               ScanHint   *hint = plan->scan_hints[i];
+               ListCell   *l;
 
-               if (level == 2)
-                       other_rels = lnext(r);          /* only consider remaining initial
-                                                                                * rels */
-               else
-                       other_rels = list_head(joinrels[1]);            /* consider all initial
-                                                                                                                * rels */
+               if (hint->enforce_mask == ENABLE_SEQSCAN)
+                       continue;
 
-               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
+               foreach(l, initial_rels)
                {
-                       /*
-                        * 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);
-               }
-       }
-
-       /*
-        * 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++)
-       {
-               int                     other_level = level - k;
+                       RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
+                       RangeTblEntry  *rte = root->simple_rte_array[rel->relid];
 
-               /*
-                * 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;
+                       if (rel->reloptkind != RELOPT_BASEREL ||
+                               RelnameCmp(&hint->relname, &rte->eref->aliasname) != 0)
+                               continue;
 
-               foreach(r, joinrels[k])
-               {
-                       RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
-                       ListCell   *other_rels;
-                       ListCell   *r2;
+                       if (save_nestlevel != 0)
+                               save_nestlevel = NewGUCNestLevel();
 
                        /*
-                        * We can ignore clauseless joins here, *except* when they
-                        * participate in join-order restrictions --- then we might have
-                        * to force a bushy join plan.
+                        * TODO ヒントで指定されたScan方式が最安価でない場合のみ、Pathを生成
+                        * しなおす
                         */
-                       if (old_rel->joininfo == NIL && !old_rel->has_eclass_joins &&
-                               !has_join_restriction(root, old_rel))
-                               continue;
+                       set_scan_config_options(hint->enforce_mask, plan->context);
 
-                       if (k == other_level)
-                               other_rels = lnext(r);  /* only consider remaining rels */
-                       else
-                               other_rels = list_head(joinrels[other_level]);
+                       rel->pathlist = NIL;    /* TODO 解放 */
+                       set_plain_rel_pathlist(root, rel, rte);
 
-                       for_each_cell(r2, other_rels)
-                       {
-                               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);
-                                       }
-                               }
-                       }
+                       break;
                }
        }
 
        /*
-        * 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).
+        * Restore the GUC variables we set above.
         */
-       if (joinrels[level] == NIL)
-       {
-               /*
-                * 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;
-
-                       if (level == 2)
-                               other_rels = lnext(r);  /* only consider remaining initial
-                                                                                * rels */
-                       else
-                               other_rels = list_head(joinrels[1]);    /* consider all initial
-                                                                                                                * rels */
-
-                       make_rels_by_clauseless_joins(root,
-                                                                                 old_rel,
-                                                                                 other_rels);
-               }
-
-               /*----------
-                * 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);
-       }
+       if (save_nestlevel != 0)
+               AtEOXact_GUC(true, save_nestlevel);
 }
 
 /*
  * src/backend/optimizer/path/joinrels.c
- * static make_rels_by_clause_joins() を流用
+ * export make_join_rel() をラップする関数
  * 
- * 変更箇所
- *  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.
+ * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
+ * 呼び出す。
  */
-static void
-make_rels_by_clause_joins(PlannerInfo *root,
-                                                 RelOptInfo *old_rel,
-                                                 ListCell *other_rels)
+static RelOptInfo *
+pg_hint_plan_make_join_rel(PlannerInfo *root, RelOptInfo *rel1, RelOptInfo *rel2)
 {
-       ListCell   *l;
+       Relids                  joinrelids;
+       JoinHint           *hint;
+       RelOptInfo         *rel;
+       int                             save_nestlevel;
 
-       for_each_cell(l, other_rels)
-       {
-               RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
+       joinrelids = bms_union(rel1->relids, rel2->relids);
+       hint = scan_join_hint(joinrelids);
+       bms_free(joinrelids);
 
-               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)))
-               {
-                       (void) my_make_join_rel(root, old_rel, other_rel);
-               }
-       }
-}
+       if (!hint)
+               return make_join_rel(root, rel1, rel2);
 
-/*
- * src/backend/optimizer/path/joinrels.c
- * static make_rels_by_clauseless_joins() を流用
- * 
- * 変更箇所
- *  make_join_rel() の呼び出しをラップする、my_make_join_rel()の呼び出しに変更
- */
-/*
- * 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 void
-make_rels_by_clauseless_joins(PlannerInfo *root,
-                                                         RelOptInfo *old_rel,
-                                                         ListCell *other_rels)
-{
-       ListCell   *l;
+       save_nestlevel = NewGUCNestLevel();
 
-       for_each_cell(l, other_rels)
-       {
-               RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
+       set_join_config_options(hint->enforce_mask, global->context);
 
-               if (!bms_overlap(other_rel->relids, old_rel->relids))
-               {
-                       (void) my_make_join_rel(root, old_rel, other_rel);
-               }
-       }
+       rel = make_join_rel(root, rel1, rel2);
+
+       /*
+        * Restore the GUC variables we set above.
+        */
+       AtEOXact_GUC(true, save_nestlevel);
+
+       return rel;
 }
 
-/*
- * src/backend/optimizer/path/joinrels.c
- * static has_join_restriction() を流用
- * 
- * 変更箇所
- *  なし
- */
-/*
- * has_join_restriction
- *             Detect whether the specified relation has join-order restrictions
- *             due to being inside an outer join or an IN (sub-SELECT).
- *
- * 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.)
- */
-static bool
-has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
+static RelOptInfo *
+pg_hint_plan_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
 {
-       ListCell   *l;
-
-       foreach(l, root->join_info_list)
+       /*
+        * pg_hint_planが無効、または有効なヒントが1つも指定されなかった場合は、標準
+        * の処理を行う。
+        */
+       if (!global)
        {
-               SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
-
-               /* ignore full joins --- other mechanisms preserve their ordering */
-               if (sjinfo->jointype == JOIN_FULL)
-                       continue;
+               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);
+       }
 
-               /* 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))
-                       continue;
+       rebuild_join_hints(global, root, levels_needed, initial_rels);
+       rebuild_scan_path(global, root, levels_needed, initial_rels);
 
-               /* 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;
-       }
+       /*
+        * GEQOを使用する条件を満たした場合は、GEQOを用いた結合方式の検索を行う。
+        * このとき、スキャン方式のヒントとSetヒントのみが有効になり、結合方式や結合
+        * 順序はヒント句は無効になりGEQOのアルゴリズムで決定される。
+        */
+       if (enable_geqo && levels_needed >= geqo_threshold)
+               return geqo(root, levels_needed, initial_rels);
 
-       return false;
+       return standard_join_search_org(root, levels_needed, initial_rels);
 }
+
+#define standard_join_search standard_join_search_org
+#define join_search_one_level pg_hint_plan_join_search_one_level
+#define make_join_rel pg_hint_plan_make_join_rel
+#include "core.c"