Create new tables in SQLite

2

Working with NodeJS , until now, created new rows when a user was not found, and did it in the following way:

const sqlite = require('sqlite');
sqlite.open('points.sqlite').then(() => {
  sqlite.get('SELECT * FROM users WHERE ID = ${user}')
    .then(rows => {
      if (!rows) {
        sqlite.run('INSERT INTO users (ID) VALUES (?)', ['${user}'])
          .then(() => {
            sqlite.get('SELECT * FROM users WHERE ID = ${user}')
              .then((row) => {
                if (!row) return;
                client.scores.set(row.ID, row);
              }).catch(console.log);
          });
      }
    }).catch(console.log);
});

However, now I want, with another database, called lpoints.sqlite , to create a new table with the following fields:

CREATE TABLE 'IDGUILD' (
    'IDUSER'    TEXT NOT NULL UNIQUE,
    'SCORE' INTEGER,
    PRIMARY KEY('IDUSER')
);

In which, IDGUILD would be the variable ID of the guild (string of 18 characters).

How can I create new tables?

    
asked by Antonio Roman 04.02.2017 в 01:35
source

1 answer

1

Solution, make sqlite.run in which the table is created, with the name of the table and the fields. The format for the creation of the table is: sqlite.run(CREATE TABLE nombreTabla (var1 TYPE1, var2 TYPE2 ...)) source (in English).

const sqlite  = require('sqlite');
sqlite.open('lpoints.sqlite').then(() => {
  sqlite.run('CREATE TABLE '${GUILDID}' (IDUSER TEXT NOT NULL UNIQUE, SCORE INTEGER, PRIMARY KEY(IDUSER))');
});

Or on ES7 using async / await:

new Promise(async (resolve, reject) => {
  try {
    const sqlite = require('sqlite');
    await sqlite.open('lpoints.sqlite')
    await sqlite.run('CREATE TABLE '${GUILDID}' (IDUSER TEXT NOT NULL UNIQUE, SCORE INTEGER, PRIMARY KEY(IDUSER))');
    resolve();
  } catch(e) {
    reject(e);
  }
});
    
answered by 04.02.2017 / 05:21
source