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

Unable to access the store from the Redux library within a React application

I decided to test out the Redux example from the official React-Redux website, which can be found HERE, using the following JavaScript code: // index.js import React from 'react' import ReactDOM from 'react-dom' import TodoApp from &ap ...

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

How to Troubleshoot jQuery AJAX Not Sending JSON Data

I've been attempting to make an ajax request, but it keeps returning with an error response. $('form#contactForm button.submit').click(function () { var contactName = $('#contactForm #contactName').val(); ...

Display webpage content in an Iframe using Javascript after PHP code has been executed

Despite researching keywords like PHP // Javascript // Load // URL online, I'm still struggling to fully grasp the concepts. Real-life case studies have been helpful, but I must admit that I'm feeling a bit overwhelmed at the moment. I created a ...

Calculating the product of two input fields and storing the result in a third input field using a for loop

There's a small issue I'm facing. I have implemented a For Loop to generate multiple sets of 3 input fields - (Quantity, Rate, Price). Using a Javascript function, I aim to retrieve the Ids of 'Quantity' and 'Rate', and then d ...

Having trouble persisting data with indexedDB

Hi there, I've encountered an issue with indexedDB. Whenever I attempt to store an array of links, the process fails without any visible errors or exceptions. I have two code snippets. The first one works perfectly: export const IndexedDB = { initDB ...

Is there a way to dynamically alter the theme based on stored data within the store

Is it possible to dynamically change the colors of MuiThemeProvider using data from a Redux store? The issue I'm facing is that this data is asynchronously loaded after the render in App.js, making the color prop unreachable by the theme provider. How ...

Incorporating jQuery to seamlessly add elements without causing any disruptions to the layout

I'm looking to enhance the design of my website by adding a mouseenter function to display two lines when hovering over an item. However, I've encountered an issue where the appearance and disappearance of these lines cause the list items to move ...

Error message: Unhandled error: The function Role.Create is not defined

I'm encountering an issue with a ".create is not a function" error while trying to repopulate my database upon restarting nodemon. Previously, everything was functioning well and all the tables were populated successfully. However, I keep receiving th ...

Countdown Timer App using Flask

I'm currently working on a Flask-based game that involves countdown timers for each round. My goal is to have the timer decrease by 1 second every round without the need to reload the page. I've tried using time.sleep in my Python code to update ...

Issues Encountered During Form Data Transmission via XHR

I require the ability to transfer files from one cloud service to another using Azure Functions running Node. In order to do this, I have installed the necessary packages (axios, form-data, xmlhttprequest) and am coding in VSCode. However, when dealing wi ...

What is the best way to add multiple elements to an array simultaneously?

I am facing an issue with my array arrayPath. I am pushing multiple values into it, but there are duplicates in the data. When the value of singleFile.originalFilename is a duplicate, I do not want to push that duplicate value into arrayPath. How can I ach ...

What is the best way to verify and eliminate unnecessary attributes from a JSON request payload in a node.js application?

My goal is to verify the data in the request payload and eliminate any unknown attributes. Example of a request payload: { "firstname":"john", "lastname":"clinton", "age": 32 } Required attributes: firstname and lastname Optional a ...

Leverage the power of Next.js Dynamic routing query object with an SWR fetch request

While working with Next.js dynamic routing, I am facing an issue where my SWR fetch request is being called before the query object is properly set. This occurs specifically when using the routing query object. Let's take the example of a dynamic rou ...

What is the method for toggling a checkbox on and off repeatedly?

I've been struggling with this piece of code. I've attempted using setTimeout, promises, and callback functions, but nothing seems to work as expected. document.querySelectorAll("input").forEach((el, i) => { setTimeout(() => { ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

Unable to display information retrieved from an API within a React application

I am facing an issue with rendering questions fetched from an API. I have set up the state and used useEffect to make the API call. However, when I try to display the questions, it seems to disrupt my CSS and show a blank page. I even attempted moving the ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Froala Editor: Innovative external toolbar that pops up when the button is clicked

In our project, we are implementing the latest version of Froala and aim to configure it so that the toolbar is activated by a separate external button, similar to Gmail where the editor initially does not display a toolbar. I attempted to modify the &apo ...

Retrieve a Google map using Ajax in a PHP script

I'm attempting to display a google map on my homepage using the following function: function addressCode(id, concatenatedToShowInMap) { var geocoder; var map; geocoder = new google.maps.Geocoder(); ...