Что такое web sql
Что такое web sql
SQL html
Всем привет. Сегодня мы рассмотрим работу с api Web SQL которое позволяет нам хранить данные в локальной базе данных в браузере. Данный api работает примерно потому же принципу что и localStorage. Отличие в том что localStorage хранит данные в виде пары ключ и значение, а Api Web SQL хранит данные в таблицах локальной базы данных. И для обращения к таблицам базы используются SQL запросы. Кросс доменные ограничения также распространяются на данный api. То есть вы не сможете использовать общую базу данных на разных доменах. Итак, приступим!
Первое что нам необходимо сделать, создать базу и установить с ней соединение. Делается это одной строчкой.
C помощью данного кода мы создали базу данных с названием DB, указали ей версию 0.1 и описание «My first dataBases web SQL», последним параметром мы выставили приблизительный размер 200000 выделенный под содержимое базы.
В переменной dataBases у нас теперь хранится соединение с базой данных. Для проверки успешного соединения с базой нам необходимо выполнить следующий код.
При успешном соединении идем далее. Следующим шагом у нас будет создание таблиц в базе данных.
C помощью данного кода мы создали таблицу user. Здесь мы уже воспользовались sql запросом «CREATE TABLE IF NOT EXISTS `user`(id INTEGER PRIMARY KEY, name TEXT, age INT)».
Для отправки и формирования запроса мы воспользовались такой конструкцией:
Отлично! Идем дальше!
После создания таблицы мы можем начать ее наполнять своими данными.
Теперь рассмотрим вывод значений из таблицы:
С помощью данного кода мы выведем все строки и их поля таблицы user. Причем если вы не закомментировали предыдущую строчку с добавлением новых значений, то при каждой перезагрузке страницы нам будет добавляться новая строка. Обратите внимание на поле id. При добавлении данных в таблицу мы его не указывали. Оно заполняется самостоятельно благодаря типу INTEGER и первичному(уникальному) ключу PRIMARY KEY который мы указали при создании таблицы. Это поле лучше использовать во всех таблицах, так как оно неповторимо, уникально и позволяет более точно указывать какую строку мы хотим обновить или удалить.
Обновление и удаление это наши последние операции которые мы рассмотрим.
Итак, рассмотрим пример с удалением. Допустим мы хотим удалить строку из таблицы с То есть это по сути первый элемент таблицы.
После выполнения данного кода строка с id равная 1, будет удалена из таблицы user. Теперь возможно вы понимаете для чего нужен id. С помощью него мы можем идентифицировать каждую строку в таблице получить, обновить, удалить ее не затрагивая другие строки.
Если мы хотим удалить все данные из таблицы нам достаточно не указывать условие WHERE.
C помощью данного кода мы полностью очистим таблицу user.
И в завершении данной статьи рассмотрим обновление данных в таблице.
Допустим мы хотим обновить значения полей таблицы user в строке с >
Вот в принципе и все что я хотел вам рассказать про API web SQL.
API web SQL позволяет нам создавать мощные приложения имеющие свою локальную базу данных которая будет хранится на стороне клиента. Конечно для того чтобы им пользоваться необходимо уметь строить и понимать основные sql запросы. Без этого никак.
Использование данного api в небольших проектах не имеет особого смысла. Так как существует тот же самый api localStorage.
В общем лучше использовать данное api когда нет других альтернатив. Если у вас остались или появились вопросы оставляйте их в комментариях или пишите в группу
На этом у меня все. Желаю вам успехов и удачи! Пока!
Поддержка HTML5 Web Sql Database и Google Gears с примерами
Мы все ценим свое время, и я хочу помочь вам (ну может быть не вам, но кому-то уж точно) его сберечь.
Речь пойдет о клиентских БД — Web Sql Database и Google Gears.
По долгу службы я занимаюсь веб приложением, использующим Local Database и Web Workers.
Итак, что нам требуется:
1. SQL запросы, выбирающие из локальной БД всякие данные
2. Скачивание данных через Ajax в фоновом режиме и запись их в локальную БД
3. Поддержка Firefox, Google Chrome, Safari, IE
4. Поддержка Win, Linux, MacOS, iPad
С первого взгляда ничего страшного, но со второго начинаются проблемы.
Google Gears
Поддержка Google Gears (SQL и Web Workers) показана в таблице ниже.
Основные критерии:
± поддержка Local Database,
± поддержка Web Workers
± поддержка Local Database из Web Worker
X — не проверялось
(сразу скажу — Google Gears во всех поддерживаемых браузерах поддерживает или все, или ничего, но для наглядности оставим три значения)
Chrome | Firefox | Safari | IE | |
Win | +++ | +++ | — | +++ |
MacOS | — | +++ | — | X |
iPad | X | X | — | X |
Linux | — | +++ | — | X |
Так же для Safari (MacOS) существует отдельный кастомный плагин для Google Gears, который работает, только при запуске Safari в 32-bit режиме (Snow Leopard).
Здесь все прозрачно и просто, информация и примеры — огромное количество в интернете.
Подключаем gears_init.js.
Примеры использования Google Gears Sql
var connect = google.gears.factory.create(‘beta.database’);
connect.open(dbName);
var result = connect.execute(query, fields);
while (result.isValidRow()) <
var > result.next();
>
connect.close();
Примеры использование Google Gears Workers
var workerPool = google.gears.factory.create(‘beta.workerpool’);
var childWorkerId = workerPool.createWorkerFromUrl(‘worker.js’);
workerPool.onmessage = function(a, b, message) <
switch (message.body) <
case ‘EVENT_1’:
break;
case ‘EVENT_2’:
break;
default:
break;
>
>;
workerPool.sendMessage(
worker.js:
var worker = google.gears.workerPool
worker.onmessage = function(a, b, message) <
//event message.body.event
worker.sendMessage(‘EVENT_1’, message.sender);
>
HTML5 Web Sql Database
Поддержка HTML5 Web Sql Database показана в таблице ниже.
Основные критерии:
± поддержка Local Database,
± поддержка Web Workers
± поддержка Local Database из Web Worker
X — не проверялось
Chrome | Firefox | Safari | IE | |
Win | +++ | -+- | ++- | — |
MacOS | +++ | -+- | ++- | X |
iPad | X | X | +— | X |
Linux | +++ | -+- | X | X |
Внезапно появляется еще одна проблема — Web Sql Database работает асинхронно. Т.е. выполнить цепочку запросов просто так нельзя. Так же вы можете быть на 100% уверены, что когда выполнится следующий оператор после sql запроса, sql запрос еще не будет выполнен.
Есть несколько вариантов решений:
1) Выполнять вложенные действия. Т.е. мы выполняем sql, после выполнения вызывается callback функция, в которой мы делаем нужные нам действия. Не очень удобно.
2) Построить систему событий. При выполнении запроса, выбросить определенное событие, успешно его поймать и выполнить продолжение. Тоже не очень удобно.
Примеры использования Web Worker
var worker = new Worker(«worker.js»);
worker.onmessage = function (evt) <
switch (evt.data) <
case ‘EVENT_1’:
break;
default:
break;
>
>;
worker.onerror = function (evt) <
alert(‘error: ‘ + evt.data);
>;
onmessage = function (event) <
switch (event.data) <
case ‘START’:
break;
default:
break;
>
postMessage(‘EVENT_1’);
>;
Примеры использования Web Sql Database вне Web Worker
var connect = window.openDatabase(dbName, «1.0», «», 1024*1024*5);
connect.transaction(function(db) <
//Асинхронно
db.executeSql(«SELECT id FROM test», fields,
function(t, results) <
for (i = 0; i
Примеры использования Web Sql Database в Web Worker
var db = openDatabaseSync(‘db’, «1.0», «», 1024*1024*5);
db.transaction(function(db) <
//Синхронно
var result = db.executeSql(«SELECT id FROM test»);
for (var i = 0; i
Так же есть такая вот проблема в Chrome — жесткий лимит в 5 мб для БД, который на данный момент невозможно расширить обычными методами js.
По спецификации Chrome должен показать окно о превышении лимита в 5 мб и вопрос на разрешение увеличить его. Но… увы.
Я надеюсь, это вам поможет сэкономить немного драгоценного времени.
Под знаменем HTML 5
Java Script API: базы данных Web SQL
Стандарт и штандарт HTML 5
Об особенностях спецификации гипертекста HTML 5 мы уже писали ещё тогда, когда только появился первый черновик этого стандарта («КВ» №4’2008). Теперь же обратимся к остальным технологиям и начнём со встраиваемого в браузер языка JavaScript.
Язык JavaScript стал самостоятельной технологией, не привязанной только к работе с DOM-деревьями. Он описывается отдельным стандартом ECMAScript и применяется не только в браузерах, а, например, используется в Adobe Photoshop.
Что же касается браузеров, то следующим механизмом, в котором активно задействован JavaScript, явилась модная технология AJAX, которая позволяет в фоновом режиме обмениваться браузеру данными в XML-формате с сервером.
Но браузеры крутеют. В них появляются всё новые и новые механизмы и возможности. И скоро они станут настоящими операционными системами. Кроме механизма DOM и AJAX, новые браузеры обзаведутся следующими технологическими фишками:
А теперь после такого внушительного вступления можно перейти к каждой из перечисленных технологических новинок. Начнём со встроенных в браузеры системой управления базами данных Web SQL Database.
«All your base are belong to us»
Последние версии некоторых современных браузеров содержат в себе встроенные системы управления базами данных. На момент написания этой статьи к браузерам, поддерживающим Web SQL, относятся Chrome, Safari и Opera. Установив один из этих веб-обозревателей, можно на практике опробовать работу встроенных баз данных.
Наличие встроенных в браузер баз данных необходимо для разработки веб-приложений, работающих как онлайн, так и без подключения к Сети. Это одна из возможных замен технологии Gears, разрабатываемой ранее Google.
Веб-приложения могут использовать встроенные базы данных как хранилища табличных данных. Также на их основе можно создавать какие-либо оригинальные веб-приложения, например, браузерные календари, ежедневники. Тут уже всё зависит от фантазии программиста.
Каждый браузер создаёт для веб-приложения, использующего Web SQL Database, свою базу данных. И это следует учитывать. Поэтому для таких веб-приложений хороши, наверное, будут технологии виджетов Opera или же Adobe AIR.
API JavaScript Web SQL представляет набор прикладных программных интерфейсов для управления клиентской базой данных с помощью SQL. Или, другими словами, для доступа к встроенной СУБД используется «обёртка» из JavaScript вокруг SQL-запросов.
Создаём базу данных:
Вставляем в таблицу данные:
Выбираем из таблицы значение столбца data:
Для публичных сайтов, сервисов и веб-приложений системой управления базами данных Web SQL ещё рановато пользоваться. Нет поддержки всеми браузерами, да и интерфейс ещё может поменяться.
А вот для личного употребления, для личных веб-приложений Web SQL вполне по желанию можно употреблять.
WebSQL — реляционная база данных на веб-странице
WebSQL DB — это API для доступа к полноценному SQL-хранилищу данных, основанному на SQLite. Впрочем, последнее обстоятельство — скорее, особенность реализации и стандартом не оговаривается, хотя диалект SQL используется именно от SQLite. (Вообще, использование SQLite в веб-браузере — практика не новая: Firefox и Chrome давно применяют эту компактную СУБД для хранения настроек, паролей, закладок.)
Работает этот механизм так:
Var db = tpenDatabase(‘my_db’,’1.0′,’test’,2*1024*1024, function()< console. log(‘БД открыта!’)
Console. log(‘новая БД!’)
Код создает объект для взаимодействия с базой данных. Если БД с таким именем не существует, она будет создана. Аргументы метода следующие:
— объем БД (предполагаемый);
— функция обратного вызова, вызываемая при успешном открытии;
— функция обратного вызова, вызываемая при создании новой БД. Далее можно делать запросы, оборачивая их в транзакцию:
T. executeSql(‘SELECT title FROM documents’, [], function()< >);
Функция получает аргумент — объект транзакции (transaction object), вторым аргументом метода которого e xecuteSql (обязателен только первый — строка запроса) является массив аргументов для запроса, подставляемых в него вместо знаков ‘?’ (плейсхлодеров):
Чтение сохраненных значений производится из полей объекта набора значений, возвращаемого в результате соответствующего SQL-запроса:
T. exesuteSql(‘SELECT title FROM documents WHERE created
Web SQL Database
W3C Working Group Note 18 November 2010
Abstract
This specification defines an API for storing data in databases that can be queried using a variant of SQL.
Status of This Document
Beware. This specification is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the most recently formally published revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
This document is the 18 November 2010 Working Group Note of Web SQL Database. Publication as a Working Group Note does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress. The W3C Web Applications Working Group is the W3C working group responsible for this document.
This document was on the W3C Recommendation track but specification work has stopped. The specification reached an impasse: all interested implementors have used the same SQL backend (Sqlite), but we need multiple independent implementations to proceed along a standardisation path.
The Web Applications Working Group continues work on two other storage-related specifications: Web Storage and Indexed Database API.
Implementors should be aware that this specification is not stable. Implementors who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification should join the aforementioned mailing lists and take part in the discussions.
If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives) or whatwg@whatwg.org (subscribe, archives), or submit them using our public bug database. All feedback is welcome.
This specification is automatically generated from the corresponding section in the HTML5 specification’s source document, as hosted in the WHATWG Subversion repository. Detailed change history for all of HTML5, including the parts that form this specification, can be found at the following locations:
This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
Table of Contents
1 Introduction
This section is non-normative.
This specification introduces a set of APIs to manipulate client-side databases using SQL.
The API is asynchronous, so authors are likely to find anonymous functions (lambdas) very useful in using this API.
The executeSql() method has an argument intended to allow variables to be substituted into statements without risking SQL injection vulnerabilities:
Sometimes, there might be an arbitrary number of variables to substitute in. Even in these case, the right solution is to construct the query using only «?» characters, and then to pass the variables in as the second argument:
2 Conformance requirements
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words «MUST», «MUST NOT», «REQUIRED», «SHOULD», «SHOULD NOT», «RECOMMENDED», «MAY», and «OPTIONAL» in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
Requirements phrased in the imperative as part of algorithms (such as «strip any leading space characters» or «return false and abort these steps») are to be interpreted with the meaning of the key word («must», «should», «may», etc) used in introducing the algorithm.
Some conformance requirements are phrased as requirements on attributes, methods or objects. Such requirements are to be interpreted as requirements on user agents.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
The only conformance class defined by this specification is user agents.
User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.
When support for a feature is disabled (e.g. as an emergency measure to mitigate a security problem, or to aid in development, or for performance reasons), user agents must act as if they had no support for the feature whatsoever, and as if the feature was not mentioned in this specification. For example, if a particular feature is accessed via an attribute in a Web IDL interface, the attribute itself would be omitted from the objects that implement that interface — leaving the attribute on the object but making it return null or throw an exception is insufficient.
2.1 Dependencies
This specification relies on several other underlying specifications. HTML
Many fundamental concepts from HTML are used by this specification. [HTML]
The IDL blocks in this specification use the semantics of the WebIDL specification. [WEBIDL]
3 Terminology
The construction «a Foo object», where Foo is actually an interface, is sometimes used instead of the more accurate «an object implementing the interface Foo «.
The term DOM is used to refer to the API set made available to scripts in Web applications, and does not necessarily imply the existence of an actual Document object or of any other Node objects as defined in the DOM Core specifications. [DOMCORE]
An IDL attribute is said to be getting when its value is being retrieved (e.g. by author script), and is said to be setting when a new value is assigned to it.
The term «JavaScript» is used to refer to ECMA262, rather than the official term ECMAScript, since the term JavaScript is more widely known. [ECMA262]
4 The API
4.1 Databases
Each origin has an associated set of databases. Each database has a name and a current version. There is no way to enumerate or delete the databases available for an origin from this API.
Each database has one version at a time; a database can’t exist in multiple versions at once. Versions are intended to allow authors to manage schema changes incrementally and non-destructively, and without running the risk of old code (e.g. in another browser window) trying to write to a database with incorrect assumptions.
The method on the Window and WorkerUtils interfaces and the method on the WorkerUtils interface take the following arguments: a database name, a database version, a display name, an estimated size — in bytes — of the data that will be stored in the database, and optionally a callback to be invoked if the database has not yet been created. The callback, if provided, is intended to be used to call changeVersion() ; the callback is invoked with the database having the empty string as its version regardless of the given database version. If the callback is not provided, the database is created with the given database version as its version.
When invoked, these methods must run the following steps, with all but the last two steps being run atomically:
The user agent may raise a SECURITY_ERR exception instead of returning a Database object if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to open databases).
For the method on the Window object: let origin be the origin of the active document of the browsing context of the Window object on which the method was invoked.
For the methods on the WorkerUtils object: let origin be the origin of the scripts in the worker.
If origin is not a scheme/host/port tuple, then throw a SECURITY_ERR exception and abort these steps.
If no database with the given name from the origin origin exists, then create the database and let created be true. If a callback was passed to the method, then set the new database’s version to the empty string. Otherwise, set the new database’s version to the given database version.
Otherwise, if a database with the given name already exists, let created be false.
If created is false or if no callback was passed to the method, skip this step. Otherwise:
For the openDatabase() methods: queue a task to to invoke the callback with result as its only argument.
For the openDatabaseSync() method: invoke the callback with result as its only argument. If the callback throws an exception, rethrow that exception and abort these steps.
All strings including the empty string are valid database names. Database names must be compared in a case-sensitive manner.
Implementations can support this even in environments that only support a subset of all strings as database names by mapping database names (e.g. using a hashing algorithm) to the supported set of names.
The version that the database was opened with is the of this Database or DatabaseSync object. It can be the empty string, in which case there is no expected version — any version is fine.
User agents are expected to use the display name and the estimated database size to optimize the user experience. For example, a user agent could use the estimated size to suggest an initial quota to the user. This allows a site that is aware that it will try to use hundreds of megabytes to declare this upfront, instead of the user agent prompting the user for permission to increase the quota every five megabytes.
4.2 Parsing and processing SQL statements
Parse sqlStatement as a SQL statement, with the exception that U+003F QUESTION MARK characters (?) can be used in place of SQL literals in the statement. [SQL]
If the Database object that the SQLTransaction or SQLTransactionSync object was created from has an expected version that is neither the empty string nor the actual version of the database, then mark the statement as bogus. (Error code 2.)
Otherwise, if the mode that was used to create the SQLTransaction or SQLTransactionSync object is read-only but the statement’s main verb can modify the database, mark the statement as bogus. (Error code 5.)
The user agent must act as if the database was hosted in an otherwise completely empty environment with no resources. For example, attempts to read from or write to the file system will fail.
A future version of this specification will probably define the exact SQL subset required in more detail.
4.3 Asynchronous database API
The and methods takes one to three arguments. When called, these methods must immediately return and then asynchronously run the transaction steps with the transaction callback being the first argument, the error callback being the second argument, if any, the success callback being the third argument, if any, and with no preflight operation or postflight operation.
For the transaction() method, the mode must be read/write. For the readTransaction() method, the mode must be read-only.
On getting, the attribute must return the current version of the database (as opposed to the expected version of the Database object).
The method allows scripts to atomically verify the version number and change it at the same time as doing a schema update. When the method is invoked, it must immediately return, and then asynchronously run the transaction steps with the transaction callback being the third argument, the error callback being the fourth argument, the success callback being the fifth argument, the preflight operation being the following:
Check that the value of the first argument to the changeVersion() method exactly matches the database’s actual version. If it does not, then the preflight operation fails.
. and the mode being read/write.
If any of the optional arguments are omitted, then they must be treated as if they were null.
4.3.1 Executing SQL statements
When the method is invoked, the user agent must run the following algorithm. (This algorithm is relatively simple in that it doesn’t actually execute any SQL — the bulk of the work is actually done as part of the transaction steps.)
If the second argument is omitted or null, then treat the arguments array as empty.
Queue up the statement in the transaction, along with the third argument (if any) as the statement’s result set callback and the fourth argument (if any) as the error callback.
4.3.2 Processing model
The are as follows. These steps must be run asynchronously. These steps are invoked with a transaction callback, optionally an error callback, optionally a success callback, optionally a preflight operation, optionally a postflight operation, and with a mode that is either read/write or read-only.
Open a new SQL transaction to the database, and create a SQLTransaction object that represents that transaction. If the mode is read/write, the transaction must have an exclusive write lock over the entire database. If the mode is read-only, the transaction must have a shared read lock over the entire database. The user agent should wait for an appropriate lock to be available.
If an error occurred in the opening of the transaction (e.g. if the user agent failed to obtain an appropriate lock after an appropriate delay), jump to the last step.
If a preflight operation was defined for this instance of the transaction steps, run that. If it fails, then jump to the last step. (This is basically a hook for the changeVersion() method.)
If the transaction callback is not null, queue a task to invoke the transaction callback with the aforementioned SQLTransaction object as its only argument, and wait for that task to be run.
If the callback raised an exception, jump to the last step.
While there are any statements queued up in the transaction, perform the following steps for each queued up statement in the transaction, oldest first. Each statement has a statement, optionally a result set callback, and optionally an error callback.
If the statement is marked as bogus, jump to the «in case of error» steps below.
Execute the statement in the context of the transaction. [SQL]
If the statement failed, jump to the «in case of error» steps below.
Create a SQLResultSet object that represents the result of the statement.
If the statement has a result set callback that is not null, queue a task to invoke it with the SQLTransaction object as its first argument and the new SQLResultSet object as its second argument, and wait for that task to be run.
If the callback was invoked and raised an exception, jump to the last step in the overall steps.
Move on to the next statement, if any, or onto the next overall step otherwise.
In case of error (or more specifically, if the above substeps say to jump to the «in case of error» steps), run the following substeps:
If the statement had an associated error callback that is not null, then queue a task to invoke that error callback with the SQLTransaction object and a newly constructed SQLError object that represents the error that caused these substeps to be run as the two arguments, respectively, and wait for the task to be run.
If the error callback returns false, then move on to the next statement, if any, or onto the next overall step otherwise.
Otherwise, the error callback did not return false, or there was no error callback. Jump to the last step in the overall steps.
If a postflight operation was defined for this instance of the transaction steps, then: as one atomic operation, commit the transaction and, if that succeeds, run the postflight operation. If the commit fails, then instead jump to the last step. (This is basically a hook for the changeVersion() method.)
Otherwise: commit the transaction. If an error occurred in the committing of the transaction, jump to the last step.
Queue a task to invoke the success callback, if it is not null.
End these steps. The next step is only used when something goes wrong.
Queue a task to invoke the transaction’s error callback, if it is not null, with a newly constructed SQLError object that represents the last error to have occurred in this transaction. Rollback the transaction. Any still-pending statements in the transaction are discarded.
4.4 Synchronous database API
The and methods must run the following steps:
If the method was the transaction() method, create a SQLTransactionSync object for a read/write transaction. Otherwise, create a SQLTransactionSync object for a read-only transaction. In either case, if this throws an exception, then rethrow it and abort these steps. Otherwise, let transaction be the newly created SQLTransactionSync object.
If the first argument is null, rollback the transaction, throw a SQLException exception, and abort these steps. (Error code 0.)
Invoke the callback given by the first argument, passing it the transaction object as its only argument.
Mark the SQLTransactionSync object as stale.
If the callback was terminated by an exception, then rollback the transaction, rethrow that exception, and abort these steps.
Commit the transaction.
If an error occurred in the committing of the transaction, rollback the transaction, throw a SQLException exception, and abort these steps.
On getting, the attribute must return the current version of the database (as opposed to the expected version of the DatabaseSync object).
The method allows scripts to atomically verify the version number and change it at the same time as doing a schema update. When the method is invoked, it must run the following steps:
Create a SQLTransactionSync object for a read/write transaction. If this throws an exception, then rethrow it and abort these steps. Otherwise, let transaction be the newly created SQLTransactionSync object.
Check that the value of the first argument to the changeVersion() method exactly matches the database’s actual version. If it does not, then throw a SQLException exception and abort these steps. (Error code 2.)
If the third argument is not null, invoke the callback given by the third argument, passing it the transaction object as its only argument.
Mark the SQLTransactionSync object as stale.
If the callback was terminated by an exception, then rollback the transaction, rethrow the exception, and abort these steps.
Commit the transaction.
When the user agent is to for a transaction that is either read/write or read-only, it must run the following steps:
Open a new SQL transaction to the database, and create a SQLTransactionSync object that represents that transaction. If the mode is read/write, the transaction must have an exclusive write lock over the entire database. If the mode is read-only, the transaction must have a shared read lock over the entire database. The user agent should wait for an appropriate lock to be available.
If an error occurred in the opening of the transaction (e.g. if the user agent failed to obtain an appropriate lock after an appropriate delay), throw a SQLException exception and abort these steps.
Return the newly created SQLTransactionSync object.
4.4.1 Executing SQL statements
A SQLTransactionSync object is initially fresh, but it will be marked as stale once it has been committed or rolled back.
When the method is invoked, the user agent must run the following algorithm:
If the SQLTransactionSync object is stale, then throw an INVALID_STATE_ERR exception.
If the second argument is omitted or null, then treat the arguments array as empty.
If the statement is marked as bogus, throw a SQLException exception.
Execute the statement in the context of the transaction. [SQL]
If the statement failed, throw a SQLException exception.
Create a SQLResultSet object that represents the result of the statement.
Return the newly created SQLResultSet object.
4.5 Database query results
The executeSql() method invokes its callback with a SQLResultSet object as an argument.
The attribute must return the row ID of the row that the SQLResultSet object’s SQL statement inserted into the database, if the statement inserted a row. If the statement inserted multiple rows, the ID of the last row must be the one returned. If the statement did not insert a row, then the attribute must instead raise an INVALID_ACCESS_ERR exception.
The attribute must return the number of rows that were changed by the SQL statement. If the statement did not affected any rows, then the attribute must return zero. For «SELECT» statements, this returns zero (querying the database doesn’t affect any rows).
The attribute must return a SQLResultSetRowList representing the rows returned, in the order returned by the database. The same object must be returned each time. If no rows were returned, then the object will be empty (its length will be zero).
For the asynchronous API, implementors are encouraged to prefetch all the data for SQLResultSetRowList objects when the object is constructed (before the result set callback is invoked), rather than on-demand, for better responsiveness. For the synchronous API, an on-demand lazy evaluation implementation strategy is encouraged instead, for better performance.
Fetching the length might be expensive, and authors are thus encouraged to avoid using it (or enumerating over the object, which implicitly uses it) where possible.
4.6 Errors and exceptions
Errors in the asynchronous database API are reported using callbacks that have a SQLError object as one of their arguments.
The IDL attribute must return the most appropriate code from the table below.
The IDL attribute must return an error message describing the error encountered. The message should be localized to the user’s language.
Errors in the synchronous database API are reported using SQLException exceptions:
The IDL attribute must return the most appropriate code from the table below.
The IDL attribute must return an error message describing the error encountered. The message should be localized to the user’s language.
5 Web SQL
User agents must implement the SQL dialect supported by Sqlite 3.6.19.
When converting bound arguments to SQL data types, the JavaScript ToPrimitive abstract operation must be applied to obtain the raw value to be processed. [ECMA262].
6 Disk space
User agents should limit the total amount of space allowed for databases.
User agents should guard against sites storing data under the origins other affiliated sites, e.g. storing up to the limit in a1.example.com, a2.example.com, a3.example.com, etc, circumventing the main example.com storage limit.
User agents may prompt the user when quotas are reached, allowing the user to grant a site more space. This enables sites to store many user-created documents on the user’s computer, for instance.
User agents should allow users to see how much space each domain is using.
A mostly arbitrary limit of five megabytes per origin is recommended. Implementation feedback is welcome and will be used to update this suggestion in the future.
7 Privacy
7.1 User tracking
A third-party advertiser (or any entity capable of getting content distributed to multiple sites) could use a unique identifier stored in its client-side databases to track a user across multiple sessions, building a profile of the user’s interests to allow for highly targeted advertising. In conjunction with a site that is aware of the user’s real identity (for example an e-commerce site that requires authenticated credentials), this could allow oppressive groups to target individuals with greater accuracy than in a world with purely anonymous Web usage.
There are a number of techniques that can be used to mitigate the risk of user tracking: Blocking third-party storage
Expiring stored data
User agents may, if so configured by the user, automatically delete stored data after a period of time.
This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when he authenticates with the site itself (e.g. by making a purchase or logging in to a service).
However, this also reduces the usefulness of the API as a long-term storage mechanism. It can also put the user’s data at risk, if the user does not fully understand the implications of data expiration.
Treating persistent storage as cookies
If users attempt to protect their privacy by clearing cookies without also clearing data stored in the relevant databases, sites can defeat those attempts by using the two features as redundant backup for each other. User agents should present the interfaces for clearing these in a way that helps users to understand this possibility and enables them to delete data in all persistent storage features simultaneously. [COOKIES]
Site-specific white-listing of access to databases
User agents may require the user to authorize access to databases before a site can use the feature.
Origin-tracking of stored data
User agents may record the origins of sites that contained content from third-party origins that caused data to be stored.
If this information is then used to present the view of data currently in persistent storage, it would allow the user to make informed decisions about which parts of the persistent storage to prune. Combined with a blacklist («delete this data and prevent this domain from ever storing data again»), the user can restrict the use of persistent storage to sites that he trusts.
User agents may allow users to share their persistent storage domain blacklists.
This would allow communities to act together to protect their privacy.
While these suggestions prevent trivial use of this API for user tracking, they do not block it altogether. Within a single domain, a site can continue to track the user during a session, and can then pass all this information to the third party along with any identifying information (names, credit card numbers, addresses) obtained by the site. If a third party cooperates with multiple sites to obtain such information, a profile can still be created.
However, user tracking is to some extent possible even with no cooperation from the user agent whatsoever, for instance by using session identifiers in URLs, a technique already commonly used for innocuous purposes but easily repurposed for user tracking (even retroactively). This information can then be shared with other sites, using using visitors’ IP addresses and other user-specific data (e.g. user-agent headers and configuration settings) to combine separate sessions into coherent user profiles.
7.2 Sensitivity of data
User agents should treat persistently stored data as potentially sensitive; it’s quite possible for e-mails, calendar appointments, health records, or other confidential documents to be stored in this mechanism.
To this end, user agents should ensure that when deleting data, it is promptly deleted from the underlying storage.
8 Security
8.1 DNS spoofing attacks
Because of the potential for DNS spoofing attacks, one cannot guarantee that a host claiming to be in a certain domain really is from that domain. To mitigate this, pages can use TLS. Pages using TLS can be sure that only pages using TLS that have certificates identifying them as being from the same domain can access their databases.
8.2 Cross-directory attacks
Even if a path-restriction feature was made available, the usual DOM scripting security model would make it trivial to bypass this protection and access the data from any path.
8.3 Implementation risks
The two primary risks when implementing these persistent storage features are letting hostile sites read information from other domains, and letting hostile sites write information that is then read from other domains.
Letting third-party sites read data that is not supposed to be read from their domain causes information leakage, For example, a user’s shopping wishlist on one domain could be used by another domain for targeted advertising; or a user’s work-in-progress confidential documents stored by a word-processing site could be examined by the site of a competing company.
Letting third-party sites write data to the persistent storage of other domains can result in information spoofing, which is equally dangerous. For example, a hostile site could add items to a user’s wishlist; or a hostile site could set a user’s session identifier to a known ID that the hostile site can then use to track the user’s actions on the victim site.
Thus, strictly following the origin model described in this specification is important for user security.
8.4 SQL and user agents
User agent implementors are strongly encouraged to audit all their supported SQL statements for security implications. For example, LOAD DATA INFILE is likely to pose security risks and there is little reason to support it.
In general, it is recommended that user agents not support features that control how databases are stored on disk. For example, there is little reason to allow Web authors to control the character encoding used in the disk representation of the data, as all data in JavaScript is implicitly UTF-16.
8.5 SQL injection
References
All references are normative unless marked «Non-normative».