How to retrieve the column names of a table using Web SQL?

Working on extracting column lists from Web SQL (Chrome's local database). One approach is to gather information from sqlite_master.

SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "'+name+'";

As an example, here is a sample result:

CREATE TABLE table_name ( id INTEGER PRIMARY KEY AUTOINCREMENT, 
number INTEGER unique, description TEXT, password TEXT, url TEXT ) 

I am seeking assistance with writing regex to extract column names or exploring alternative methods to achieve the same.

PS. I prefer not to use select * from table to retrieve column names as I believe it is not the most efficient solution.

Answer №1

To retrieve the columns of a table, simply use the PRAGMA table_info(table_name) command:

PRAGMA table_info()

This will return a single row for each column in the specified table. The data set includes details such as:

  • cid: Column ID (numbered sequentially from left to right, starting at 0)
  • name: Column name
  • type: Column type declaration
  • notnull: Indicates if 'NOT NULL' is part of the column declaration
  • dflt_value: Default value for the column, if applicable

It's important to note that Chrome blocks all PRAGMA commands, so this method isn't effective in WebSQL.


In WebSQL, access is restricted to tables created by your app, so it's essential to keep track of the columns within your tables.


Alternatively, you can attempt to read from the table directly:

SELECT * FROM table_name LIMIT 1

By utilizing the LIMIT clause, you can efficiently fetch only a single record. (Unless there are large blobs stored in that record.)

Answer №2

After experimenting in Chrome, I found success using the html5sql library. Additionally, I created a codepen that showcases pure-HTML5 integration with a clever Promise-based query function, which you can check out here.

function retrieveDatabaseInfo(callback){
    html5sql.process("SELECT * FROM sqlite_master WHERE name NOT LIKE 'sqlite\\_%' escape '\\' AND name NOT LIKE '\\_%' escape '\\'", function(txTables, rsTables, tables){
        if (!tables.length) return callback(null, []);
        tables.forEach(function(table){
            var tableQuery = table.sql.split(',');
            tableQuery[0] = tableQuery[0].replace(new RegExp('create\\s+table\\s+' + table.name + '\\s*\\(', 'i'),'');
            table.fields = tableQuery.map(function(item){
                return item.trim().split(/\s/).shift();
            })
            .filter(function(item){
                return (item.indexOf(')') === -1)
            });
        });
        callback(null, tables)
    }, callback);
}

Your (error, tables) callback will receive data structured like this:

[{
    "type": "table",
    "name": "Users",
    "tbl_name": "Users",
    "rootpage": 6,
    "sql": "CREATE TABLE Users(\n  id INTEGER PRIMARY KEY AUTOINCREMENT,\n  firstName VARCHAR(255),\n  lastName VARCHAR(255),\n  email VARCHAR(255),\n  created TIMESTAMP DEFAULT (DATETIME('now','localtime'))\n)",
    "fields": [
        "id",
        "firstName",
        "lastName",
        "email",
        "created"
    ]
}]

Take note of the fields section. This method functions even when there are no records. While the regex/string parsing could be enhanced and type information could potentially be extracted as well, this approach worked effectively for my requirements. An alternative SQL method once you have the field names is as follows:

SELECT TYPEOF(id) as id, TYPEOF(firstName) AS firstName , TYPEOF(lastName) AS lastName, TYPEOF(email) AS email, TYPEOF(created) AS created FROM Users;

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

Is locking Node and npm versions necessary for frontend framework projects?

Currently working on frontend projects in React and Vue, I am using specific versions of node and npm. However, with other developers contributing to the repository, how can we ensure that they also use the same versions to create consistent js bundles? ...

WebDriverIO effortlessly converts the text extracted using the getText() command

One of my webpage elements contains the following text: <span class="mat-button-wrapper">Sicherheitsfrage ändern</span> However, when I attempt to verify this text using webdriver, it indicates that it is incorrect assert.strictEqual($(.mat ...

Navigate to items within a content block with a set height

I have a <div> that has a fixed height and overflow-y: scroll. Inside this div, there is mostly a <p> tag containing a long text with some highlighting (spans with background-color and a numbered id attribute). Just to note, this is an HTML5 a ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Tips for transferring data between iframes on separate pages

I am currently working on implementing a web calendar module within an iframe on page-b. This module consists of 1 page with two sections. Upon entering zipcodes and house numbers, the inputs are hidden and the calendar is displayed. The technology used he ...

Terminate the Chrome browser using python and end the process

How can I close the Chrome browser window and kill the process opened in the beginning in the program below? from selenium import webdriver import subprocess subprocess.Popen('"C:\\Program Files\\Google\\Chrome&bsol ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

Is it possible to swap a <div> element with the content of another HTML page using the .innerHTML method?

I am currently working on a project that involves loading different webpages into a <div> on my page once specific links are clicked. I came across a thread about using jQuery for this purpose, but I'm not familiar with it. Is there a way to ach ...

Error occurs when attempting to reference an object from an NPM package

Currently, I'm attempting to utilize the https://github.com/iamcal/js-emoji library for colon-to-emoji conversion. Following the installation of its NPM package, I included <script src="../node_modules/emoji-js/lib/emoji.js" type="te ...

Problem encountered with JavaScript getter on iOS 5

While implementing JavaScript getters in my iPad-optimized website, everything was working perfectly until I updated to iOS 5. Suddenly, the site stopped functioning properly. After thorough investigation, I discovered the root cause of the issue. I have ...

What is the Next.js equivalent of routing with rendering capability for nested component paths?

I am new to Next.js and so far have been loving the experience. I'm a bit stuck on how to achieve the equivalent of the following code in Next.js These are all client-side routes that render nested components on the user page. The value of ${currentP ...

What steps should be taken to resolve the error message "This Expression is not constructable"?

I'm trying to import a JavaScript class into TypeScript, but I keep getting the error message This expression is not constructable.. The TypeScript compiler also indicates that A does not have a constructor signature. Can anyone help me figure out how ...

Invoke data-id when the ajax call is successful

Initially, there was a smoothly working "like button" with the following appearance: <a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span ...

Identifying the Operating System and Applying the Appropriate Stylesheet

I am trying to detect the Windows operating system and assign a specific stylesheet for Windows only. Below is the code snippet I have been using: $(function() { if (navigator.appVersion.indexOf("Win")!=-1) { $(document ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

Exploring asynchronous data handling in AngularJS using promises

Currently, I am working on a single page application using angularJS and encountering some difficulties in storing asynchronous data. In simple terms, I have a service that contains my data models which are returned as promises (as they can be updated asy ...

Using Jquery Chosen Plugin to Dynamically Populate One Chosen Selection Based on Another

Good evening to all, please excuse any errors in my English. I have successfully integrated a jQuery Chosen plugin with my 'estado' field (or province). My goal is to populate another jQuery Chosen plugin with the cities corresponding to that s ...

Styling extracted content using headless browsing algorithm

Is there a way to format the scraped text from multiple elements on the page for use elsewhere? I have JavaScript code that can loop over the elements, add their text to an array, and turn it into a string, achieving the desired formatting. How can I inc ...

Steps to improve the appearance of the Header on a dataTable during Dragging

I am working on creating a table that can be reordered using mat-table and MatTableDataSource. However, I would like the column to have a white background color instead of being transparent when dragged. Is there a way to achieve this? <table mat-tab ...

Are the server updates not syncing with the client browser?

Is there a reason why server updates are not appearing on the client browser? Could it be that a specific attribute value needs to be modified or is this related to caching? app.get('/hello' , (_ , res) => { res.header({ 'Cach ...