Ir al contenido

Una consulta con parámetros ​

Traducción automática

Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.

Tarea: listar los productos cuyo nombre contiene lo que pide la URL (/?name=mouse), de forma segura.

yaml
# Recipe: a query that takes a value from the URL, bound as a parameter.
paths:
  components: ./components
  migrations: ./migrations

datasources:
  db:
    driver: sqlite
    database: ./data/shop.db
sql
CREATE TABLE products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    price REAL NOT NULL
);

INSERT INTO products (name, price) VALUES
    ('Notebook', 3500.0), ('Mouse', 80.0), ('Monitor', 1200.0), ('Mousepad', 25.0);

Cada :name del SQL se vincula al q:param del mismo nombre: el valor va a la base de datos separado del texto SQL, convertido antes por su type. Un :name sin q:param no pasa el análisis, así que no hay forma de pegar un valor en el SQL por accidente.

xml
<q:component name="Products">
  <!-- ?name=mouse from the URL; empty when it is not there. -->
  <q:set name="term" value="{query.name}" default="" />

  <!-- :pattern is bound to the q:param: the value is sent to the database
       apart from the SQL, so it can never change what the SQL does. -->
  <q:query name="products" datasource="db">
    SELECT name, price FROM products WHERE name LIKE :pattern ORDER BY price
    <q:param name="pattern" value="%{term}%" type="string" />
  </q:query>

  <ui:window title="Products">
    <ui:text>{products_result.recordCount} products</ui:text>
    <ui:table source="{products}">
      <ui:column key="name" label="Name" />
      <ui:column key="price" label="Price" />
    </ui:table>
  </ui:window>
</q:component>

La última prueba envía SQL en la URL. Es solo un texto a buscar: ningún producto lo tiene en su nombre, y la tabla queda intacta.

xml
<q:test name="without a filter, every product" page="/">
  <test:visit />
  <test:expect text="4 products" />
  <test:expect text="Notebook" />
</q:test>

<q:test name="the value from the URL filters" page="/">
  <test:visit name="mouse" />
  <test:expect text="2 products" />
  <test:expect text="Mousepad" />
  <test:expect no-text="Monitor" />
</q:test>

<q:test name="SQL in the URL is only text to search for" page="/">
  <test:visit name="' OR '1'='1" />
  <test:expect text="0 products" />
  <test:expect table="products" count="4" />
</q:test>
text
tests/products.test.q
  PASS  without a filter, every product
  PASS  the value from the URL filters
  PASS  SQL in the URL is only text to search for
3 passed, 0 failed

Ver DB-1.

Licencia MIT · Hecho con VitePress