MCPcopy Create free account
hub / github.com/ElementsProject/lightning / prepare_table_manip

Function prepare_table_manip

db/db_sqlite3.c:463–520  ·  view source on GitHub ↗

Move table out the way, return columns. * Note: with db_hook, frees tmpctx! */

Source from the content-addressed store, hash-verified

461/* Move table out the way, return columns.
462 * Note: with db_hook, frees tmpctx! */
463static char **prepare_table_manip(const tal_t *ctx,
464 struct db *db, const char *tablename)
465{
466 sqlite3_stmt *stmt;
467 const char *sql;
468 char *cmd, *bracket;
469 char **parts;
470 int err;
471 struct db_sqlite3 *wrapper = (struct db_sqlite3 *)db->conn;
472
473 /* Get schema. */
474 sqlite3_prepare_v2(wrapper->conn, "SELECT sql FROM sqlite_master WHERE type = ? AND name = ?;", -1, &stmt, NULL);
475 sqlite3_bind_text(stmt, 1, "table", strlen("table"), SQLITE_TRANSIENT);
476 sqlite3_bind_text(stmt, 2, tablename, strlen(tablename), SQLITE_TRANSIENT);
477
478 err = sqlite3_step(stmt);
479 if (err != SQLITE_ROW) {
480 db->error = tal_fmt(db, "getting schema: %s",
481 sqlite3_errmsg(wrapper->conn));
482 sqlite3_finalize(stmt);
483 return NULL;
484 }
485
486 sql = tal_strdup(tmpctx, (const char *)sqlite3_column_text(stmt, 0));
487 sqlite3_finalize(stmt);
488
489 /* We MUST use generic routines to write to db, since they
490 * mirror changes to the db hook! */
491 bracket = strchr(sql, '(');
492 if (!strstarts(sql, "CREATE TABLE") || !bracket)
493 db_fatal(db, "Bad sql from prepare_table_manip %s: %s",
494 tablename, sql);
495
496 /* Split after ( by commas: any lower case is assumed to be a field */
497 parts = tal_strsplit(ctx, bracket + 1, ",", STR_EMPTY_OK);
498
499 /* Now, we actually need to turn OFF transactions for a moment, as
500 * this pragma only has an effect outside a tx! */
501 db_commit_transaction(db);
502
503 /* But core insists we're "in a transaction" for all ops, so fake it */
504 db->in_transaction = "Not really";
505 db->transaction_started = true;
506 /* Turn off foreign keys first. */
507 db_prepare_for_changes(db);
508 db_exec_prepared_v2(take(db_prepare_untranslated(db,
509 "PRAGMA foreign_keys = OFF;")));
510 db_report_changes(db, NULL, 0);
511 db->in_transaction = NULL;
512 db->transaction_started = false;
513
514 db_begin_transaction(db);
515 cmd = tal_fmt(tmpctx, "ALTER TABLE %s RENAME TO temp_%s;",
516 tablename, tablename);
517 db_exec_prepared_v2(take(db_prepare_untranslated(db, cmd)));
518
519 return parts;
520}

Callers 2

db_sqlite3_rename_columnFunction · 0.85

Calls 6

db_fatalFunction · 0.85
db_prepare_for_changesFunction · 0.85
db_exec_prepared_v2Function · 0.85
db_prepare_untranslatedFunction · 0.85
db_report_changesFunction · 0.85
db_commit_transactionFunction · 0.70

Tested by

no test coverage detected