SlideShare a Scribd company logo
1 of 42
Download to read offline
<Insert Picture Here>




An API for Reading the MySQL Binary Log
Mats Kindahl                   Lars Thalmann
Lead Software Engineer, MySQL Development Director, MySQL
Replication & Utilities       Replication, Backup & Connectors
The following is intended to outline our general
product direction. It is intended for information
purposes only, and may not be incorporated into any
contract. It is not a commitment to deliver any
material, code, or functionality, and should not be
relied upon in making purchasing decisions.
The development, release, and timing of any
features or functionality described for Oracle’s
products remains at the sole discretion of Oracle.




                                                      3
Outline

•Replication Architecture
•Binary logs
•Binary log event
•Reading binary log
  – Connecting to server
  – Reading from files
•Reading events
  – Queries
  – Reading rows (row-based replication)
  – Other events


                                           4
Replication Architecture
             Master              Slave(s)
Clients




                       Changes




                                            5
Replication Architecture
          Master           Slave(s)

Session
                                Databa
                                 Databa
                                  Databa
                                  se
Session
 Client        Dump
                Dump               se
                 Dump                se
Session
                        I/O     SQL
                         I/O     SQL
                          I/O     SQL




      Binary Log




                                           6
Replication Architecture
          Master           Slave(s)

Session
                                  Databa
                                 Database
                                   Databa
Session
 Client        Dump
                Dump                se
                 Dump                 se
Session
                        I/O       SQL
                         I/O       SQL
                          I/O       SQL




      Binary Log          Relay Log




                                            7
Replication to other systems       Slave(s)


                                         Database

          Master
                               I/O        SQL


Session
                                 Relay Log

Session
 Client        Dump
                Dump
                 Dump
                  Dump
                                                Data
Session                      HBase              Mining



                                                Full-text
                              SOLR              indexing

      Binary Log
                         ?



                                                      8
Transforming events
              Subject of our presentation
Se
   rv
    r e




            API
                  Transformer      SOLR
     le
   Fi




          “Change Data Capture”



                                            9
Binlog API

•Library to process replication events
•API is ready for use
•Goals:
 – Simple
 – Extensible
 – Efficient



                                         10
<Insert Picture Here>



                                       Binlog API
                        ●
                          The replication listener

                         How to capture events




                                                     11
First example
#include <cstdlib>
#include <iostream>
#include <binlog_api.h>                                <Insert Picture Here>

int main(int argc, char *argv[]) {
  const char *url = “mysql://root@127.0.0.1:3360”;
  Binary_log binlog(create_transport(url));
  binlog.connect();
  Binary_log_event *event;
  while (true) {
    int result = binlog.wait_for_next_event(&event);
    if (result == ERR_EOF)
      break;
    cout << “ at “ << binlog.get_position()
         << “ event type “ << event.get_type_code()
         << endl;
  }
  return EXIT_SUCCESS;
}




                                                                         12
Create network transport
#include <cstdlib>
#include <iostream>
#include <binlog_api.h>                                <Insert Picture Here>

int main(int argc, char *argv[]) {
  const char *url = “mysql://root@127.0.0.1:3360”;
  Binary_log binlog(create_transport(url));
  binlog.connect();
  Binary_log_event *event;
  while (true) {
    int result = binlog.wait_for_next_event(&event);
    if (result == ERR_EOF)
      break;
    cout << “ at “ << binlog.get_position()
         << “ event type “ << event.get_type_code()
         << endl;
  }
  return EXIT_SUCCESS;
}




                                                                         13
… or file transport
#include <cstdlib>
#include <iostream>
#include <binlog_api.h>                                <Insert Picture Here>

int main(int argc, char *argv[]) {
  const char *url = “file:///tmp/binlog.0000001”;
  Binary_log binlog(create_transport(url));
  binlog.connect();
  Binary_log_event *event;
  while (true) {
    int result = binlog.wait_for_next_event(&event);
    if (result == ERR_EOF)
      break;
    cout << “ at “ << binlog.get_position()
         << “ event type “ << event.get_type_code()
         << endl;
  }
  return EXIT_SUCCESS;
}




                                                                         14
Connect the transport
#include <cstdlib>
#include <iostream>
#include <binlog_api.h>                                <Insert Picture Here>

int main(int argc, char *argv[]) {
  const char *url = “file:///tmp/binlog.0000001”;
  Binary_log binlog(create_transport(url));
  binlog.connect();
  Binary_log_event *event;
  while (true) {
    int result = binlog.wait_for_next_event(&event);
    if (result == ERR_EOF)
      break;
    cout << “ at “ << binlog.get_position()
         << “ event type “ << event.get_type_code()
         << endl;
  }
  return EXIT_SUCCESS;
}




                                                                         15
Digression: set read position

   •Default: start at beginning       <Insert Picture Here>



   •Set position explicitly:
if (binlog.set_position(file, pos))
{
  /* Handle error */
}




                                                        16
Read events
#include <cstdlib>
#include <iostream>
#include <binlog_api.h>                                <Insert Picture Here>

int main(int argc, char *argv[]) {   Get event
  const char *url = “file:///tmp/binlog.0000001”;
  Binary_log binlog(create_transport(url));
  binlog.connect();
  Binary_log_event *event;
  while (true) {
    int result = binlog.wait_for_next_event(&event);
    if (result == ERR_EOF)
      break;
    cout << “ at “ << binlog.get_position()
         << “ event type “ << event­>get_type_code()
         << endl;
  }
  return EXIT_SUCCESS;
}




                                                                         17
Steps summary

•Create a transport
  – create_transport
•Connect to server
  – connect
•Set position
  – set_position
•Start event loop
  – wait_for_next_event




                          18
<Insert Picture Here>



                                             Binlog API
                              ●
                                The replication listener

                        Reading information in events




                                                           19
Binlog Event Structure

                    • Common header
   Common Header      • Generic data
                      • Fixed size
                    • Post-header
    Post-header
                      • Event-specific data
                      • Fixed size
                    • Variable part
                      • Event-specific data
    Variable Part
                      • Variable size




                                              20
Reading the header

•Read common header                     <Insert Picture Here>


  – header()
•Access fields
switch (event­>header()­>type_code) {
case QUERY_EVENT:
  …
case USER_VAR_EVENT:
  …
case FORMAT_DESCRIPTION_EVENT:
  …
}




                                                          21
Binlog Event Common Header
              type_code
timestamp             server_id    • Data common to all events
                                   • Next Position
   4 bytes                           – One-after-end of event
                                   • Timestamp
                                     – Statement start time
                                   • Flags
                                     –   Binlog-in-use
                   next_position     –   Thread-specific
                                     –   Suppress “use”
             event_length
                                     –   Artificial
 flags
             19 Bytes                –   Relay-log event




                                                                 22
Binlog Event Structure

                    • Common header
   Common Header      • Generic data
                      • Fixed size
                    • Post-header
    Post-header
                      • Event-specific data
                      • Fixed size
                    • Variable part
                      • Event-specific data
    Variable Part
                      • Variable size




                                              23
Query Event
thread_id        exec_time   •Most common event
      Common Header
                             •Used for statements
                             •Statement logged
                              literally
            query              – … in almost all cases

                         std::vector<uint8_t> variables          ed
                                                             ecod
                                                     to be d
            error_code
                                               ne ed
db_name                                 ca se:
                               Spe cial




                                                                  24
Reading event data

•Cast to correct event type             <Insert Picture Here>


•Access fields
switch (event­>header()­>type_code) {
case QUERY_EVENT:
  Query_event *qev =
    static_cast<Query_event*>(event);
  cout << qev­>query << endl;
  break;
case USER_VAR_EVENT:
  …
case FORMAT_DESCRIPTION_EVENT:
  …
}



                                                          25
Event-driven API

                   <Insert Picture Here>




                                     26
Event-driven API

• Content handlers                  <Insert Picture Here>




                     wait_for_next_event



                                                      27
Saving user-defined variables

class Save_handler
  : public Content_handler
{ … };

Save_handler::Map vars;
Save_handler save_vars(vars);
binlog.content_handler_pipeline()
  ­>push_back(&save_vars);




                                    28
User-defined variables
class Save_handler : public Content_handler {
public:
                                              <Insert Picture Here>
  typedef std::map<std::string, std::string> Map;
  Save_handler(Map &container) : m_var(container)
  { }

  Binary_log_event *
  process_event(User_var_event *event) {
    m_var[event­>name] = event­>value;
    return NULL;
  }

private:
  Map &m_var;
};




                                                                 29
Replace handler
class Replace_vars : 
  public Content_handler
{
  Binary_log_event *
  process_event(Query_log_event *event)
  {
    /* Code to replace variables */
  }                                p
                                 cp
};                            2.
                                       s ic-
                                  ba
                            le:
                          mp
                     e xa
              Full

                                               30
<Insert Picture Here>



                                               Binlog API
                                ●
                                  The replication listener

                                           Example two:
                        How to capture live row changes




                                                             31
We'll cover this
     Row events in the binlog                      soon (trust me)


              Table map
                                           Header
              Write rows
Transaction
              Write rows

              Write rows

              Table map
Transaction
              Delete rows                          A bunch of rows


                            Map table definition
                            to table ID




                                                                  32
Capturing row events
class Row_event_handler : 
  public Content_handler
{
public:
  Binary_log_event *
  process_event(Row_event *event)
  {
    switch(ev­>header()­>type_code)
    {
      case WRITE_ROWS_EVENT:
      case UPDATE_ROWS_EVENT:
      case DELETE_ROWS_EVENT:
         ...

                                      33
Capturing row events

• The *_ROWS_EVENT
                         Defined in the
                         table map event
uint64_t table_id;
uint16_t flags;
uint64_t columns_len;
uint32_t null_bits_len;
vector<uint8_t> columns_before_image;
vector<uint8_t> used_columns;
vector<uint8_t> row;
                          Raw row data




                                           34
Reading rows

•Wrap raw row data in Row_event_set
•Iterate over rows using iterator
Row_event_set rows(row_event, table_map_event);

Row_event_set::iterator it= rows.begin();




                                      You need to have
                                      captured this before!




                                                         35
Reading fields of a row

•Row_of_fields to iterate fields of a row
 – Turns row into row of fields sequence
Row_event_set rows(row_event, table_map_event);

 for (Row_event_set::iterator it = rows.begin() ;
      it != rows.end() ;
      ++it)
   table_delete(os.str(), Row_of_fields(*it));




                                                    36
Reading fields of a row

• Iterate over fields in Row_of_fields

void table_delete (..., const Row_of_fields& fields)
{
 Row_of_fields::iterator it= fields.begin();
 for (int id = 0 ; it =! fields.end() ; ++it, ++id) {
  std::string str;
  Converter().to(str, *it);
  std::cout << id << "= " << str << std::endl;
 }
}




                                                        37
Decoding a field

• Iterate over fields in Row_of_fields

void table_delete (..., const Row_of_fields& fields)
{
 Row_of_fields::iterator it= fields.begin();
 for (int id = 0 ; it =! fields.end() ; ++it, ++id) {
  std::string str;
  Converter().to(str, *it);
  std::cout << id << "= " << str << std::endl;
 }
}




                                                        38
Summary – what's it for?

•Replicate to other systems
  – Hbase, SOLR, etc.
•Triggering on specific events
  – Call the DBA when tables are dropped?
  – Monitor objects in database
•Browsing binary logs
  – Extract subset of changes (by table, by execution time, etc.)
  – Statistics
•Component in building other solutions
  – Point-in-time restore
  – Sharding / Load-balancing

                                                                    39
Summary – what we've covered

•Reading events
•Creating content handlers
•Processing queries
•Processing rows
•Reading fields
•… but there is a lot more




                               40
• Available at labs
   – http://labs.mysql.com/
• Source code available at launchpad
   – http://launchpad.net/mysql-replication-listener
• MySQL High Availability
  Get it as free ebook: http://oreilly.com/go/ebookrequest
  Valid this week, mention event “MySQL Replication
  Update”




                                                             41
MySQL Binary Log API Presentation - OSCON 2011

More Related Content

What's hot

MySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellMySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellEmily Ikuta
 
What You Should Know About WebLogic Server 12c (12.2.1.2) #oow2015 #otntour2...
What You Should Know About WebLogic Server 12c (12.2.1.2)  #oow2015 #otntour2...What You Should Know About WebLogic Server 12c (12.2.1.2)  #oow2015 #otntour2...
What You Should Know About WebLogic Server 12c (12.2.1.2) #oow2015 #otntour2...Frank Munz
 
The Native NDB Engine for Memcached
The Native NDB Engine for MemcachedThe Native NDB Engine for Memcached
The Native NDB Engine for MemcachedJohn David Duncan
 
Percona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-managementPercona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-managementmysqlops
 
Easy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and TroubleshootingEasy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and TroubleshootingBob Burgess
 
Hadoop For Enterprises
Hadoop For EnterprisesHadoop For Enterprises
Hadoop For Enterprisesnvvrajesh
 
Weblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationWeblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationRakesh Gujjarlapudi
 
MySQL Performance Best Practices
MySQL Performance Best PracticesMySQL Performance Best Practices
MySQL Performance Best PracticesOlivier DASINI
 
2020 pre fosdem mysql clone
2020 pre fosdem   mysql clone2020 pre fosdem   mysql clone
2020 pre fosdem mysql cloneGeorgi Kodinov
 
MySQL Performance Tuning Variables
MySQL Performance Tuning VariablesMySQL Performance Tuning Variables
MySQL Performance Tuning VariablesFromDual GmbH
 
MySQL Group Replication - Ready For Production? (2018-04)
MySQL Group Replication - Ready For Production? (2018-04)MySQL Group Replication - Ready For Production? (2018-04)
MySQL Group Replication - Ready For Production? (2018-04)Kenny Gryp
 
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 Geir Høydalsvik
 
MySQL cluster 72 in the Cloud
MySQL cluster 72 in the CloudMySQL cluster 72 in the Cloud
MySQL cluster 72 in the CloudMarco Tusa
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptChien Chung Shen
 
MySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgradeMySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgradeAbel Flórez
 
Benchmarking MongoDB and CouchBase
Benchmarking MongoDB and CouchBaseBenchmarking MongoDB and CouchBase
Benchmarking MongoDB and CouchBaseChristopher Choi
 
5050 dev nation
5050 dev nation5050 dev nation
5050 dev nationArun Gupta
 
12cR2 Single-Tenant: Multitenant Features for All Editions
12cR2 Single-Tenant: Multitenant Features for All Editions12cR2 Single-Tenant: Multitenant Features for All Editions
12cR2 Single-Tenant: Multitenant Features for All EditionsFranck Pachot
 
Upcoming changes in MySQL 5.7
Upcoming changes in MySQL 5.7Upcoming changes in MySQL 5.7
Upcoming changes in MySQL 5.7Morgan Tocker
 
InnoDB Tablespace Encryption
InnoDB Tablespace Encryption InnoDB Tablespace Encryption
InnoDB Tablespace Encryption Satya Bodapati
 

What's hot (20)

MySQL 5.7 in a Nutshell
MySQL 5.7 in a NutshellMySQL 5.7 in a Nutshell
MySQL 5.7 in a Nutshell
 
What You Should Know About WebLogic Server 12c (12.2.1.2) #oow2015 #otntour2...
What You Should Know About WebLogic Server 12c (12.2.1.2)  #oow2015 #otntour2...What You Should Know About WebLogic Server 12c (12.2.1.2)  #oow2015 #otntour2...
What You Should Know About WebLogic Server 12c (12.2.1.2) #oow2015 #otntour2...
 
The Native NDB Engine for Memcached
The Native NDB Engine for MemcachedThe Native NDB Engine for Memcached
The Native NDB Engine for Memcached
 
Percona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-managementPercona Live 2012PPT:mysql-security-privileges-and-user-management
Percona Live 2012PPT:mysql-security-privileges-and-user-management
 
Easy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and TroubleshootingEasy MySQL Replication Setup and Troubleshooting
Easy MySQL Replication Setup and Troubleshooting
 
Hadoop For Enterprises
Hadoop For EnterprisesHadoop For Enterprises
Hadoop For Enterprises
 
Weblogic Administration Managed Server migration
Weblogic Administration Managed Server migrationWeblogic Administration Managed Server migration
Weblogic Administration Managed Server migration
 
MySQL Performance Best Practices
MySQL Performance Best PracticesMySQL Performance Best Practices
MySQL Performance Best Practices
 
2020 pre fosdem mysql clone
2020 pre fosdem   mysql clone2020 pre fosdem   mysql clone
2020 pre fosdem mysql clone
 
MySQL Performance Tuning Variables
MySQL Performance Tuning VariablesMySQL Performance Tuning Variables
MySQL Performance Tuning Variables
 
MySQL Group Replication - Ready For Production? (2018-04)
MySQL Group Replication - Ready For Production? (2018-04)MySQL Group Replication - Ready For Production? (2018-04)
MySQL Group Replication - Ready For Production? (2018-04)
 
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015 2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
2015: Whats New in MySQL 5.7, At Oracle Open World, November 3rd, 2015
 
MySQL cluster 72 in the Cloud
MySQL cluster 72 in the CloudMySQL cluster 72 in the Cloud
MySQL cluster 72 in the Cloud
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning Concept
 
MySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgradeMySQL 5.7 - What's new and How to upgrade
MySQL 5.7 - What's new and How to upgrade
 
Benchmarking MongoDB and CouchBase
Benchmarking MongoDB and CouchBaseBenchmarking MongoDB and CouchBase
Benchmarking MongoDB and CouchBase
 
5050 dev nation
5050 dev nation5050 dev nation
5050 dev nation
 
12cR2 Single-Tenant: Multitenant Features for All Editions
12cR2 Single-Tenant: Multitenant Features for All Editions12cR2 Single-Tenant: Multitenant Features for All Editions
12cR2 Single-Tenant: Multitenant Features for All Editions
 
Upcoming changes in MySQL 5.7
Upcoming changes in MySQL 5.7Upcoming changes in MySQL 5.7
Upcoming changes in MySQL 5.7
 
InnoDB Tablespace Encryption
InnoDB Tablespace Encryption InnoDB Tablespace Encryption
InnoDB Tablespace Encryption
 

Similar to MySQL Binary Log API Presentation - OSCON 2011

MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) Frazer Clement
 
2012 replication
2012 replication2012 replication
2012 replicationsqlhjalp
 
iguazio - nuclio overview to CNCF (Sep 25th 2017)
iguazio - nuclio overview to CNCF (Sep 25th 2017)iguazio - nuclio overview to CNCF (Sep 25th 2017)
iguazio - nuclio overview to CNCF (Sep 25th 2017)Eran Duchan
 
PostgreSQL Write-Ahead Log (Heikki Linnakangas)
PostgreSQL Write-Ahead Log (Heikki Linnakangas) PostgreSQL Write-Ahead Log (Heikki Linnakangas)
PostgreSQL Write-Ahead Log (Heikki Linnakangas) Ontico
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systemssosorry
 
Dbvisit replicate: logical replication made easy
Dbvisit replicate: logical replication made easyDbvisit replicate: logical replication made easy
Dbvisit replicate: logical replication made easyFranck Pachot
 
nuclio Overview October 2017
nuclio Overview October 2017nuclio Overview October 2017
nuclio Overview October 2017iguazio
 
Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)
Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)
Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)Issac Buenrostro
 
What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4nobby
 
Splunk as a_big_data_platform_for_developers_spring_one2gx
Splunk as a_big_data_platform_for_developers_spring_one2gxSplunk as a_big_data_platform_for_developers_spring_one2gx
Splunk as a_big_data_platform_for_developers_spring_one2gxDamien Dallimore
 
[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep DiveAkihiro Suda
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with serverEugene Yokota
 
Replication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party ExtinctionReplication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party ExtinctionBen Mildren
 
Java one 2015 [con3339]
Java one 2015 [con3339]Java one 2015 [con3339]
Java one 2015 [con3339]Arshal Ameen
 
2012 scale replication
2012 scale replication2012 scale replication
2012 scale replicationsqlhjalp
 
Creating Scalable JVM/Java Apps on Heroku
Creating Scalable JVM/Java Apps on HerokuCreating Scalable JVM/Java Apps on Heroku
Creating Scalable JVM/Java Apps on HerokuJoe Kutner
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repositorynobby
 
Using MongoDB to Build a Fast and Scalable Content Repository
Using MongoDB to Build a Fast and Scalable Content RepositoryUsing MongoDB to Build a Fast and Scalable Content Repository
Using MongoDB to Build a Fast and Scalable Content RepositoryMongoDB
 
Playing in the Same Sandbox: MySQL and Oracle
Playing in the Same Sandbox:  MySQL and OraclePlaying in the Same Sandbox:  MySQL and Oracle
Playing in the Same Sandbox: MySQL and Oraclelynnferrante
 

Similar to MySQL Binary Log API Presentation - OSCON 2011 (20)

MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014) MySQL Cluster Asynchronous replication (2014)
MySQL Cluster Asynchronous replication (2014)
 
2012 replication
2012 replication2012 replication
2012 replication
 
iguazio - nuclio overview to CNCF (Sep 25th 2017)
iguazio - nuclio overview to CNCF (Sep 25th 2017)iguazio - nuclio overview to CNCF (Sep 25th 2017)
iguazio - nuclio overview to CNCF (Sep 25th 2017)
 
PostgreSQL Write-Ahead Log (Heikki Linnakangas)
PostgreSQL Write-Ahead Log (Heikki Linnakangas) PostgreSQL Write-Ahead Log (Heikki Linnakangas)
PostgreSQL Write-Ahead Log (Heikki Linnakangas)
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
Dbvisit replicate: logical replication made easy
Dbvisit replicate: logical replication made easyDbvisit replicate: logical replication made easy
Dbvisit replicate: logical replication made easy
 
nuclio Overview October 2017
nuclio Overview October 2017nuclio Overview October 2017
nuclio Overview October 2017
 
Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)
Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)
Open Source LinkedIn Analytics Pipeline - BOSS 2016 (VLDB)
 
What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4What's New In Apache Lenya 1.4
What's New In Apache Lenya 1.4
 
Splunk as a_big_data_platform_for_developers_spring_one2gx
Splunk as a_big_data_platform_for_developers_spring_one2gxSplunk as a_big_data_platform_for_developers_spring_one2gx
Splunk as a_big_data_platform_for_developers_spring_one2gx
 
[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive
 
Road to sbt 1.0 paved with server
Road to sbt 1.0   paved with serverRoad to sbt 1.0   paved with server
Road to sbt 1.0 paved with server
 
Replication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party ExtinctionReplication features, technologies and 3rd party Extinction
Replication features, technologies and 3rd party Extinction
 
Java one 2015 [con3339]
Java one 2015 [con3339]Java one 2015 [con3339]
Java one 2015 [con3339]
 
2012 scale replication
2012 scale replication2012 scale replication
2012 scale replication
 
MySQL Replication
MySQL ReplicationMySQL Replication
MySQL Replication
 
Creating Scalable JVM/Java Apps on Heroku
Creating Scalable JVM/Java Apps on HerokuCreating Scalable JVM/Java Apps on Heroku
Creating Scalable JVM/Java Apps on Heroku
 
The Java Content Repository
The Java Content RepositoryThe Java Content Repository
The Java Content Repository
 
Using MongoDB to Build a Fast and Scalable Content Repository
Using MongoDB to Build a Fast and Scalable Content RepositoryUsing MongoDB to Build a Fast and Scalable Content Repository
Using MongoDB to Build a Fast and Scalable Content Repository
 
Playing in the Same Sandbox: MySQL and Oracle
Playing in the Same Sandbox:  MySQL and OraclePlaying in the Same Sandbox:  MySQL and Oracle
Playing in the Same Sandbox: MySQL and Oracle
 

More from Mats Kindahl

Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricMats Kindahl
 
High-Availability using MySQL Fabric
High-Availability using MySQL FabricHigh-Availability using MySQL Fabric
High-Availability using MySQL FabricMats Kindahl
 
Elastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStackElastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStackMats Kindahl
 
Sharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL FabricSharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL FabricMats Kindahl
 
MySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL ServersMySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL ServersMats Kindahl
 
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFSMySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFSMats Kindahl
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMats Kindahl
 
Replication Tips & Trick for SMUG
Replication Tips & Trick for SMUGReplication Tips & Trick for SMUG
Replication Tips & Trick for SMUGMats Kindahl
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHPMats Kindahl
 
Replication Tips & Tricks
Replication Tips & TricksReplication Tips & Tricks
Replication Tips & TricksMats Kindahl
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesMats Kindahl
 
Mysteries of the binary log
Mysteries of the binary logMysteries of the binary log
Mysteries of the binary logMats Kindahl
 

More from Mats Kindahl (13)

Why rust?
Why rust?Why rust?
Why rust?
 
Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL Fabric
 
High-Availability using MySQL Fabric
High-Availability using MySQL FabricHigh-Availability using MySQL Fabric
High-Availability using MySQL Fabric
 
Elastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStackElastic Scalability in MySQL Fabric Using OpenStack
Elastic Scalability in MySQL Fabric Using OpenStack
 
Sharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL FabricSharding and Scale-out using MySQL Fabric
Sharding and Scale-out using MySQL Fabric
 
MySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL ServersMySQL Fabric: Easy Management of MySQL Servers
MySQL Fabric: Easy Management of MySQL Servers
 
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFSMySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
MySQL Applier for Apache Hadoop: Real-Time Event Streaming to HDFS
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
 
Replication Tips & Trick for SMUG
Replication Tips & Trick for SMUGReplication Tips & Trick for SMUG
Replication Tips & Trick for SMUG
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHP
 
Replication Tips & Tricks
Replication Tips & TricksReplication Tips & Tricks
Replication Tips & Tricks
 
Python Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL DatabasesPython Utilities for Managing MySQL Databases
Python Utilities for Managing MySQL Databases
 
Mysteries of the binary log
Mysteries of the binary logMysteries of the binary log
Mysteries of the binary log
 

Recently uploaded

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Recently uploaded (20)

How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

MySQL Binary Log API Presentation - OSCON 2011

  • 1.
  • 2. <Insert Picture Here> An API for Reading the MySQL Binary Log Mats Kindahl Lars Thalmann Lead Software Engineer, MySQL Development Director, MySQL Replication & Utilities Replication, Backup & Connectors
  • 3. The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 3
  • 4. Outline •Replication Architecture •Binary logs •Binary log event •Reading binary log – Connecting to server – Reading from files •Reading events – Queries – Reading rows (row-based replication) – Other events 4
  • 5. Replication Architecture Master Slave(s) Clients Changes 5
  • 6. Replication Architecture Master Slave(s) Session Databa Databa Databa se Session Client Dump Dump se Dump se Session I/O SQL I/O SQL I/O SQL Binary Log 6
  • 7. Replication Architecture Master Slave(s) Session Databa Database Databa Session Client Dump Dump se Dump se Session I/O SQL I/O SQL I/O SQL Binary Log Relay Log 7
  • 8. Replication to other systems Slave(s) Database Master I/O SQL Session Relay Log Session Client Dump Dump Dump Dump Data Session HBase Mining Full-text SOLR indexing Binary Log ? 8
  • 9. Transforming events Subject of our presentation Se rv r e API Transformer SOLR le Fi “Change Data Capture” 9
  • 10. Binlog API •Library to process replication events •API is ready for use •Goals: – Simple – Extensible – Efficient 10
  • 11. <Insert Picture Here> Binlog API ● The replication listener How to capture events 11
  • 12. First example #include <cstdlib> #include <iostream> #include <binlog_api.h> <Insert Picture Here> int main(int argc, char *argv[]) {   const char *url = “mysql://root@127.0.0.1:3360”;   Binary_log binlog(create_transport(url));   binlog.connect();   Binary_log_event *event;   while (true) {     int result = binlog.wait_for_next_event(&event);     if (result == ERR_EOF)       break;     cout << “ at “ << binlog.get_position()          << “ event type “ << event.get_type_code()          << endl;   }   return EXIT_SUCCESS; } 12
  • 13. Create network transport #include <cstdlib> #include <iostream> #include <binlog_api.h> <Insert Picture Here> int main(int argc, char *argv[]) {   const char *url = “mysql://root@127.0.0.1:3360”;   Binary_log binlog(create_transport(url));   binlog.connect();   Binary_log_event *event;   while (true) {     int result = binlog.wait_for_next_event(&event);     if (result == ERR_EOF)       break;     cout << “ at “ << binlog.get_position()          << “ event type “ << event.get_type_code()          << endl;   }   return EXIT_SUCCESS; } 13
  • 14. … or file transport #include <cstdlib> #include <iostream> #include <binlog_api.h> <Insert Picture Here> int main(int argc, char *argv[]) {   const char *url = “file:///tmp/binlog.0000001”;   Binary_log binlog(create_transport(url));   binlog.connect();   Binary_log_event *event;   while (true) {     int result = binlog.wait_for_next_event(&event);     if (result == ERR_EOF)       break;     cout << “ at “ << binlog.get_position()          << “ event type “ << event.get_type_code()          << endl;   }   return EXIT_SUCCESS; } 14
  • 15. Connect the transport #include <cstdlib> #include <iostream> #include <binlog_api.h> <Insert Picture Here> int main(int argc, char *argv[]) {   const char *url = “file:///tmp/binlog.0000001”;   Binary_log binlog(create_transport(url));   binlog.connect();   Binary_log_event *event;   while (true) {     int result = binlog.wait_for_next_event(&event);     if (result == ERR_EOF)       break;     cout << “ at “ << binlog.get_position()          << “ event type “ << event.get_type_code()          << endl;   }   return EXIT_SUCCESS; } 15
  • 16. Digression: set read position •Default: start at beginning <Insert Picture Here> •Set position explicitly: if (binlog.set_position(file, pos)) {   /* Handle error */ } 16
  • 17. Read events #include <cstdlib> #include <iostream> #include <binlog_api.h> <Insert Picture Here> int main(int argc, char *argv[]) { Get event   const char *url = “file:///tmp/binlog.0000001”;   Binary_log binlog(create_transport(url));   binlog.connect();   Binary_log_event *event;   while (true) {     int result = binlog.wait_for_next_event(&event);     if (result == ERR_EOF)       break;     cout << “ at “ << binlog.get_position()          << “ event type “ << event­>get_type_code()          << endl;   }   return EXIT_SUCCESS; } 17
  • 18. Steps summary •Create a transport – create_transport •Connect to server – connect •Set position – set_position •Start event loop – wait_for_next_event 18
  • 19. <Insert Picture Here> Binlog API ● The replication listener Reading information in events 19
  • 20. Binlog Event Structure • Common header Common Header • Generic data • Fixed size • Post-header Post-header • Event-specific data • Fixed size • Variable part • Event-specific data Variable Part • Variable size 20
  • 21. Reading the header •Read common header <Insert Picture Here> – header() •Access fields switch (event­>header()­>type_code) { case QUERY_EVENT:   … case USER_VAR_EVENT:   … case FORMAT_DESCRIPTION_EVENT:   … } 21
  • 22. Binlog Event Common Header type_code timestamp server_id • Data common to all events • Next Position 4 bytes – One-after-end of event • Timestamp – Statement start time • Flags – Binlog-in-use next_position – Thread-specific – Suppress “use” event_length – Artificial flags 19 Bytes – Relay-log event 22
  • 23. Binlog Event Structure • Common header Common Header • Generic data • Fixed size • Post-header Post-header • Event-specific data • Fixed size • Variable part • Event-specific data Variable Part • Variable size 23
  • 24. Query Event thread_id exec_time •Most common event Common Header •Used for statements •Statement logged literally query – … in almost all cases std::vector<uint8_t> variables ed ecod to be d error_code ne ed db_name ca se: Spe cial 24
  • 25. Reading event data •Cast to correct event type <Insert Picture Here> •Access fields switch (event­>header()­>type_code) { case QUERY_EVENT:   Query_event *qev =     static_cast<Query_event*>(event);   cout << qev­>query << endl;   break; case USER_VAR_EVENT:   … case FORMAT_DESCRIPTION_EVENT:   … } 25
  • 26. Event-driven API <Insert Picture Here> 26
  • 27. Event-driven API • Content handlers <Insert Picture Here> wait_for_next_event 27
  • 29. User-defined variables class Save_handler : public Content_handler { public: <Insert Picture Here>   typedef std::map<std::string, std::string> Map;   Save_handler(Map &container) : m_var(container)   { }   Binary_log_event *   process_event(User_var_event *event) {     m_var[event­>name] = event­>value;     return NULL;   } private:   Map &m_var; }; 29
  • 31. <Insert Picture Here> Binlog API ● The replication listener Example two: How to capture live row changes 31
  • 32. We'll cover this Row events in the binlog soon (trust me) Table map Header Write rows Transaction Write rows Write rows Table map Transaction Delete rows A bunch of rows Map table definition to table ID 32
  • 34. Capturing row events • The *_ROWS_EVENT Defined in the table map event uint64_t table_id; uint16_t flags; uint64_t columns_len; uint32_t null_bits_len; vector<uint8_t> columns_before_image; vector<uint8_t> used_columns; vector<uint8_t> row; Raw row data 34
  • 35. Reading rows •Wrap raw row data in Row_event_set •Iterate over rows using iterator Row_event_set rows(row_event, table_map_event); Row_event_set::iterator it= rows.begin(); You need to have captured this before! 35
  • 36. Reading fields of a row •Row_of_fields to iterate fields of a row – Turns row into row of fields sequence Row_event_set rows(row_event, table_map_event); for (Row_event_set::iterator it = rows.begin() ;      it != rows.end() ;      ++it)   table_delete(os.str(), Row_of_fields(*it)); 36
  • 37. Reading fields of a row • Iterate over fields in Row_of_fields void table_delete (..., const Row_of_fields& fields) {  Row_of_fields::iterator it= fields.begin();  for (int id = 0 ; it =! fields.end() ; ++it, ++id) {   std::string str;   Converter().to(str, *it);   std::cout << id << "= " << str << std::endl;  } } 37
  • 38. Decoding a field • Iterate over fields in Row_of_fields void table_delete (..., const Row_of_fields& fields) {  Row_of_fields::iterator it= fields.begin();  for (int id = 0 ; it =! fields.end() ; ++it, ++id) {   std::string str;   Converter().to(str, *it);   std::cout << id << "= " << str << std::endl;  } } 38
  • 39. Summary – what's it for? •Replicate to other systems – Hbase, SOLR, etc. •Triggering on specific events – Call the DBA when tables are dropped? – Monitor objects in database •Browsing binary logs – Extract subset of changes (by table, by execution time, etc.) – Statistics •Component in building other solutions – Point-in-time restore – Sharding / Load-balancing 39
  • 40. Summary – what we've covered •Reading events •Creating content handlers •Processing queries •Processing rows •Reading fields •… but there is a lot more 40
  • 41. • Available at labs – http://labs.mysql.com/ • Source code available at launchpad – http://launchpad.net/mysql-replication-listener • MySQL High Availability Get it as free ebook: http://oreilly.com/go/ebookrequest Valid this week, mention event “MySQL Replication Update” 41