如何使用php重置数据库

时间:2022-09-28 22:47:39

I tried to write the function which can reset the tables in postgresql database, but it always reminds me that

我试着编写可以重置postgresql数据库中的表的函数,但它总是让我想起

Error: timeout of 5000ms exceeded. Ensure the done() callback is being called in this test. at mocha.js:4455:19

错误:超过5000毫秒的超时。确保在此测试中调用done()回调。在mocha.js:4455:19

My codes are as follows. How can I solve this problem?

我的代码如下。我怎么解决这个问题?

function reset_database($dbh) {
    $query = "DROP TABLE IF EXISTS 'users', 'posts', 'voting', 'hashtag';";
    $result = pg_query($dbh, $query);
    if (!result) {
        return array( 'status' => 0 );
    }
    else {
        return array( 'status' => 1 );

    $query  = "CREATE TABLE users(username VARCHAR(50) PRIMARY KEY, password VARCHAR(32) NOT NULL);";
    $result = pg_query($dbh, $query);

    if (!result) {
        return array( 'status' => 0 );
    }
    else {
        return array( 'status' => 1 );

    $query = "CREATE TABLE posts(pID serial, username VARCHAR(50) NOT NULL, title VARCHAR(20) NOT NULL, content VARCHAR(42),time timestamp,coorX INTEGER,coorY INTEGER, PRIMARY KEY(pID),FOREIGN KEY(username) REFERENCES users(username) ON DELETE CASCADE);";
    $result = pg_query($dbh, $query);

    if (!result) {
        return array( 'status' => 0 );
    }
    else {
        return array( 'status' => 1 );

    $query = "CREATE TABLE voting(username VARCHAR(50) NOT NULL,pID INTEGER NOT NULL,PRIMARY KEY(username, pID),FOREIGN KEY (username) REFERENCES users(username) ON DELETE CASCADE,FOREIGN KEY (pID) REFERENCES posts ON DELETE CASCADE);";
    $result = pg_query($dbh, $query);
    if (!result) {
        return array( 'status' => 0 );
    }
    else {
        return array( 'status' => 1 );

    $query = "CREATE TABLE hashtag(tag VARCHAR(42) NOT NULL,pID INTEGER NOT NULL,PRIMARY KEY(tag),FOREIGN KEY(pID) REFERENCES posts(pID) ON DELETE CASCADE);";
    $result = pg_query($dbh, $query);

    if (!result) {
        return array( 'status' => 0 );
    }
    else {
        return array( 'status' => 1 );
    }
}

1 个解决方案

#1


0  

You can use the TRUNCATE command:

您可以使用TRUNCATE命令:

$query = "TRUNCATE ONLY users, posts, voting, hashtag RESTART IDENTITY";
$result = pg_query($dbh, $query);
if (!result) {
  return array( 'status' => 0 );
} else {
  return array( 'status' => 1 );
}

ref: https://www.postgresql.org/docs/current/static/sql-truncate.html

参考:https://www.postgresql.org/docs/current/static/sql-truncate.html

#1


0  

You can use the TRUNCATE command:

您可以使用TRUNCATE命令:

$query = "TRUNCATE ONLY users, posts, voting, hashtag RESTART IDENTITY";
$result = pg_query($dbh, $query);
if (!result) {
  return array( 'status' => 0 );
} else {
  return array( 'status' => 1 );
}

ref: https://www.postgresql.org/docs/current/static/sql-truncate.html

参考:https://www.postgresql.org/docs/current/static/sql-truncate.html