summaryrefslogtreecommitdiff
path: root/storage/oqgraph/ha_oqgraph.cc
blob: cb57b4711d4c8cfedbb543c3b7f81facf34480c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
/* Copyright (C) 2007-2009 Arjen G Lentz & Antony T Curtis for Open Query
   Portions of this file copyright (C) 2000-2006 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* ======================================================================
   Open Query Graph Computation Engine, based on a concept by Arjen Lentz
   Mk.II implementation by Antony Curtis & Arjen Lentz
   For more information, documentation, support, enhancement engineering,
   and non-GPL licensing, see http://openquery.com/graph
   or contact graph@openquery.com
   For packaged binaries, see http://ourdelta.org
   ======================================================================
*/

#include <mysql_version.h>
#include "ha_oqgraph.h"
#include "graphcore.h"

#define MYSQL_SERVER	// to have THD
#include <mysql/plugin.h>
#include "table.h"
#include "field.h"
#include "key.h"

#define OQGRAPH_STATS_UPDATE_THRESHOLD 10

using namespace open_query;


struct oqgraph_info_st
{
  THR_LOCK lock;
  oqgraph_share *graph;
  uint use_count;
  uint key_stat_version;
  uint records;
  bool dropped;
  char name[FN_REFLEN+1];
};

static const char oqgraph_description[]=
  "Open Query Graph Computation Engine, stored in memory "
  "(http://openquery.com/graph)";

static HASH oqgraph_open_tables;
static mysql_mutex_t LOCK_oqgraph;
static bool oqgraph_init_done= 0;

#define HASH_KEY_LENGTH size_t

static uchar* get_key(const uchar *ptr, HASH_KEY_LENGTH *length,
                      my_bool)
{
  const OQGRAPH_INFO *share= (const OQGRAPH_INFO*) ptr;
  *length= strlen(share->name);
  return (uchar*) share->name;
}

#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key key_LOCK_oqgraph;
static PSI_mutex_info all_mutexes[]=
{
  { &key_LOCK_oqgraph, "LOCK_oqgraph", PSI_FLAG_GLOBAL},
};

static void init_psi_keys()
{
  mysql_mutex_register("oqgraph", all_mutexes, array_elements(all_mutexes));
}
#else
#define init_psi_keys() /* no-op */
#endif /* HAVE_PSI_INTERFACE */


static handler* oqgraph_create_handler(handlerton *hton, TABLE_SHARE *table,
                                       MEM_ROOT *mem_root)
{
  return new (mem_root) ha_oqgraph(hton, table);
}

static int oqgraph_init(handlerton *hton)
{
  init_psi_keys();
  if (mysql_mutex_init(key_LOCK_oqgraph, &LOCK_oqgraph, MY_MUTEX_INIT_FAST))
    goto error;
  if (my_hash_init(&oqgraph_open_tables, &my_charset_bin, 32, 0, 0,
                get_key, 0, 0))
  {
    mysql_mutex_destroy(&LOCK_oqgraph);
    goto error;
  }
  hton->state= SHOW_OPTION_YES;
  hton->db_type= DB_TYPE_AUTOASSIGN;
  hton->create= oqgraph_create_handler;
  hton->flags= HTON_NO_FLAGS;
  oqgraph_init_done= TRUE;
  return 0;
error:
  return 1;
}

static int oqgraph_fini(void *)
{
  my_hash_free(&oqgraph_open_tables);
  mysql_mutex_destroy(&LOCK_oqgraph);
  oqgraph_init_done= FALSE;
  return 0;
}

static OQGRAPH_INFO *get_share(const char *name, TABLE *table=0)
{
  OQGRAPH_INFO *share;
  uint length= strlen(name);

  mysql_mutex_assert_owner(&LOCK_oqgraph);
  if (!(share= (OQGRAPH_INFO*) my_hash_search(&oqgraph_open_tables,
                                           (byte*) name, length)))
  {
    if (!table ||
        !(share= new OQGRAPH_INFO))
      return 0;
    share->use_count= share->key_stat_version= share->records= 0;
    share->dropped= 0;
    strmov(share->name, name);
    if (!(share->graph= oqgraph::create()))
    {
      delete share;
      return 0;
    }
    if (my_hash_insert(&oqgraph_open_tables, (byte*) share))
    {
      oqgraph::free(share->graph);
      delete share;
      return 0;
    }
    thr_lock_init(&share->lock);
  }
  share->use_count++;
  return share;
}

static int free_share(OQGRAPH_INFO *share, bool drop=0)
{
  mysql_mutex_assert_owner(&LOCK_oqgraph);
  if (!share)
    return 0;
  if (drop)
  {
    share->dropped= true;
    my_hash_delete(&oqgraph_open_tables, (byte*) share);
  }
  if (!--share->use_count)
  {
    if (share->dropped)
    {
      thr_lock_delete(&share->lock);
      oqgraph::free(share->graph);
      delete share;
    }
  }
  return 0;
}

static int error_code(int res)
{
  switch (res)
  {
  case oqgraph::OK:
    return 0;
  case oqgraph::NO_MORE_DATA:
    return HA_ERR_END_OF_FILE;
  case oqgraph::EDGE_NOT_FOUND:
    return HA_ERR_KEY_NOT_FOUND;
  case oqgraph::INVALID_WEIGHT:
    return HA_ERR_AUTOINC_ERANGE;
  case oqgraph::DUPLICATE_EDGE:
    return HA_ERR_FOUND_DUPP_KEY;
  case oqgraph::CANNOT_ADD_VERTEX:
  case oqgraph::CANNOT_ADD_EDGE:
    return HA_ERR_RECORD_FILE_FULL;
  case oqgraph::MISC_FAIL:
  default:
    return HA_ERR_CRASHED_ON_USAGE;
  }
}

/**
 * Check if table complies with our designated structure
 *
 *    ColName    Type      Attributes
 *    =======    ========  =============
 *    latch     SMALLINT  UNSIGNED NULL
 *    origid    BIGINT    UNSIGNED NULL
 *    destid    BIGINT    UNSIGNED NULL
 *    weight    DOUBLE    NULL
 *    seq       BIGINT    UNSIGNED NULL
 *    linkid    BIGINT    UNSIGNED NULL
 *    =================================
 *
  CREATE TABLE foo (
    latch   SMALLINT  UNSIGNED NULL,
    origid  BIGINT    UNSIGNED NULL,
    destid  BIGINT    UNSIGNED NULL,
    weight  DOUBLE    NULL,
    seq     BIGINT    UNSIGNED NULL,
    linkid  BIGINT    UNSIGNED NULL,
    KEY (latch, origid, destid) USING HASH,
    KEY (latch, destid, origid) USING HASH
  ) ENGINE=OQGRAPH

 */
static int oqgraph_check_table_structure (TABLE *table_arg)
{
  int i;
  struct { const char *colname; int coltype; } skel[] = {
    { "latch" , MYSQL_TYPE_SHORT },
    { "origid", MYSQL_TYPE_LONGLONG },
    { "destid", MYSQL_TYPE_LONGLONG },
    { "weight", MYSQL_TYPE_DOUBLE },
    { "seq"   , MYSQL_TYPE_LONGLONG },
    { "linkid", MYSQL_TYPE_LONGLONG },
  { NULL    , 0}
  };

  DBUG_ENTER("ha_oqgraph::table_structure_ok");

  Field **field= table_arg->field;
  for (i= 0; *field && skel[i].colname; i++, field++) {
    /* Check Column Type */
    if ((*field)->type() != skel[i].coltype)
      DBUG_RETURN(-1);
    if (skel[i].coltype != MYSQL_TYPE_DOUBLE) {
      /* Check Is UNSIGNED */
      if (!((*field)->flags & UNSIGNED_FLAG ))
        DBUG_RETURN(-1);
    }
    /* Check THAT  NOT NULL isn't set */
    if ((*field)->flags & NOT_NULL_FLAG)
      DBUG_RETURN(-1);
    /* Check the column name */
    if (strcmp(skel[i].colname,(*field)->field_name))
      DBUG_RETURN(-1);
  }

  if (skel[i].colname || *field || !table_arg->key_info || !table_arg->s->keys)
    DBUG_RETURN(-1);

  KEY *key= table_arg->key_info;
  for (uint i= 0; i < table_arg->s->keys; ++i, ++key)
  {
    Field **field= table_arg->field;
    /* check that the first key part is the latch and it is a hash key */
    if (!(field[0] == key->key_part[0].field &&
          HA_KEY_ALG_HASH == key->algorithm))
      DBUG_RETURN(-1);
    if (key->user_defined_key_parts == 3)
    {
      /* KEY (latch, origid, destid) USING HASH */
      /* KEY (latch, destid, origid) USING HASH */
      if (!(field[1] == key->key_part[1].field &&
            field[2] == key->key_part[2].field) &&
          !(field[1] == key->key_part[2].field &&
            field[2] == key->key_part[1].field))
        DBUG_RETURN(-1);
    }
    else
      DBUG_RETURN(-1);
  }

  DBUG_RETURN(0);
}

/*****************************************************************************
** OQGRAPH tables
*****************************************************************************/

ha_oqgraph::ha_oqgraph(handlerton *hton, TABLE_SHARE *table_arg)
  : handler(hton, table_arg),
    share(0), graph(0), records_changed(0), key_stat_version(0)
{ }


static const char *ha_oqgraph_exts[] =
{
  NullS
};

const char **ha_oqgraph::bas_ext() const
{
  return ha_oqgraph_exts;
}

ulonglong ha_oqgraph::table_flags() const
{
  return (HA_NO_BLOBS | HA_NULL_IN_KEY |
          HA_REC_NOT_IN_SEQ | HA_CAN_INSERT_DELAYED |
          HA_BINLOG_STMT_CAPABLE | HA_BINLOG_ROW_CAPABLE);
}

ulong ha_oqgraph::index_flags(uint inx, uint part, bool all_parts) const
{
  return HA_ONLY_WHOLE_INDEX | HA_KEY_SCAN_NOT_ROR;
}

int ha_oqgraph::open(const char *name, int mode, uint test_if_locked)
{
  mysql_mutex_lock(&LOCK_oqgraph);
  if ((share = get_share(name, table)))
  {
    ref_length= oqgraph::sizeof_ref;
  }

  if (share)
  {
    /* Initialize variables for the opened table */
    thr_lock_data_init(&share->lock, &lock, NULL);

    graph= oqgraph::create(share->graph);

    /*
      We cannot run update_key_stats() here because we do not have a
      lock on the table. The 'records' count might just be changed
      temporarily at this moment and we might get wrong statistics (Bug
      #10178). Instead we request for update. This will be done in
      ha_oqgraph::info(), which is always called before key statistics are
      used.
    */
    key_stat_version= share->key_stat_version-1;
  }
  mysql_mutex_unlock(&LOCK_oqgraph);

  return (share ? 0 : 1);
}

int ha_oqgraph::close(void)
{
  mysql_mutex_lock(&LOCK_oqgraph);
  oqgraph::free(graph); graph= 0;
  int res= free_share(share);
  mysql_mutex_unlock(&LOCK_oqgraph);
  return error_code(res);
}

void ha_oqgraph::update_key_stats()
{
  for (uint i= 0; i < table->s->keys; i++)
  {
    KEY *key=table->key_info+i;
    if (!key->rec_per_key)
      continue;
    if (key->algorithm != HA_KEY_ALG_BTREE)
    {
      if (key->flags & HA_NOSAME)
        key->rec_per_key[key->user_defined_key_parts-1]= 1;
      else
      {
        unsigned vertices= graph->vertices_count();
        unsigned edges= graph->edges_count();
        uint no_records= vertices ? 2 * (edges + vertices) / vertices : 2;
        if (no_records < 2)
          no_records= 2;
        key->rec_per_key[key->user_defined_key_parts-1]= no_records;
      }
    }
  }
  records_changed= 0;
  /* At the end of update_key_stats() we can proudly claim they are OK. */
  key_stat_version= share->key_stat_version;
}


int ha_oqgraph::write_row(byte * buf)
{
  int res= oqgraph::MISC_FAIL;
  Field ** const field= table->field;

  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
  my_ptrdiff_t ptrdiff= buf - table->record[0];

  if (ptrdiff)
  {
    field[1]->move_field_offset(ptrdiff);
    field[2]->move_field_offset(ptrdiff);
    field[3]->move_field_offset(ptrdiff);
  }

  if (!field[1]->is_null() && !field[2]->is_null())
  {
    VertexID orig_id= (VertexID) field[1]->val_int();
    VertexID dest_id= (VertexID) field[2]->val_int();
    EdgeWeight weight= 1;

    if (!field[3]->is_null())
      weight= (EdgeWeight) field[3]->val_real();

    if (!(res= graph->insert_edge(orig_id, dest_id, weight, replace_dups)))
    {
      ++records_changed;
      share->records++;
    }
    if (res == oqgraph::DUPLICATE_EDGE && ignore_dups && !insert_dups)
      res= oqgraph::OK;
  }

  if (ptrdiff)
  {
    field[1]->move_field_offset(-ptrdiff);
    field[2]->move_field_offset(-ptrdiff);
    field[3]->move_field_offset(-ptrdiff);
  }
  dbug_tmp_restore_column_map(table->read_set, old_map);

  if (!res && records_changed*OQGRAPH_STATS_UPDATE_THRESHOLD > share->records)
  {
    /*
       We can perform this safely since only one writer at the time is
       allowed on the table.
    */
    share->key_stat_version++;
  }

  return error_code(res);
}

int ha_oqgraph::update_row(const byte * old, byte * buf)
{
  int res= oqgraph::MISC_FAIL;
  VertexID orig_id, dest_id;
  EdgeWeight weight= 1;
  Field **field= table->field;

  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
  my_ptrdiff_t ptrdiff= buf - table->record[0];

  if (ptrdiff)
  {
    field[0]->move_field_offset(ptrdiff);
    field[1]->move_field_offset(ptrdiff);
    field[2]->move_field_offset(ptrdiff);
    field[3]->move_field_offset(ptrdiff);
  }

  if (inited == INDEX || inited == RND)
  {
    VertexID *origp= 0, *destp= 0;
    EdgeWeight *weightp= 0;
    if (!field[1]->is_null())
      *(origp= &orig_id)= (VertexID) field[1]->val_int();
    if (!field[2]->is_null())
      *(destp= &dest_id)= (VertexID) field[2]->val_int();
    if (!field[3]->is_null())
      *(weightp= &weight)= (EdgeWeight) field[3]->val_real();

    my_ptrdiff_t ptrdiff2= old - buf;

    field[0]->move_field_offset(ptrdiff2);
    field[1]->move_field_offset(ptrdiff2);
    field[2]->move_field_offset(ptrdiff2);
    field[3]->move_field_offset(ptrdiff2);

    if (field[0]->is_null())
    {
      if (!origp == field[1]->is_null() &&
          *origp == (VertexID) field[1]->val_int())
        origp= 0;
      if (!destp == field[2]->is_null() &&
          *destp == (VertexID) field[2]->val_int())
        origp= 0;
      if (!weightp == field[3]->is_null() &&
          *weightp == (VertexID) field[3]->val_real())
        weightp= 0;

      if (!(res= graph->modify_edge(oqgraph::current_row(),
                                    origp, destp, weightp, replace_dups)))
        ++records_changed;
      else if (ignore_dups && res == oqgraph::DUPLICATE_EDGE)
        res= oqgraph::OK;
    }

    field[0]->move_field_offset(-ptrdiff2);
    field[1]->move_field_offset(-ptrdiff2);
    field[2]->move_field_offset(-ptrdiff2);
    field[3]->move_field_offset(-ptrdiff2);
  }

  if (ptrdiff)
  {
    field[0]->move_field_offset(-ptrdiff);
    field[1]->move_field_offset(-ptrdiff);
    field[2]->move_field_offset(-ptrdiff);
    field[3]->move_field_offset(-ptrdiff);
  }
  dbug_tmp_restore_column_map(table->read_set, old_map);

  if (!res && records_changed*OQGRAPH_STATS_UPDATE_THRESHOLD > share->records)
  {
    /*
       We can perform this safely since only one writer at the time is
       allowed on the table.
    */
    share->key_stat_version++;
  }
  return error_code(res);
}

int ha_oqgraph::delete_row(const byte * buf)
{
  int res= oqgraph::EDGE_NOT_FOUND;
  Field **field= table->field;

  if (inited == INDEX || inited == RND)
  {
    if ((res= graph->delete_edge(oqgraph::current_row())) == oqgraph::OK)
    {
      ++records_changed;
      share->records--;
    }
  }
  if (res != oqgraph::OK)
  {
    my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
    my_ptrdiff_t ptrdiff= buf - table->record[0];

    if (ptrdiff)
    {
      field[0]->move_field_offset(ptrdiff);
      field[1]->move_field_offset(ptrdiff);
      field[2]->move_field_offset(ptrdiff);
    }

    if (field[0]->is_null() && !field[1]->is_null() && !field[2]->is_null())
    {
      VertexID orig_id= (VertexID) field[1]->val_int();
      VertexID dest_id= (VertexID) field[2]->val_int();

      if ((res= graph->delete_edge(orig_id, dest_id)) == oqgraph::OK)
      {
        ++records_changed;
        share->records--;
      }
    }

    if (ptrdiff)
    {
      field[0]->move_field_offset(-ptrdiff);
      field[1]->move_field_offset(-ptrdiff);
      field[2]->move_field_offset(-ptrdiff);
    }
    dbug_tmp_restore_column_map(table->read_set, old_map);
  }

  if (!res && table->s->tmp_table == NO_TMP_TABLE &&
      records_changed*OQGRAPH_STATS_UPDATE_THRESHOLD > share->records)
  {
    /*
       We can perform this safely since only one writer at the time is
       allowed on the table.
    */
    share->key_stat_version++;
  }
  return error_code(res);
}

int ha_oqgraph::index_read(byte * buf, const byte * key, uint key_len,
			enum ha_rkey_function find_flag)
{
  DBUG_ASSERT(inited==INDEX);
  return index_read_idx(buf, active_index, key, key_len, find_flag);
}

int ha_oqgraph::index_next_same(byte *buf, const byte *key, uint key_len)
{
  int res;
  open_query::row row;
  DBUG_ASSERT(inited==INDEX);
  if (!(res= graph->fetch_row(row)))
    res= fill_record(buf, row);
  table->status= res ? STATUS_NOT_FOUND : 0;
  return error_code(res);
}

int ha_oqgraph::index_read_idx(byte * buf, uint index, const byte * key,
			    uint key_len, enum ha_rkey_function find_flag)
{
  Field **field= table->field;
  KEY *key_info= table->key_info + index;
  int res;
  VertexID orig_id, dest_id;
  int latch;
  VertexID *orig_idp=0, *dest_idp=0;
  int *latchp=0;
  open_query::row row;

  bmove_align(buf, table->s->default_values, table->s->reclength);
  key_restore(buf, (byte*) key, key_info, key_len);

  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->read_set);
  my_ptrdiff_t ptrdiff= buf - table->record[0];

  if (ptrdiff)
  {
    field[0]->move_field_offset(ptrdiff);
    field[1]->move_field_offset(ptrdiff);
    field[2]->move_field_offset(ptrdiff);
  }

  if (!field[0]->is_null())
  {
    latch= (int) field[0]->val_int();
    latchp= &latch;
  }

  if (!field[1]->is_null())
  {
    orig_id= (VertexID) field[1]->val_int();
    orig_idp= &orig_id;
  }

  if (!field[2]->is_null())
  {
    dest_id= (VertexID) field[2]->val_int();
    dest_idp= &dest_id;
  }

  if (ptrdiff)
  {
    field[0]->move_field_offset(-ptrdiff);
    field[1]->move_field_offset(-ptrdiff);
    field[2]->move_field_offset(-ptrdiff);
  }
  dbug_tmp_restore_column_map(table->read_set, old_map);

  res= graph->search(latchp, orig_idp, dest_idp);

  if (!res && !(res= graph->fetch_row(row)))
    res= fill_record(buf, row);
  table->status = res ? STATUS_NOT_FOUND : 0;
  return error_code(res);
}

int ha_oqgraph::fill_record(byte *record, const open_query::row &row)
{
  Field **field= table->field;

  bmove_align(record, table->s->default_values, table->s->reclength);

  my_bitmap_map *old_map= dbug_tmp_use_all_columns(table, table->write_set);
  my_ptrdiff_t ptrdiff= record - table->record[0];

  if (ptrdiff)
  {
    field[0]->move_field_offset(ptrdiff);
    field[1]->move_field_offset(ptrdiff);
    field[2]->move_field_offset(ptrdiff);
    field[3]->move_field_offset(ptrdiff);
    field[4]->move_field_offset(ptrdiff);
    field[5]->move_field_offset(ptrdiff);
  }

  // just each field specifically, no sense iterating
  if (row.latch_indicator)
  {
    field[0]->set_notnull();
    field[0]->store((longlong) row.latch, 0);
  }

  if (row.orig_indicator)
  {
    field[1]->set_notnull();
    field[1]->store((longlong) row.orig, 0);
  }

  if (row.dest_indicator)
  {
    field[2]->set_notnull();
    field[2]->store((longlong) row.dest, 0);
  }

  if (row.weight_indicator)
  {
    field[3]->set_notnull();
    field[3]->store((double) row.weight);
  }

  if (row.seq_indicator)
  {
    field[4]->set_notnull();
    field[4]->store((longlong) row.seq, 0);
  }

  if (row.link_indicator)
  {
    field[5]->set_notnull();
    field[5]->store((longlong) row.link, 0);
  }

  if (ptrdiff)
  {
    field[0]->move_field_offset(-ptrdiff);
    field[1]->move_field_offset(-ptrdiff);
    field[2]->move_field_offset(-ptrdiff);
    field[3]->move_field_offset(-ptrdiff);
    field[4]->move_field_offset(-ptrdiff);
    field[5]->move_field_offset(-ptrdiff);
  }
  dbug_tmp_restore_column_map(table->write_set, old_map);

  return 0;
}

int ha_oqgraph::rnd_init(bool scan)
{
  return error_code(graph->random(scan));
}

int ha_oqgraph::rnd_next(byte *buf)
{
  int res;
  open_query::row row;
  if (!(res= graph->fetch_row(row)))
    res= fill_record(buf, row);
  table->status= res ? STATUS_NOT_FOUND: 0;
  return error_code(res);
}

int ha_oqgraph::rnd_pos(byte * buf, byte *pos)
{
  int res;
  open_query::row row;
  if (!(res= graph->fetch_row(row, pos)))
    res= fill_record(buf, row);
  table->status=res ? STATUS_NOT_FOUND: 0;
  return error_code(res);
}

void ha_oqgraph::position(const byte *record)
{
  graph->row_ref((void*) ref);	// Ref is aligned
}

int ha_oqgraph::cmp_ref(const byte *ref1, const byte *ref2)
{
  return memcmp(ref1, ref2, oqgraph::sizeof_ref);
}

int ha_oqgraph::info(uint flag)
{
  stats.records= graph->vertices_count() + graph->edges_count();
  /*
    If info() is called for the first time after open(), we will still
    have to update the key statistics. Hoping that a table lock is now
    in place.
  */
  if (key_stat_version != share->key_stat_version)
    update_key_stats();
  return 0;
}

int ha_oqgraph::extra(enum ha_extra_function operation)
{
  switch (operation)
  {
  case HA_EXTRA_IGNORE_DUP_KEY:
    ignore_dups= true;
    break;
  case HA_EXTRA_NO_IGNORE_DUP_KEY:
    ignore_dups= false;
    insert_dups= false;
    break;
  case HA_EXTRA_WRITE_CAN_REPLACE:
    replace_dups= true;
    break;
  case HA_EXTRA_WRITE_CANNOT_REPLACE:
    replace_dups= false;
    break;
  case HA_EXTRA_INSERT_WITH_UPDATE:
    insert_dups= true;
    break;
  default:
    break;
  }
  return 0;
}

int ha_oqgraph::delete_all_rows()
{
  int res;
  if (!(res= graph->delete_all()))
  {
    share->records= 0;
  }

  if (!res && table->s->tmp_table == NO_TMP_TABLE)
  {
    /*
       We can perform this safely since only one writer at the time is
       allowed on the table.
    */
    share->key_stat_version++;
  }
  return error_code(res);
}

int ha_oqgraph::external_lock(THD *thd, int lock_type)
{
  return 0;					// No external locking
}


THR_LOCK_DATA **ha_oqgraph::store_lock(THD *thd,
				       THR_LOCK_DATA **to,
				       enum thr_lock_type lock_type)
{
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
    lock.type=lock_type;
  *to++= &lock;
  return to;
}

/*
  We have to ignore ENOENT entries as the HEAP table is created on open and
  not when doing a CREATE on the table.
*/

int ha_oqgraph::delete_table(const char *name)
{
  int res= 0;
  OQGRAPH_INFO *share;
  mysql_mutex_lock(&LOCK_oqgraph);
  if ((share= get_share(name)))
  {
    res= free_share(share, true);
  }
  mysql_mutex_unlock(&LOCK_oqgraph);
  return error_code(res);
}

int ha_oqgraph::rename_table(const char * from, const char * to)
{
  mysql_mutex_lock(&LOCK_oqgraph);
  if (OQGRAPH_INFO *share= get_share(from))
  {
    strmov(share->name, to);
    my_hash_update(&oqgraph_open_tables, (byte*) share,
                (byte*) from, strlen(from));
  }
  mysql_mutex_unlock(&LOCK_oqgraph);
  return 0;
}


ha_rows ha_oqgraph::records_in_range(uint inx, key_range *min_key,
                                  key_range *max_key)
{
  KEY *key=table->key_info+inx;

  if (!min_key || !max_key ||
      min_key->length != max_key->length ||
      min_key->length < key->key_length - key->key_part[2].store_length ||
      min_key->flag != HA_READ_KEY_EXACT ||
      max_key->flag != HA_READ_AFTER_KEY)
  {
    if (min_key->length == key->key_part[0].store_length)
    {
      // If latch is not null and equals 0, return # nodes
      DBUG_ASSERT(key->key_part[0].store_length == 3);
      if (key->key_part[0].null_bit && !min_key->key[0] &&
          !min_key->key[1] && !min_key->key[2])
        return graph->vertices_count();
    }
    return HA_POS_ERROR;			// Can only use exact keys
  }

  if (stats.records <= 1)
    return stats.records;

  /* Assert that info() did run. We need current statistics here. */
  DBUG_ASSERT(key_stat_version == share->key_stat_version);
  ha_rows result= key->rec_per_key[key->user_defined_key_parts-1];

  return result;
}


int ha_oqgraph::create(const char *name, TABLE *table_arg,
		    HA_CREATE_INFO *create_info)
{
  int res = -1;
  OQGRAPH_INFO *share;

  mysql_mutex_lock(&LOCK_oqgraph);
  if ((share= get_share(name)))
  {
    free_share(share);
  }
  else
  {
    if (!oqgraph_check_table_structure(table_arg))
      res= 0;;
  }
  mysql_mutex_unlock(&LOCK_oqgraph);

  if (this->share)
    info(HA_STATUS_NO_LOCK | HA_STATUS_CONST | HA_STATUS_VARIABLE);
  return error_code(res);
}


void ha_oqgraph::update_create_info(HA_CREATE_INFO *create_info)
{
  table->file->info(HA_STATUS_AUTO);
}

struct st_mysql_storage_engine oqgraph_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION };

maria_declare_plugin(oqgraph)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &oqgraph_storage_engine,
  "OQGRAPH",
  "Arjen Lentz & Antony T Curtis, Open Query",
  oqgraph_description,
  PLUGIN_LICENSE_GPL,
  (int (*)(void*)) oqgraph_init, /* Plugin Init                  */
  oqgraph_fini,               /* Plugin Deinit                   */
  0x0200,                     /* Version: 2.0                    */
  NULL,                       /* status variables                */
  NULL,                       /* system variables                */
  "2.0",
  MariaDB_PLUGIN_MATURITY_BETA
}
maria_declare_plugin_end;