Error: SQLite database file name must be specified

I'm currently working through this tutorial that guides us in building an app with next.js. The tutorial involves using sqlite and performing database testing. One of the key components of the tutorial is the 'database-test.js' file:

const sqlite = require('sqlite');

async function setup() {
    const db = await sqlite.open('./mydb.sqlite');
    await db.migrate({force: 'last'});

    const people = await db.all('SELECT * FROM person');
    console.log('ALL PEOPLE', JSON.stringify(people, null, 2));

    const vehicles = await db.all('SELECT * FROM vehicle');
    console.log('ALL VEHICLES', JSON.stringify(vehicles, null, 2));
}

setup();

Upon running $node database-test.js, I encounter the following error:

(node:26446) UnhandledPromiseRejectionWarning: Error: sqlite: filename cannot be null / undefined

I'm puzzled by the requirement to open a .sqlite file instead of a .db file. Despite verifying the correct path to the .sqlite file, I remain unsure about the cause of this error and how to resolve it. Unfortunately, I've been unable to find any further information or examples of the .open function.

Answer №1

Referencing @ANimator120's suggestion, I made a few adjustments. Utilize the require function as it operates on the server side. Begin by installing sqlite3 using npm i sqlite3. Next, include the path to your migrations folder if it is not located in the project root.

const sqlite3 = require('sqlite3');
const sqlite = require('sqlite');

async function openDb() {
  return sqlite.open({
    filename: './database.db',
    driver: sqlite3.Database,
  });
}

async function setup() {
  const db = await openDb();
  await db.migrate(
                    { 
                      migrationsPath: './src/migrations', //specify custom path for migrations
                      force: 'last' 
                    }
                  );

  const people = await db.all('SELECT * FROM Person');
  console.log('all person', JSON.stringify(people, null, 2));

  const vehicle = await db.all(`SELECT a.*, b.* FROM Person as a
  LEFT JOIN Vehicle as b
  ON a.id = b.ownerId
  `);
  console.log('all vehicles', JSON.stringify(vehicle, null, 2));
}

setup();

Everything seems to be functioning smoothly, at least from my perspective.

Answer №2

To utilize the open() method correctly, ensure that you have installed both sqlite and sqlite3 via npm. The proper way to implement the open() method is as shown below:

const sqlite = require('sqlite');
      const sqlite3 = require('sqlite3')
    const {open} = require('sqlite')

       async function openDB (){
    return open({
        filename : './mydb.sqlite',
        driver: sqlite3.Database
    })
}


async function setup(){
    const db = await openDB();
    await db.migrate({force : 'last'});
}

setup();

Answer №3

  1. To start, ensure sqlite3 is installed by running the command npm i --save sqlite3 in your terminal.

  2. In your JS file, replace your existing code with the following:

    const sqlite = require('sqlite');
    const sqlite3 = require('sqlite3');
    const {open} = require('sqlite');
    
    async function openDB (){
       return open({
          filename : './mydb.sqlite',
          driver: sqlite3.Database
       })
    }
    
    
    async function setup(){
        const db = await openDB();
        await db.migrate({force : 'last'});
    }
    
    setup(); 
    

However, when executing the command line

 const people = await db.all('SELECT * FROM Person'); console.log("ALL PEOPLE", JSON.stringify(people, null, 2));
, an error stating that the table 'Person' does not exist is displayed. To resolve this issue, I had to remove DROP TABLE Person; from the migration file.

Answer №4

It turns out that the tutorial was using sqlite 3.0.3. If you're using sqlite3, here is the proper way to use open() in this scenario:

import { open } from 'sqlite'
import sqlite3 from 'sqlite3'

// Remember to import or invoke this function in a different file
export async function openDB () {
  return open({
    filename: './mydb.sqlite',
    driver: sqlite3.Database
  })
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A helpful guide on integrating a Google font into your Next.js project using Tailwind CSS locally

I'm planning to use the "Work Sans" Font available on Google Fonts for a website I'm working on. After downloading the "WorkSans-Black.ttf" file, I created a subfolder named "fonts" within the "public" folder and placed the font file in there. Be ...

Having trouble pinpointing the element with protractor's binding locator

<div class="apiRequestDisplay ng-scope"> <pre class="ng-binding">GET</pre> <pre class="ng-binding">v1/securityprofiles/{securityProfileID} </pre> </div> I am trying to target the specific text within v1/secur ...

Error: The src for the image of the double cheeseburger could not be properly parsed by the `next/image` component

Could you kindly take a moment to review this? import Image from "next/image"; import { useState, useEffect } from "react"; import "@/data/data.json"; interface propsData { dish: { id: numbe ...

Is it possible to globally delay the execution of WebElement.sendKeys() in Protractor's onPrepare function?

While running protractor on a sluggish machine, I am in need of slowing down each key press and action performed. The action part has been successfully implemented, but how can I achieve the same for key presses? I have come up with a local solution which ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

Creating a buffered transformation stream in practice

In my current project, I am exploring the use of the latest Node.js streams API to create a stream that buffers a specific amount of data. This buffer should be automatically flushed when the stream is piped to another stream or when it emits `readable` ev ...

Utilizing CSS transitions to smoothly adjust the width of an element until it completely fills the container div in ReactJS

import React from 'react'; import PropTypes from 'prop-types'; import SearchIcon from '@material-ui/icons/Search'; import InputBase from '@material-ui/core/InputBase'; import { AccountCircle } from '@material-ui ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

What is the best way to adjust the color of a button element?

I've been troubleshooting the mouseover function of my JavaScript button object. The goal is to have a function call (specifically show()) within the object that detects the mouseover event and changes the button's color to grey. I suspect that t ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

The expiration period set in expireAfterSeconds doesn't seem to be functioning as expected in the time-to-live (ttl) configuration. Rows are

Can you please take a look at my code and provide some feedback? The issue I am facing is that the record is getting deleted without specifying the number of seconds. I have tried changing from createIndex to ensureIndex but it's still not working as ...

Pass data back and forth between app.js (node) and javascript (main.js)

I am facing a challenge in sending and retrieving data (username) between app.js and main.js. In my setup, I have a node app.js that calls index.html which then triggers the main.js function called "clicked". Below is the code snippets for each file: app. ...

Attempting to generate printed documents with multiple components spread across individual pages using react-to-print

I am working with the react-to-print library and I have a requirement to print a list of components, with each component on its own separate page. However, when I click on the print button, I encounter an error stating that the argument does not appear to ...

Having difficulty setting a value for a tooltip with replaceWith() function

When using jQuery's .replaceWith() method to insert new DOM contents, I noticed that all content gets replaced except for the value of the title. Even though I tried different approaches, the tooltip only displays {{descriptions.title}} instead of the ...

How to effectively compare time duration with a timer in the Laravel framework

I am managing a table that stores various job entries for employees. Each job entry includes a column for duration. I would like to trigger an alert or other event when the duration of a job has ended. My project is built using Laravel and VueJS. Below i ...

limiting the number of HTTP requests within a JavaScript forEach loop

In my current coding situation, I am facing an issue where the HTTP requests are being made simultaneously within a forEach loop. This leads to all the requests firing off at once. const main = async () => { items.forEach(async (i: Item) => ...

Utilizing ID for Data Filtering

[ { "acronym": "VMF", "defaultValue": "Video & Audio Management Function", "description": "This is defined as the Video and/or Audio Management functionality that can be performed on a Digital Item. The Video & Audio M ...

What is the best way to insert a record into the rth column of the nth row in a table

In the table I'm working with, there are 6 columns and only 5 of them have data filled in. The last column is currently empty for all rows. I am now trying to populate the last column of each row with some data. Can someone guide me on how to use a f ...

Conceal the Submit button upon completing the form submission using the load method

When creating a form and sending a request to another page, I use the following code: $(document).ready(function() { $("#send").click(function() { var text = $("#text").val(); var email = $("#email").val(); $("#exp").load("sendmail.php",{text: ...

Having trouble with the second Angular directive not functioning correctly

I am encountering an issue with two directives on the same page. The first directive is functioning correctly, but the second one is not working as expected. Below is the code snippet: HTML <body class="login" ng-app="Login"> <div ng-controller ...