OSDN Git Service

ParseScanMethodをPostgreSQL9.1に対応した。
[pghintplan/pg_hint_plan.git] / pg_hint_plan.c
index b2394fe..b398018 100644 (file)
@@ -1,31 +1,68 @@
 /*-------------------------------------------------------------------------
  *
  * 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 "nodes/print.h"
-#include "utils/elog.h"
-#include "utils/builtins.h"
-#include "utils/memutils.h"
-#include "optimizer/cost.h"
+#include "miscadmin.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/lsyscache.h"
 
 #ifdef PG_MODULE_MAGIC
 PG_MODULE_MAGIC;
 #endif
 
-#define HASH_ENTRIES 201
+#if PG_VERSION_NUM < 90100
+#error unsupported PostgreSQL version
+#endif
+
+#define HINT_START     "/*"
+#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"
+#if PG_VERSION_NUM >= 90200
+#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
+
+#define parse_ereport(str, detail) \
+       ereport(pg_hint_plan_parse_message, \
+                       (errmsg("hint syntax error at or near \"%s\"", (str)), \
+                        errdetail detail))
+
+#define skip_space(str) \
+       while (isspace(*str)) \
+               str++;
 
 enum
 {
@@ -38,94 +75,158 @@ enum
        ENABLE_HASHJOIN         = 0x40
 } TYPE_BITS;
 
-typedef struct tidlist
+#define ENABLE_ALL_SCAN (ENABLE_SEQSCAN | ENABLE_INDEXSCAN | ENABLE_BITMAPSCAN \
+                                               | ENABLE_TIDSCAN)
+#define ENABLE_ALL_JOIN (ENABLE_NESTLOOP | ENABLE_MERGEJOIN | ENABLE_HASHJOIN)
+
+/* scan method hints */
+typedef struct ScanHint
 {
-       int nrels;
-       Oid *oids;
-} TidList;
+       const char         *opt_str;            /* must not do pfree */
+       char               *relname;
+       List               *indexnames;
+       unsigned char   enforce_mask;
+} ScanHint;
 
-typedef struct hash_entry
+/* join method hints */
+typedef struct JoinHint
 {
-       TidList tidlist;
-       unsigned char enforce_mask;
-       struct hash_entry *next;
-} HashEntry;
+       const char         *opt_str;            /* must not do pfree */
+       int                             nrels;
+       char              **relnames;
+       unsigned char   enforce_mask;
+       Relids                  joinrelids;
+} JoinHint;
 
-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;
+/* change a run-time parameter hints */
+typedef struct SetHint
+{
+       char   *name;                           /* name of variable */
+       char   *value;
+} SetHint;
+
+/*
+ * Describes a context of hint processing.
+ */
+typedef struct PlanHint
+{
+       char       *hint_str;           /* original hint string */
+
+       /* 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 */
+
+       /* 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;                 /* # of relations to be joined */
+       List      **join_hint_level;
+
+       /* for Leading hints */
+       List       *leading;            /* relation names specified in Leading hint */
+
+       /* 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;
+       bool    have_paren;
+       HintParserFunction      hint_parser;
+} 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);
 
+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 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 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);
+static const char *Ordered(PlanHint *plan, Query *parse, char *keyword, const char *str);
 #endif
-static void free_hashent(HashEntry *head);
-static unsigned int calc_hash(TidList *tidlist);
-#ifdef NOT_USED
-static HashEntry *search_ent(TidList *tidlist);
-#endif
-
-/* Join Method Hints */
-typedef struct RelIdInfo
-{
-       Index           relid;
-       Oid                     oid;
-       Alias      *eref;
-} RelIdInfo;
-
-typedef struct JoinHint
-{
-       int                             nrels;
-       List               *relidinfos;
-       Relids                  joinrelids;
-       unsigned char   enforce_mask;
-} JoinHint;
 
-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 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 RelOptInfo *my_join_search(PlannerInfo *root, int levels_needed,
-                                                         List *initial_rels);
-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 join_search_hook_type org_join_search = NULL;
-static List **join_hint_level = NULL;
-
-PG_FUNCTION_INFO_V1(pg_add_hint);
-PG_FUNCTION_INFO_V1(pg_clear_hint);
+static void set_plain_rel_pathlist(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte);
+
+
+/* GUC variables */
+static bool pg_hint_plan_enable = true;
+static bool pg_hint_plan_debug_print = false;
+static int pg_hint_plan_parse_message = INFO;
+
+static const struct config_enum_entry parse_message_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 planner_hook_type prev_planner_hook = NULL;
+static get_relation_info_hook_type prev_get_relation_info = NULL;
+static join_search_hook_type prev_join_search = NULL;
+
+/* フック関数をまたがって使用する情報を管理する */
+static PlanHint *global = NULL;
+
+static const HintParser parsers[] = {
+       {HINT_SEQSCAN, true, ParseScanMethod},
+       {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},
+       {HINT_NONESTLOOP, true, ParseJoinMethod},
+       {HINT_NOMERGEJOIN, true, ParseJoinMethod},
+       {HINT_NOHASHJOIN, true, ParseJoinMethod},
+       {HINT_LEADING, true, ParseLeading},
+       {HINT_SET, true, ParseSet},
+       {NULL, false, NULL},
+};
 
 /*
  * Module load callbacks
@@ -133,1211 +234,1474 @@ PG_FUNCTION_INFO_V1(pg_clear_hint);
 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_message",
+                                                        "Messege level of the parse error.",
+                                                        NULL,
+                                                        &pg_hint_plan_parse_message,
+                                                        INFO,
+                                                        parse_message_level_options,
+                                                        PGC_USERSET,
+                                                        0,
+                                                        NULL,
+                                                        NULL,
+                                                        NULL);
+
+       /* Install hooks. */
+       prev_planner_hook = 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;
+       /* Uninstall hooks. */
+       planner_hook = prev_planner_hook;
+       get_relation_info_hook = prev_get_relation_info;
+       join_search_hook = prev_join_search;
+}
 
-#ifdef NOT_USED
-       cost_hook = org_cost_hook;
-#endif
-       join_search_hook = org_join_search;
+static ScanHint *
+ScanHintCreate(void)
+{
+       ScanHint           *hint;
 
-       for (i = 0 ; i < HASH_ENTRIES ; i++)
-       {
-               free_hashent(hashent[i]);
-               hashent[i] = NULL;
+       hint = palloc(sizeof(ScanHint));
+       hint->opt_str = NULL;
+       hint->relname = NULL;
+       hint->indexnames = NIL;
+       hint->enforce_mask = 0;
 
-       }
+       return hint;
 }
 
-#ifdef NOT_USED
-char *rels_str(PlannerInfo *root, Path *path)
+static void
+ScanHintDelete(ScanHint *hint)
+{
+       if (!hint)
+               return;
+
+       if (hint->relname)
+               pfree(hint->relname);
+       list_free_deep(hint->indexnames);
+       pfree(hint);
+}
+
+static JoinHint *
+JoinHintCreate(void)
 {
-       char buf[4096];                                                         
-       int relid;
-       int first = 1;
-       Bitmapset *tmpbms;
+       JoinHint   *hint;
+
+       hint = palloc(sizeof(JoinHint));
+       hint->opt_str = NULL;
+       hint->nrels = 0;
+       hint->relnames = NULL;
+       hint->enforce_mask = 0;
+       hint->joinrelids = NULL;
 
-       if (path->pathtype == T_Invalid) return strdup("");
+       return hint;
+}
 
-       tmpbms = bms_copy(path->parent->relids);
+static void
+JoinHintDelete(JoinHint *hint)
+{
+       if (!hint)
+               return;
 
-       buf[0] = 0;
-       while ((relid = bms_first_member(tmpbms)) >= 0)
+       if (hint->relnames)
        {
-               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;
+               int     i;
+
+               for (i = 0; i < hint->nrels; i++)
+                       pfree(hint->relnames[i]);
+               pfree(hint->relnames);
        }
+       bms_free(hint->joinrelids);
+       pfree(hint);
+}
+
+static SetHint *
+SetHintCreate(void)
+{
+       SetHint    *hint;
+
+       hint = palloc(sizeof(SetHint));
+       hint->name = NULL;
+       hint->value = NULL;
+
+       return hint;
+}
 
-       return strdup(buf);
+static void
+SetHintDelete(SetHint *hint)
+{
+       if (!hint)
+               return;
+
+       if (hint->name)
+               pfree(hint->name);
+       if (hint->value)
+               pfree(hint->value);
+       pfree(hint);
 }
-#endif
 
-static int oidsortcmp(const void *a, const void *b)
+static PlanHint *
+PlanHintCreate(void)
 {
-       const Oid oida = *((const Oid *)a);
-       const Oid oidb = *((const Oid *)b);
+       PlanHint   *hint;
+
+       hint = palloc(sizeof(PlanHint));
+       hint->hint_str = NULL;
+       hint->nscan_hints = 0;
+       hint->max_scan_hints = 0;
+       hint->scan_hints = NULL;
+       hint->njoin_hints = 0;
+       hint->max_join_hints = 0;
+       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;
 
-       return oida - oidb;
+       return hint;
 }
 
-#ifdef NOT_USED
-static TidList *maketidlist(PlannerInfo *root, Path *path1, Path *path2)
+static void
+PlanHintDelete(PlanHint *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);
-       }
+       ListCell   *l;
+       int                     i;
 
-       ret->nrels = nrels;
-       ret->oids = (Oid *)malloc(nrels * sizeof(Oid));
+       if (!hint)
+               return;
 
-       for (i = 0 ; i < 2 ; i++)
-       {
-               Bitmapset *tmpbms;
+       if (hint->hint_str)
+               pfree(hint->hint_str);
 
-               if (paths[i] == NULL) continue;
+       for (i = 0; i < hint->nscan_hints; i++)
+               ScanHintDelete(hint->scan_hints[i]);
+       if (hint->scan_hints)
+               pfree(hint->scan_hints);
 
-               tmpbms= bms_copy(paths[i]->parent->relids);
+       for (i = 0; i < hint->njoin_hints; i++)
+               JoinHintDelete(hint->join_hints[i]);
+       if (hint->join_hints)
+               pfree(hint->join_hints);
 
-               while ((relid = bms_first_member(tmpbms)) >= 0)
-                       ret->oids[j++] = root->simple_rte_array[relid]->relid;
-       }
+       for (i = 2; i <= hint->nlevel; i++)
+               list_free(hint->join_hint_level[i]);
+       if (hint->join_hint_level)
+               pfree(hint->join_hint_level);
 
-       if (nrels > 1)
-               qsort(ret->oids, nrels, sizeof(Oid), oidsortcmp);
+       list_free_deep(hint->leading);
 
-       return ret;
-}
+       foreach(l, hint->set_hints)
+               SetHintDelete((SetHint *) lfirst(l));
+       list_free(hint->set_hints);
 
-static void free_tidlist(TidList *tidlist)
-{
-       if (tidlist)
-       {
-               if (tidlist->oids)
-                       free(tidlist->oids);
-               free(tidlist);
-       }
+       pfree(hint);
 }
 
-int r = 0;
-static void dump_rels(char *label, PlannerInfo *root, Path *path, bool found, bool enabled)
+static bool
+PlanHintIsempty(PlanHint *hint)
 {
-       char *relsstr;
-
-       if (!print_log) return;
-       relsstr = rels_str(root, path);
-       ereport(INFO, (errmsg_internal("SCAN: %04d: %s for relation %s (%s, %s)\n",
-                                                                 r++, label, relsstr,
-                                                                 found ? "found" : "not found",
-                                                                 enabled ? "enabled" : "disabled")));
-       free(relsstr);
+       if (hint->nscan_hints == 0 &&
+               hint->njoin_hints == 0 &&
+               hint->leading == NIL &&
+               hint->set_hints == NIL)
+               return true;
+
+       return false;
 }
 
-int J = 0;
-void dump_joinrels(char *label, PlannerInfo *root, Path *inpath, Path *outpath,
-                                  bool found, bool enabled)
+/* TODO オブジェクト名のクォート処理を追加 */
+static void
+PlanHintDump(PlanHint *hint)
 {
-       char *irelstr, *orelstr;
-
-       if (!print_log) return;
-       irelstr = rels_str(root, inpath);
-       orelstr = rels_str(root, outpath);
-
-       ereport(INFO, (errmsg_internal("JOIN: %04d: %s for relation ((%s),(%s)) (%s, %s)\n",
-                                                                 J++, label, irelstr, orelstr,
-                                                                 found ? "found" : "not found",
-                                                                 enabled ? "enabled" : "disabled")));
-       free(irelstr);
-       free(orelstr);
-}
+       StringInfoData  buf;
+       ListCell           *l;
+       int                             i;
+       bool                    is_first = true;
 
+       if (!hint)
+       {
+               elog(INFO, "no hint");
+               return;
+       }
 
-bool my_cost_hook(CostHookType type, PlannerInfo *root, Path *path1, Path *path2)
-{
-       TidList *tidlist;
-       HashEntry *ent;
-       bool ret = false;
+       initStringInfo(&buf);
+       appendStringInfo(&buf, "/*\n");
+       for (i = 0; i < hint->nscan_hints; i++)
+       {
+               ScanHint   *h = hint->scan_hints[i];
+               ListCell   *n;
+               switch(h->enforce_mask)
+               {
+                       case(ENABLE_SEQSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_SEQSCAN);
+                               break;
+                       case(ENABLE_INDEXSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_INDEXSCAN);
+                               break;
+                       case(ENABLE_BITMAPSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_BITMAPSCAN);
+                               break;
+                       case(ENABLE_TIDSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_TIDSCAN);
+                               break;
+                       case(ENABLE_INDEXSCAN | ENABLE_BITMAPSCAN | ENABLE_TIDSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_NOSEQSCAN);
+                               break;
+                       case(ENABLE_SEQSCAN | ENABLE_BITMAPSCAN | ENABLE_TIDSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_NOINDEXSCAN);
+                               break;
+                       case(ENABLE_SEQSCAN | ENABLE_INDEXSCAN | ENABLE_TIDSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_NOBITMAPSCAN);
+                               break;
+                       case(ENABLE_SEQSCAN | ENABLE_INDEXSCAN | ENABLE_BITMAPSCAN):
+                               appendStringInfo(&buf, "%s(", HINT_NOTIDSCAN);
+                               break;
+                       default:
+                               appendStringInfoString(&buf, "\?\?\?(");
+                               break;
+               }
+               appendStringInfo(&buf, "%s", h->relname);
+               foreach(n, h->indexnames)
+                       appendStringInfo(&buf, " %s", (char *) lfirst(n));
+               appendStringInfoString(&buf, ")\n");
+       }
 
-       if (!tweak_enabled)
+       for (i = 0; i < hint->njoin_hints; i++)
        {
-               switch (type)
+               JoinHint   *h = hint->join_hints[i];
+               int                     i;
+               switch(h->enforce_mask)
                {
-                       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;
+                       case(ENABLE_NESTLOOP):
+                               appendStringInfo(&buf, "%s(", HINT_NESTLOOP);
+                               break;
+                       case(ENABLE_MERGEJOIN):
+                               appendStringInfo(&buf, "%s(", HINT_MERGEJOIN);
+                               break;
+                       case(ENABLE_HASHJOIN):
+                               appendStringInfo(&buf, "%s(", HINT_HASHJOIN);
+                               break;
+                       case(ENABLE_ALL_JOIN ^ ENABLE_NESTLOOP):
+                               appendStringInfo(&buf, "%s(", HINT_NONESTLOOP);
+                               break;
+                       case(ENABLE_ALL_JOIN ^ ENABLE_MERGEJOIN):
+                               appendStringInfo(&buf, "%s(", HINT_NOMERGEJOIN);
+                               break;
+                       case(ENABLE_ALL_JOIN ^ ENABLE_HASHJOIN):
+                               appendStringInfo(&buf, "%s(", HINT_NOHASHJOIN);
+                               break;
+                       case(ENABLE_ALL_JOIN):
+                               continue;
                        default:
-                               ereport(LOG, (errmsg_internal("Unknown cost type")));
+                               appendStringInfoString(&buf, "\?\?\?(");
                                break;
                }
+               appendStringInfo(&buf, "%s", h->relnames[0]);
+               for (i = 1; i < h->nrels; i++)
+                       appendStringInfo(&buf, " %s", h->relnames[i]);
+               appendStringInfoString(&buf, ")\n");
+       }
+
+       foreach(l, hint->set_hints)
+       {
+               SetHint    *h = (SetHint *) lfirst(l);
+               appendStringInfo(&buf, "%s(%s %s)\n", HINT_SET, h->name, h->value);
        }
-       switch (type)
+
+       foreach(l, hint->leading)
        {
-               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 (is_first)
+               {
+                       appendStringInfo(&buf, "%s(%s", HINT_LEADING, (char *)lfirst(l));
+                       is_first = false;
+               }
+               else
+                       appendStringInfo(&buf, " %s", (char *)lfirst(l));
        }
-       
-       return true;
+       if (!is_first)
+               appendStringInfoString(&buf, ")\n");
+
+       appendStringInfoString(&buf, "*/");
+
+       elog(INFO, "%s", buf.data);
+
+       pfree(buf.data);
 }
-#endif
 
-static void free_hashent(HashEntry *head)
+static int
+RelnameCmp(const void *a, const void *b)
 {
-       HashEntry *next = head;
+       const char *relnamea = *((const char **) a);
+       const char *relnameb = *((const char **) b);
 
-       while (next)
-       {
-               HashEntry *last = next;
-               if (next->tidlist.oids != NULL) free(next->tidlist.oids);
-               next = next->next;
-               free(last);
-       }
+       return strcmp(relnamea, relnameb);
 }
 
-static HashEntry *parse_tidlist(char **str)
+static int
+ScanHintCmp(const void *a, const void *b, bool order)
 {
-       char tidstr[8];
-       char *p0;
-       Oid tid[20]; /* ^^; */
-       int ntids = 0;
-       int i, len;
-       HashEntry *ret;
-
-       while (isdigit(**str) && ntids < 20)
-       {
-               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;
+       const ScanHint     *hinta = *((const ScanHint **) a);
+       const ScanHint     *hintb = *((const ScanHint **) b);
+       int                                     result;
 
-               if (**str == ',') (*str)++;
-       }
+       if ((result = RelnameCmp(&hinta->relname, &hintb->relname)) != 0)
+               return result;
 
-       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;     
+       /* ヒント句で指定した順を返す */
+       if (order)
+               return hinta->opt_str - hintb->opt_str;
+       else
+               return 0;
 }
 
-static int parse_phrase(HashEntry **head, char **str)
+static int
+ScanHintCmpIsOrder(const void *a, const void *b)
 {
-       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;
-       bool    not_use = false;
-
-       p0 = *str;
-       while (isalpha(**str) || **str == '_') (*str)++;
-       len = *str - p0;
-       if (**str != '(' || len >= 12) return 0;
-       strncpy(req, p0, len);
-       req[len] = 0;
-       if (strncmp("no_", req, 3) == 0)
-       {
-               not_use = true;
-               memmove(req, req + 3, len - 3 + 1);
-       }
-       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 = not_use ? ~masks[cmd] : masks[cmd];
-       ent->next = NULL;
-       *head = ent;
-
-       return 1;
+       return ScanHintCmp(a, b, true);
 }
 
-
-static HashEntry* parse_top(char* str)
+static int
+JoinHintCmp(const void *a, const void *b, bool order)
 {
-       HashEntry *head = NULL;
-       HashEntry *ent = NULL;
-
-       if (!parse_phrase(&head, &str))
-       {
-               free_hashent(head);
-               return NULL;
-       }
-       ent = head;
+       const JoinHint     *hinta = *((const JoinHint **) a);
+       const JoinHint     *hintb = *((const JoinHint **) b);
 
-       while (*str)
+       if (hinta->nrels == hintb->nrels)
        {
-               if (!parse_phrase(&ent->next, &str))
+               int     i;
+               for (i = 0; i < hinta->nrels; i++)
                {
-                       free_hashent(head);
-                       return NULL;
+                       int     result;
+                       if ((result = RelnameCmp(&hinta->relnames[i], &hintb->relnames[i])) != 0)
+                               return result;
                }
-               ent = ent->next;
+
+               /* ヒント句で指定した順を返す */
+               if (order)
+                       return hinta->opt_str - hintb->opt_str;
+               else
+                       return 0;
        }
 
-       return head;
+       return hinta->nrels - hintb->nrels;
 }
 
-static bool ent_matches(TidList *key, HashEntry *ent2)
+static int
+JoinHintCmpIsOrder(const void *a, const void *b)
 {
-       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;
+       return JoinHintCmp(a, b, true);
 }
 
-static unsigned int calc_hash(TidList *tidlist)
+#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)
 {
-       unsigned int hash = 0;
-       int i = 0;
-       
-       for (i = 0 ; i < tidlist->nrels ; i++)
+       int                             result = 0;
+       MemoryContext   ccxt = CurrentMemoryContext;
+
+       PG_TRY();
        {
-               int j = 0;
-               for (j = 0 ; j < sizeof(Oid) ; j++)
-                       hash = hash * 2 + ((tidlist->oids[i] >> (j * 8)) & 0xff);
+               result = set_config_option(name, value, context, source,
+                                                                  action, changeVal);
        }
+       PG_CATCH();
+       {
+               ErrorData          *errdata;
+               MemoryContext   ecxt;
 
-       return hash % HASH_ENTRIES;
-;
-}
+               if (elevel >= ERROR)
+                       PG_RE_THROW();
 
-#ifdef NOT_USED
-static HashEntry *search_ent(TidList *tidlist)
-{
-       HashEntry *ent;
-       if (tidlist == NULL) return NULL;
+               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);
 
-       ent = hashent[calc_hash(tidlist)];
-       while(ent)
-       {
-               if (ent_matches(tidlist, ent))
-                       return ent;
-               ent = ent->next;
+               MemoryContextSwitchTo(ecxt);
        }
+       PG_END_TRY();
 
-       return NULL;
+       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
 
-Datum
-pg_add_hint(PG_FUNCTION_ARGS)
+static int
+set_config_options(List *options, GucContext context)
 {
-       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));
-
-       ret = parse_top(str);
+       ListCell   *l;
+       int                     save_nestlevel;
+       int                     result = 1;
 
-       if (ret == NULL)
-               ereport(ERROR, (errmsg_internal("Parse Error")));
+       save_nestlevel = NewGUCNestLevel();
 
-       while (ret)
+       foreach(l, options)
        {
-               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;
-               }
+               SetHint    *hint = (SetHint *) lfirst(l);
 
-               i++;
-               next = ret->next;
-               ret->next = hashent[hash];
-               hashent[hash] = ret;
-               ret = next;
+               if (result > 0)
+                       result = set_config_option(hint->name, hint->value, context,
+                                               PGC_S_SESSION, GUC_ACTION_SAVE, true,
+                                               pg_hint_plan_parse_message);
        }
-       PG_RETURN_INT32(i);
-}
-
-Datum
-pg_clear_hint(PG_FUNCTION_ARGS)
-{
-       int i;
-       int n = 0;
-
-       for (i = 0 ; i < HASH_ENTRIES ; i++)
-       {
-               free_hashent(hashent[i]);
-               hashent[i] = NULL;
-               n++;
 
-       }
-       PG_RETURN_INT32(n);
+       return save_nestlevel;
 }
 
-Datum
-pg_enable_hint(bool arg, bool *isnull)
+#define SET_CONFIG_OPTION(name, enforce_mask, type_bits) \
+       set_config_option((name), \
+               ((enforce_mask) & (type_bits)) ? "true" : "false", \
+               context, PGC_S_SESSION, GUC_ACTION_SAVE, true, ERROR)
+
+static void
+set_join_config_options(unsigned char enforce_mask, GucContext context)
 {
-       tweak_enabled = arg;
-       PG_RETURN_INT32(0);
+       SET_CONFIG_OPTION("enable_nestloop", enforce_mask, ENABLE_NESTLOOP);
+       SET_CONFIG_OPTION("enable_mergejoin", enforce_mask, ENABLE_MERGEJOIN);
+       SET_CONFIG_OPTION("enable_hashjoin", enforce_mask, ENABLE_HASHJOIN);
 }
 
-Datum
-pg_enable_log(bool arg, bool *isnull)
+static void
+set_scan_config_options(unsigned char enforce_mask, GucContext context)
 {
-       print_log = arg;
-       PG_RETURN_INT32(0);
+       SET_CONFIG_OPTION("enable_seqscan", enforce_mask, ENABLE_SEQSCAN);
+       SET_CONFIG_OPTION("enable_indexscan", enforce_mask, ENABLE_INDEXSCAN);
+       SET_CONFIG_OPTION("enable_bitmapscan", enforce_mask, ENABLE_BITMAPSCAN);
+       SET_CONFIG_OPTION("enable_tidscan", enforce_mask, ENABLE_TIDSCAN);
+#if PG_VERSION_NUM >= 90200
+       SET_CONFIG_OPTION("enable_indexonlyscan", enforce_mask, ENABLE_INDEXSCAN);
+#endif
 }
 
-static int putsbuf(char **p, char *bottom, char *str)
+/*
+ * parse functions
+ */
+
+static const char *
+parse_keyword(const char *str, StringInfo buf)
 {
-       while (*p < bottom && *str)
-       {
-               *(*p)++ = *str++;
-       }
+       skip_space(str);
+
+       while (!isspace(*str) && *str != '(' && *str != '\0')
+               appendStringInfoChar(buf, *str++);
 
-       return (*str == 0);
+       return str;
 }
 
-static void dump_ent(HashEntry *ent, char **p, char *bottom)
+static const char *
+skip_opened_parenthesis(const char *str)
 {
-       static char typesigs[] = "SIBTNMH";
-       char sigs[sizeof(typesigs)];
-       int i;
+       skip_space(str);
 
-       if (!putsbuf(p, bottom, "[(")) return;
-       for (i = 0 ; i < ent->tidlist.nrels ; i++)
+       if (*str != '(')
        {
-               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';
+               parse_ereport(str, ("Opened parenthesis is necessary."));
+               return NULL;
        }
-       if (!putsbuf(p, bottom, sigs)) return;
-       if (!putsbuf(p, bottom, "]")) return;
+
+       str++;
+
+       return str;
 }
 
-Datum
-pg_dump_hint(PG_FUNCTION_ARGS)
+static const char *
+skip_closed_parenthesis(const char *str)
 {
-       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++)
+       skip_space(str);
+
+       if (*str != ')')
        {
-               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;
-                       }
-               }
+               parse_ereport(str, ("Closed parenthesis is necessary."));
+               return NULL;
        }
-       if (p >= bottom) p--;
-       *p = 0;
-       
-       PG_RETURN_CSTRING(cstring_to_text(buf));
+
+       str++;
+
+       return str;
 }
 
 /*
- * pg_add_hint()で登録した個別のヒントを、使用しやすい構造に変換する。
+ * 二重引用符で囲まれているかもしれないトークンを読み取り word 引数に palloc
+ * で確保したバッファに格納してそのポインタを返す。
+ *
+ * 正常にパースできた場合は残りの文字列の先頭位置を、異常があった場合は NULL を
+ * 返す。
  */
-static JoinHint *
-set_relids(HashEntry *ent, RelIdInfo **relids, int nrels)
+static const char *
+parse_quote_value(const char *str, char **word, char *value_type)
 {
-       int                     i;
-       int                     j;
-       JoinHint   *hint;
+       StringInfoData  buf;
+       bool                    in_quote;
 
-       hint = palloc(sizeof(JoinHint));
-       hint->joinrelids = NULL;
-       hint->relidinfos = NIL;
+       /* 先頭のスペースは読み飛ばす。 */
+       skip_space(str);
+
+       initStringInfo(&buf);
+       if (*str == '"')
+       {
+               str++;
+               in_quote = true;
+       }
+       else
+               in_quote = false;
 
-       for (i = 0; i < ent->tidlist.nrels; i++)
+       while (true)
        {
-               for (j = 0; j < nrels; j++)
+               if (in_quote)
                {
-                       if (ent->tidlist.oids[i] == relids[j]->oid)
+                       /* 二重引用符が閉じられていない場合はパース中断 */
+                       if (*str == '\0')
                        {
-                               hint->relidinfos = lappend(hint->relidinfos, relids[j]);
-                               hint->joinrelids =
-                                       bms_add_member(hint->joinrelids, relids[j]->relid);
-                               break;
+                               pfree(buf.data);
+                               parse_ereport(str, ("Unterminated quoted %s.", value_type));
+                               return NULL;
                        }
-               }
 
-               if (j == nrels)
-               {
-                       list_free(hint->relidinfos);
-                       pfree(hint);
-                       return NULL;
+                       /*
+                        * エスケープ対象のダブルクウォートをスキップする。
+                        * もしブロックコメントの開始文字列や終了文字列もオブジェクト名とし
+                        * て使用したい場合は、/ と * もエスケープ対象とすることで使用できる
+                        * が、処理対象としていない。もしテーブル名にこれらの文字が含まれる
+                        * 場合は、エイリアスを指定する必要がある。
+                        */
+                       if(*str == '"')
+                       {
+                               str++;
+                               if (*str != '"')
+                                       break;
+                       }
                }
+               else
+                       if (isspace(*str) || *str == ')' || *str == '\0')
+                               break;
+
+               appendStringInfoCharMacro(&buf, *str++);
        }
 
-       hint->nrels = ent->tidlist.nrels;
-       hint->enforce_mask = ent->enforce_mask;
+       if (buf.len == 0)
+       {
+               pfree(buf.data);
+               parse_ereport(str, ("%s is necessary.", value_type));
+               return NULL;
+       }
 
-       return hint;
+       *word = buf.data;
+
+       return str;
 }
 
-/*
- * pg_add_hint()で登録したヒントから、今回のクエリで使用するもののみ抽出し、
- * 使用しやすい構造に変換する。
- */
-static void
-build_join_hints(PlannerInfo *root, int level, List *initial_rels)
+static const char *
+skip_option_delimiter(const char *str)
 {
-       int                     i;
-       int                     nrels;
-       RelIdInfo **relids;
-       JoinHint   *hint;
+       const char *p = str;
 
-       relids = palloc(sizeof(RelIdInfo *) * root->simple_rel_array_size);
+       skip_space(str);
 
-       // DEBUG  rtekind
-       if (print_log)
+       if (str == p)
        {
-               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);
+               parse_ereport(str, ("Must be specified space."));
+               return NULL;
        }
 
-       for (i = 0, nrels = 0; i < root->simple_rel_array_size; i++)
-       {
-               if (root->simple_rel_array[i] == NULL)
-                       continue;
+       return str;
+}
 
-               relids[nrels] = palloc(sizeof(RelIdInfo));
+static bool
+parse_hints(PlanHint *plan, Query *parse, const char *str)
+{
+       StringInfoData  buf;
+       char               *head;
 
-               Assert(i == root->simple_rel_array[i]->relid);
+       initStringInfo(&buf);
+       while (*str != '\0')
+       {
+               const HintParser *parser;
 
-               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);
+               /* in error message, we output the comment including the keyword. */
+               head = (char *) str;
 
-               nrels++;
-       }
+               /* parse only the keyword of the hint. */
+               resetStringInfo(&buf);
+               str = parse_keyword(str, &buf);
 
-       join_hint_level = palloc0(sizeof(List *) * (root->simple_rel_array_size));
-
-       for (i = 0; i < HASH_ENTRIES; i++)
-       {
-               HashEntry *next;
-
-               for (next = hashent[i]; next; next = next->next)
+               for (parser = parsers; parser->keyword != NULL; parser++)
                {
-                       int     lv;
-                       if (!(next->enforce_mask & ENABLE_HASHJOIN) &&
-                               !(next->enforce_mask & ENABLE_NESTLOOP) &&
-                               !(next->enforce_mask & ENABLE_MERGEJOIN))
-                               continue;
+                       char   *keyword = parser->keyword;
 
-                       if ((hint = set_relids(next, relids, nrels)) == NULL)
+                       if (strcasecmp(buf.data, keyword) != 0)
                                continue;
 
-                       lv = bms_num_members(hint->joinrelids);
-                       join_hint_level[lv] = lappend(join_hint_level[lv], hint);
+                       if (parser->have_paren)
+                       {
+                               /* parser of each hint does parse in a parenthesis. */
+                               if ((str = skip_opened_parenthesis(str)) == NULL ||
+                                       (str = parser->hint_parser(plan, parse, keyword, str)) == NULL ||
+                                       (str = skip_closed_parenthesis(str)) == NULL)
+                               {
+                                       pfree(buf.data);
+                                       return false;
+                               }
+                       }
+                       else
+                       {
+                               if ((str = parser->hint_parser(plan, parse, keyword, str)) == NULL)
+                               {
+                                       pfree(buf.data);
+                                       return false;
+                               }
+
+                               /*
+                                * 直前のヒントに括弧の指定がなければ次のヒントの間に空白が必要
+                                */
+                               if (!isspace(*str) && *str == '\0')
+                                       parse_ereport(str, ("Delimiter of the hint is necessary."));
+                       }
+
+                       skip_space(str);
+
+                       break;
                }
-       }
-}
 
-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 (parser->keyword == NULL)
+               {
+                       parse_ereport(head, ("Keyword \"%s\" does not exist.", buf.data));
+                       pfree(buf.data);
+                       return false;
+               }
+       }
 
-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;
-}
+       pfree(buf.data);
 
-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 true;
 }
 
 /*
- * relidビットマスクと一致するヒントを探す
+ * Do basic parsing of the query head comment.
  */
-static JoinHint *
-find_join_hint(Relids joinrelids)
+static PlanHint *
+parse_head_comment(Query *parse)
 {
-       List       *join_hint;
-       ListCell   *l;
+       const char         *p;
+       char               *head;
+       char               *tail;
+       int                             len;
+       int                             i;
+       PlanHint           *plan;
+
+       /* get client-supplied query string. */
+       p = debug_query_string;
+       if (p == NULL)
+               return NULL;
 
-       join_hint = join_hint_level[bms_num_members(joinrelids)];
-       foreach(l, join_hint)
+       /* extract query head comment. */
+       len = strlen(HINT_START);
+       skip_space(p);
+       if (strncmp(p, HINT_START, len))
+               return NULL;
+
+       p += len;
+       skip_space(p);
+
+       if ((tail = strstr(p, HINT_END)) == NULL)
        {
-               JoinHint   *hint = (JoinHint *) lfirst(l);
-               if (bms_equal(joinrelids, hint->joinrelids))
-                       return hint;
+               parse_ereport(debug_query_string, ("unterminated /* comment"));
+               return NULL;
        }
 
-       return NULL;
+       /* 入れ子にしたブロックコメントはサポートしない */
+       if ((head = strstr(p, HINT_START)) != NULL && head < tail)
+               parse_ereport(head, ("block comments nest doesn't supported"));
+
+       /* ヒント句部分を切り出す */
+       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. */
+       if (!parse_hints(plan, parse, p))
+               return plan;
+
+       /* 重複したScan条件をを除外する */
+       qsort(plan->scan_hints, plan->nscan_hints, sizeof(ScanHint *), ScanHintCmpIsOrder);
+       for (i = 0; i < plan->nscan_hints - 1;)
+       {
+               int     result = ScanHintCmp(plan->scan_hints + i,
+                                               plan->scan_hints + i + 1, false);
+               if (result != 0)
+                       i++;
+               else
+               {
+                       /* 後で指定したヒントを有効にする */
+                       plan->nscan_hints--;
+                       memmove(plan->scan_hints + i, plan->scan_hints + i + 1,
+                                       sizeof(ScanHint *) * (plan->nscan_hints - i));
+               }
+       }
+
+       /* 重複したJoin条件をを除外する */
+       qsort(plan->join_hints, plan->njoin_hints, sizeof(JoinHint *), JoinHintCmpIsOrder);
+       for (i = 0; i < plan->njoin_hints - 1;)
+       {
+               int     result = JoinHintCmp(plan->join_hints + i,
+                                               plan->join_hints + i + 1, false);
+               if (result != 0)
+                       i++;
+               else
+               {
+                       /* 後で指定したヒントを有効にする */
+                       plan->njoin_hints--;
+                       memmove(plan->join_hints + i, plan->join_hints + i + 1,
+                                       sizeof(JoinHint *) * (plan->njoin_hints - i));
+               }
+       }
+
+       return plan;
 }
 
 /*
- * 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 const char *
+ParseScanMethod(PlanHint *plan, Query *parse, char *keyword, const char *str)
 {
-       GucVariables    guc;
-       Relids                  joinrelids;
-       JoinHint           *hint;
-       RelOptInfo         *rel;
+       ScanHint   *hint;
 
-       joinrelids = bms_union(rel1->relids, rel2->relids);
-       hint = find_join_hint(joinrelids);
-       bms_free(joinrelids);
+       hint = ScanHintCreate();
+       hint->opt_str = str;
 
-       if (hint)
+       /*
+        * スキャン方式のヒントでリレーション名が読み取れない場合はヒント無効
+        */
+       if ((str = parse_quote_value(str, &hint->relname, "ralation name")) == NULL)
        {
-               backup_guc(&guc);
-               set_guc(hint->enforce_mask);
+               ScanHintDelete(hint);
+               return NULL;
        }
 
-       rel = make_join_rel(root, rel1, rel2);
-
-       if (hint)
-               restore_guc(&guc);
+       /*
+        * インデックスリストを受け付けるヒントであれば、インデックス参照をパース
+        * する。
+        */
+       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;
 
-       return rel;
-}
+                       str = parse_quote_value(str, &indexname, "index name");
+                       if (str == NULL)
+                       {
+                               ScanHintDelete(hint);
+                               return NULL;
+                       }
 
-/*
- * PostgreSQL 本体から流用した関数
- */
+                       hint->indexnames = lappend(hint->indexnames, indexname);
+                       skip_space(str);
+               }
+       }
 
-/*
- * 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;
+       /* カッコが閉じていなければヒント無効。 */
+       skip_space(str);
+       if (*str != ')')
+       {
+               parse_ereport(str, ("Closed parenthesis is necessary."));
+               ScanHintDelete(hint);
+               return NULL;
+       }
 
        /*
-        * 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);
+       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;
+       }
 
        /*
-        * 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 *));
+       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++;
 
-       root->join_rel_level[1] = initial_rels;
+       return str;
+}
+
+static const char *
+ParseJoinMethod(PlanHint *plan, Query *parse, char *keyword, const char *str)
+{
+       char       *relname;
+       JoinHint   *hint;
+
+       skip_space(str);
 
-       build_join_hints(root, levels_needed, initial_rels);
+       hint = JoinHintCreate();
+       hint->opt_str = str;
+       hint->relnames = palloc(sizeof(char *));
 
-       for (lev = 2; lev <= levels_needed; lev++)
+       while ((str = parse_quote_value(str, &relname, "table name")) != NULL)
        {
-               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])
-               {
-                       rel = (RelOptInfo *) lfirst(lc);
+               hint->nrels++;
+               hint->relnames = repalloc(hint->relnames, sizeof(char *) * hint->nrels);
+               hint->relnames[hint->nrels - 1] = relname;
 
-                       /* Find and save the cheapest paths for this rel */
-                       set_cheapest(rel);
+               skip_space(str);
+               if (*str == ')')
+                       break;
+       }
 
-#ifdef OPTIMIZER_DEBUG
-                       debug_print_rel(root, rel);
-#endif
-               }
+       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;
+
        /*
-        * 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);
+       list_free_deep(plan->leading);
+       plan->leading = NIL;
 
-       rel = (RelOptInfo *) linitial(root->join_rel_level[levels_needed]);
+       while ((str = parse_quote_value(str, &relname, "relation name")) != NULL)
+       {
+               const char *p;
 
-       root->join_rel_level = NULL;
+               plan->leading = lappend(plan->leading, relname);
 
-       return rel;
+               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
 /*
- * 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].
+ * Oracle の ORDERD ヒントの実装
  */
-static void
-my_join_search_one_level(PlannerInfo *root, int level)
+static const char *
+Ordered(PlanHint *plan, Query *parse, char *keyword, const char *str)
 {
-       List      **joinrels = root->join_rel_level;
-       ListCell   *r;
-       int                     k;
+       SetHint    *hint;
 
-       Assert(joinrels[level] == NIL);
+       hint = SetHintCreate();
+       hint->name = pstrdup("join_collapse_limit");
+       hint->value = pstrdup("1");
+       plan->set_hints = lappend(plan->set_hints, hint);
 
-       /* Set join_cur_level so that new joinrels are added to proper list */
-       root->join_cur_level = level;
+       return str;
+}
+#endif
+
+static PlannedStmt *
+pg_hint_plan_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
+{
+       int                             save_nestlevel;
+       PlannedStmt        *result;
 
        /*
-        * 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].
+        * hintが指定されない、または空のhintを指定された場合は通常のparser処理をお
+        * こなう。
+        * 他のフック関数で実行されるhint処理をスキップするために、global 変数をNULL
+        * に設定しておく。
         */
-       foreach(r, joinrels[level - 1])
+       if (!pg_hint_plan_enable ||
+               (global = parse_head_comment(parse)) == NULL ||
+               PlanHintIsempty(global))
        {
-               RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
-               ListCell   *other_rels;
+               PlanHintDelete(global);
+               global = NULL;
 
-               if (level == 2)
-                       other_rels = lnext(r);          /* only consider remaining initial
-                                                                                * rels */
+               if (prev_planner_hook)
+                       return (*prev_planner_hook) (parse, cursorOptions, boundParams);
                else
-                       other_rels = list_head(joinrels[1]);            /* consider all initial
-                                                                                                                * rels */
+                       return standard_planner(parse, cursorOptions, boundParams);
+       }
 
-               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
+       /* Set hint で指定されたGUCパラメータを設定する */
+       save_nestlevel = set_config_options(global->set_hints, global->context);
+
+       if (global->leading != NIL)
+               set_join_config_options(0, global->context);
+
+       /*
+        * TODO ビュー定義で指定したテーブル数が1つの場合にもこのタイミングでGUCを変更する必
+        * 要がある。
+        */
+       if (list_length(parse->rtable) == 1 &&
+               ((RangeTblEntry *) linitial(parse->rtable))->rtekind == RTE_RELATION)
+       {
+               int     i;
+               RangeTblEntry  *rte = linitial(parse->rtable);
+               
+               for (i = 0; i < global->nscan_hints; i++)
                {
-                       /*
-                        * 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);
+                       ScanHint           *hint = global->scan_hints[i];
+
+                       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);
                }
        }
 
+       if (prev_planner_hook)
+               result = (*prev_planner_hook) (parse, cursorOptions, boundParams);
+       else
+               result = standard_planner(parse, cursorOptions, boundParams);
+
        /*
-        * 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.
+        * Restore the GUC variables we set above.
         */
-       for (k = 2;; k++)
+       AtEOXact_GUC(true, save_nestlevel);
+
+       if (pg_hint_plan_debug_print)
        {
-               int                     other_level = level - k;
+               PlanHintDump(global);
+#ifdef NOT_USED
+               elog_node_display(INFO, "rtable", parse->rtable, true);
+#endif
+       }
 
-               /*
-                * 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;
+       PlanHintDelete(global);
+       global = NULL;
 
-               foreach(r, joinrels[k])
-               {
-                       RelOptInfo *old_rel = (RelOptInfo *) lfirst(r);
-                       ListCell   *other_rels;
-                       ListCell   *r2;
+       return result;
+}
 
-                       /*
-                        * 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;
+/*
+ * aliasnameと一致するSCANヒントを探す
+ */
+static ScanHint *
+find_scan_hint(RangeTblEntry *rte)
+{
+       int     i;
 
-                       if (k == other_level)
-                               other_rels = lnext(r);  /* only consider remaining rels */
-                       else
-                               other_rels = list_head(joinrels[other_level]);
+       for (i = 0; i < global->nscan_hints; i++)
+       {
+               ScanHint   *hint = global->scan_hints[i];
 
-                       for_each_cell(r2, other_rels)
-                       {
-                               RelOptInfo *new_rel = (RelOptInfo *) lfirst(r2);
+               if (RelnameCmp(&rte->eref->aliasname, &hint->relname) == 0)
+                       return hint;
+       }
 
-                               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);
-                                       }
-                               }
+       return NULL;
+}
+
+static void
+pg_hint_plan_get_relation_info(PlannerInfo *root, Oid relationObjectId,
+                                                                bool inhparent, RelOptInfo *rel)
+{
+       ScanHint   *hint;
+       ListCell   *cell;
+       ListCell   *prev;
+       ListCell   *next;
+
+       if (prev_get_relation_info)
+               (*prev_get_relation_info) (root, relationObjectId, inhparent, rel);
+
+       /* 有効なヒントが指定されなかった場合は処理をスキップする。 */
+       if (!global)
+               return;
+
+       if (rel->reloptkind != RELOPT_BASEREL)
+               return;
+
+       if ((hint = find_scan_hint(root->simple_rte_array[rel->relid])) == NULL)
+               return;
+
+       /* インデックスを全て削除し、スキャンに使えなくする */
+       if (hint->enforce_mask == ENABLE_SEQSCAN)
+       {
+               list_free_deep(rel->indexlist);
+               rel->indexlist = NIL;
+
+               return;
+       }
+
+       /* 後でパスを作り直すため、ここではなにもしない */
+       if (hint->indexnames == NULL)
+               return;
+
+       /* 指定されたインデックスのみをのこす */
+       prev = NULL;
+       for (cell = list_head(rel->indexlist); cell; cell = next)
+       {
+               IndexOptInfo   *info = (IndexOptInfo *) lfirst(cell);
+               char               *indexname = get_rel_name(info->indexoid);
+               ListCell           *l;
+               bool                    use_index = false;
+
+               next = lnext(cell);
+
+               foreach(l, hint->indexnames)
+               {
+                       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);
        }
+}
 
-       /*
-        * 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)
+static Index
+scan_relid_aliasname(PlannerInfo *root, char *aliasname, bool check_ambiguous, const char *str)
+{
+       /* TODO refnameRangeTblEntry を参考 */
+       int             i;
+       Index   find = 0;
+
+       for (i = 1; i < root->simple_rel_array_size; i++)
        {
-               /*
-                * 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 (root->simple_rel_array[i] == NULL)
+                       continue;
 
-                       if (level == 2)
-                               other_rels = lnext(r);  /* only consider remaining initial
-                                                                                * rels */
-                       else
-                               other_rels = list_head(joinrels[1]);    /* consider all initial
-                                                                                                                * rels */
+               Assert(i == root->simple_rel_array[i]->relid);
 
-                       make_rels_by_clauseless_joins(root,
-                                                                                 old_rel,
-                                                                                 other_rels);
-               }
+               if (RelnameCmp(&aliasname, &root->simple_rte_array[i]->eref->aliasname)
+                               != 0)
+                       continue;
+
+               if (!check_ambiguous)
+                       return i;
 
-               /*----------
-                * 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 (find)
+                       parse_ereport(str, ("relation name \"%s\" is ambiguous", aliasname));
+
+               find = i;
        }
+
+       return find;
 }
 
 /*
- * src/backend/optimizer/path/joinrels.c
- * static make_rels_by_clause_joins() を流用
- * 
- * 変更箇所
- *  make_join_rel() の呼び出しをラップする、my_make_join_rel()の呼び出しに変更
+ * relidビットマスクと一致するヒントを探す
  */
+static JoinHint *
+scan_join_hint(Relids joinrelids)
+{
+       List       *join_hint;
+       ListCell   *l;
+
+       join_hint = global->join_hint_level[bms_num_members(joinrelids)];
+       foreach(l, join_hint)
+       {
+               JoinHint   *hint = (JoinHint *) lfirst(l);
+               if (bms_equal(joinrelids, hint->joinrelids))
+                       return hint;
+       }
+
+       return NULL;
+}
+
 /*
- * 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)
+rebuild_join_hints(PlanHint *plan, PlannerInfo *root, int level, List *initial_rels)
 {
+       int                     i;
        ListCell   *l;
+       Relids          joinrelids;
+       int                     njoinrels;
+
+       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++)
+       {
+               JoinHint   *hint = plan->join_hints[i];
+               int                     j;
+               Index           relid = 0;
+
+               for (j = 0; j < hint->nrels; j++)
+               {
+                       char   *relname = hint->relnames[j];
+
+                       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;
+                       }
+
+                       hint->joinrelids = bms_add_member(hint->joinrelids, relid);
+               }
+
+               if (relid == 0)
+                       continue;
+
+               plan->join_hint_level[hint->nrels] =
+                       lappend(plan->join_hint_level[hint->nrels], hint);
+       }
 
-       for_each_cell(l, other_rels)
+       /* Leading hint は、全ての join 方式が有効な hint として登録する */
+       joinrelids = NULL;
+       njoinrels = 0;
+       foreach(l, plan->leading)
        {
-               RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
+               char       *relname = (char *)lfirst(l);
+               JoinHint   *hint;
+
+               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;
+               }
+
+               joinrelids = bms_add_member(joinrelids, i);
+               njoinrels++;
+
+               if (njoinrels < 2)
+                       continue;
 
-               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)))
+               if (njoinrels > plan->nlevel)
                {
-                       (void) my_make_join_rel(root, old_rel, other_rel);
+                       parse_ereport(plan->hint_str, ("In %s hint, specified relation name %d or less.", HINT_LEADING, plan->nlevel));
+                       break;
+               }
+
+               /* 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);
+
+                       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++;
                }
        }
+
+       bms_free(joinrelids);
 }
 
-/*
- * 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)
+rebuild_scan_path(PlanHint *plan, PlannerInfo *root, int level, List *initial_rels)
 {
-       ListCell   *l;
+       int     i;
+       int     save_nestlevel = 0;
 
-       for_each_cell(l, other_rels)
+       for (i = 0; i < plan->nscan_hints; i++)
        {
-               RelOptInfo *other_rel = (RelOptInfo *) lfirst(l);
+               ScanHint   *hint = plan->scan_hints[i];
+               ListCell   *l;
 
-               if (!bms_overlap(other_rel->relids, old_rel->relids))
+               if (hint->enforce_mask == ENABLE_SEQSCAN)
+                       continue;
+
+               foreach(l, initial_rels)
                {
-                       (void) my_make_join_rel(root, old_rel, other_rel);
+                       RelOptInfo         *rel = (RelOptInfo *) lfirst(l);
+                       RangeTblEntry  *rte = root->simple_rte_array[rel->relid];
+
+                       if (rel->reloptkind != RELOPT_BASEREL ||
+                               RelnameCmp(&hint->relname, &rte->eref->aliasname) != 0)
+                               continue;
+
+                       if (save_nestlevel != 0)
+                               save_nestlevel = NewGUCNestLevel();
+
+                       /*
+                        * TODO ヒントで指定されたScan方式が最安価でない場合のみ、Pathを生成
+                        * しなおす
+                        */
+                       set_scan_config_options(hint->enforce_mask, plan->context);
+
+                       rel->pathlist = NIL;    /* TODO 解放 */
+                       set_plain_rel_pathlist(root, rel, rte);
+
+                       break;
                }
        }
+
+       /*
+        * Restore the GUC variables we set above.
+        */
+       if (save_nestlevel != 0)
+               AtEOXact_GUC(true, save_nestlevel);
 }
 
 /*
  * src/backend/optimizer/path/joinrels.c
- * static has_join_restriction() を流用
+ * export make_join_rel() をラップする関数
  * 
- * 変更箇所
- *  なし
- */
-/*
- * 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.)
+ * ヒントにしたがって、enabele_* パラメータを変更した上で、make_join_rel()を
+ * 呼び出す。
  */
-static bool
-has_join_restriction(PlannerInfo *root, RelOptInfo *rel)
+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;
 
-       foreach(l, root->join_info_list)
-       {
-               SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l);
+       joinrelids = bms_union(rel1->relids, rel2->relids);
+       hint = scan_join_hint(joinrelids);
+       bms_free(joinrelids);
 
-               /* ignore full joins --- other mechanisms preserve their ordering */
-               if (sjinfo->jointype == JOIN_FULL)
-                       continue;
+       if (!hint)
+               return make_join_rel(root, rel1, rel2);
 
-               /* 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;
+       save_nestlevel = NewGUCNestLevel();
+
+       set_join_config_options(hint->enforce_mask, global->context);
+
+       rel = make_join_rel(root, rel1, rel2);
+
+       /*
+        * Restore the GUC variables we set above.
+        */
+       AtEOXact_GUC(true, save_nestlevel);
+
+       return rel;
+}
 
-               /* 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;
+static RelOptInfo *
+pg_hint_plan_join_search(PlannerInfo *root, int levels_needed, List *initial_rels)
+{
+       /*
+        * 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);
        }
 
-       return false;
+       rebuild_join_hints(global, root, levels_needed, initial_rels);
+       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);
+
+       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"