MCPcopy Create free account
hub / github.com/bloomberg/comdb2 / dbtable_insert

Function dbtable_insert

lua/sp.c:2424–2504  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2422}
2423
2424static int dbtable_insert(Lua lua)
2425{
2426 SP sp = getsp(lua);
2427 int rc, nargs;
2428 strbuf *columns, *params, *sql;
2429
2430 nargs = lua_gettop(lua);
2431 if (nargs != 2) {
2432 return luabb_error(lua, NULL, "bad arguments to 'insert'");
2433 }
2434
2435 luaL_checkudata(lua, 1, dbtypes.dbtable);
2436 dbtable_t *table = lua_touserdata(lua, 1);
2437
2438 columns = strbuf_new();
2439 params = strbuf_new();
2440
2441 strbuf_append(columns, "(");
2442 strbuf_append(params, "(");
2443
2444 luaL_checktype(lua, 2, LUA_TTABLE);
2445
2446 // Iterate lua table to create prepared statement
2447 lua_pushnil(lua);
2448 while (lua_next(lua, 2)) {
2449 const char *col = lua_tostring(lua, -2);
2450 char *quoted_col = sqlite3_mprintf("\"%w\",", col);
2451 strbuf_append(columns, quoted_col);
2452 sqlite3_free(quoted_col);
2453 strbuf_appendf(params, "?,");
2454 lua_pop(lua, 1);
2455 }
2456 strbuf_del(columns, 1);
2457 strbuf_del(params, 1);
2458
2459 strbuf_append(columns, ")");
2460 strbuf_append(params, ")");
2461
2462 char n1[MAXTABLELEN], separator[2], n2[MAXTABLELEN];
2463 query_tbl_name(table->table_name, n1, separator, n2);
2464 sql = strbuf_new();
2465 strbuf_appendf(sql, "INSERT INTO %s%s\"%s\" %s VALUES %s", n1, separator,
2466 n2, strbuf_buf(columns), strbuf_buf(params));
2467 char *sqlstr = strbuf_disown(sql);
2468
2469 strbuf_free(sql);
2470 strbuf_free(columns);
2471 strbuf_free(params);
2472
2473 db_reset(lua);
2474 sqlite3_stmt *stmt = NULL;
2475 rc = lua_prepare_sql(sp, sqlstr, &stmt);
2476 free(sqlstr);
2477 if (rc != 0) {
2478 lua_pushinteger(lua, rc); /* Failure return code. */
2479 return 1;
2480 }
2481

Callers

nothing calls this directly

Calls 15

lua_gettopFunction · 0.85
luabb_errorFunction · 0.85
luaL_checkudataFunction · 0.85
lua_touserdataFunction · 0.85
luaL_checktypeFunction · 0.85
lua_pushnilFunction · 0.85
lua_nextFunction · 0.85
sqlite3_mprintfFunction · 0.85
sqlite3_freeFunction · 0.85
query_tbl_nameFunction · 0.85
db_resetFunction · 0.85
lua_prepare_sqlFunction · 0.85

Tested by

no test coverage detected