MySQL是一款廣受歡迎的關系型數據庫管理系統(tǒng),提供了多種方式來執(zhí)行SQL語句,其中之一就是使用INSERT語句實現數據的插入。下面我們來看一下MySQL中INSERT語句的源代碼實現。
sql_list *insert::prepare(THD *thd, TABLE_LIST *tables, Item_list &values, List- &cols, enum_duplicates duplic, bool ignore, enum_order order_type, ulonglong options, List
*existing_partitions, st_select_lex *select_lex, bool allow_batch) { St_select_lex_backup backup(select_lex, thd); /* This lock_unsafe() should be done before calling rr_init() because we release the lock in close_thread_tables_for_reopen() called from rr_deinit(). */ tables->lock_unsafe(); Query_arena_preparer::preallocate(thd, select_lex); if (rr_init(thd)) // Read/Write deadlock detection return NULL; if (thd->lex->is_prepared_sp_stmt || thd->lex->is_function_exec()) { m_contains_values = false; } DBUG_ASSERT(!m_contains_values || tables->list.front_table()->s->table_flags & HA_CAN_INSERT_DELAYED); /* Prepare columns vector: COL_IGNORE marking Initialize 'pred_fpk_candidates' to the list of columns involved in primary key comparisons. Call columns_prepare() to prepare the set of columns to read and write. columns_prepare() returns 1 if it is possible that we need IGNORE when inserting into this table. In general it is difficult to say for sure whether IGNORE is needed or not when the table is not empty, since it depends on whether the VALUES to be inserted already exist. But if a PRIMARY or UNIQUE key is involved that covers all the columns to be updated, and if the table has no triggers, foreign keys, indexes, partitions or other complications, then INSERT IGNORE should be used automatically. (Note: if there are triggers, this only works if the trigger conditions are stored in the primary/unique index columns.) Early exit if columns_prepare() detects a hidden field in the values list which has the same name as a visible field. */ if (columns_prepare(thd, tables->list.front_table()->s, tables, values, cols, dup_col, ignoring?, order_type == ORDER_TYPE_RANDOM, order_type == ORDER_TYPE_RANDOM_MOVE_RAND_OR_NEXT)) { goto err_exit; }
這段代碼實現的是INSERT語句的prepare()函數,可看出該函數會進行多種操作,包括鎖定數據表、預處理、調用columns_prepare()等操作。其中columns_prepare()函數會對INSERT語句中的列進行準備以及判斷是否需要使用INSERT IGNORE模式,提高了INSERT語句的執(zhí)行效率,實現了對數據的快速插入。