This document discusses using the Drupal database API to interact with the database in Drupal. It covers the basics of db_query and dynamic queries using db_select. It discusses how to add conditions, joins, sorting, and other clauses to dynamic queries. It also covers how to work with result sets and how to perform inserts, updates, and deletes using the API. Finally, it discusses when to use the database API versus views and provides a case study comparing the two approaches.
PHP Data Objects (PDO) provides a clear, simple (but powerful), unified API for working with all our favorite databases. Features include prepared statements with bound parameters (for all databases, even those that don’t natively support them), transactions, cursors, LOBs, and flexible error handling.
PHP Data Objects (PDO) provides a clear, simple (but powerful), unified API for working with all our favorite databases. Features include prepared statements with bound parameters (for all databases, even those that don’t natively support them), transactions, cursors, LOBs, and flexible error handling.
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
Your code sucks, let's fix it - DPC UnConRafael Dohms
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
Caching and Scaling WordPress using Fragment CachingErick Hitter
Using what I’ve learned working on the WordPress.com VIP platform, this presentation discusses caching techniques applicable to WordPress installations of almost any size.
Presented February 18, 2012 at WordCamp Miami.
Original HTML5 slides are available at http://www.ethitter.com/2012/02/caching-and-scaling-wcmia/.
https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
This session introduces most well known design patterns to build PHP classes and objects that need to store and fetch data from a relational databases. The session will describe the difference between of the Active Record, the Table and Row Data Gateway and the Data Mapper pattern. We will also examine some technical advantages and drawbacks of these implementations. This talk will expose some of the best PHP tools, which ease database interactions and are built on top of these patterns.
Persistence is one of the most important part in a PHP project. Persisting data to a database came with PHP/FI and its MySQL support. From native extensions and PHP4 database abstraction libraries to PDO and modern ORM frameworks, you will (re)discover how persistence has evolved during the last decade. This talk will also introduce the future of data persistence with the growing success of alternative storage engines.
Lithium: The Framework for People Who Hate FrameworksNate Abele
This is the presentation was given at ConFoo on March 11th by Nate Abele and Joël Perras, and is an introduction to the architectural problems with other frameworks that Lithium was designed to address, and how it addresses them. It also introduces programming paradigms like functional and aspect-oriented programming which address issues that OOP doesn't account for.
Finally, the talk provides a quick overview of the innovative and unparalleled features that Lithium provides, including the data layer, which supports both relational and non-relational databases.
Your code sucks, let's fix it - DPC UnConRafael Dohms
How do you measure the quality of your code? Performance and testing are just one aspect of code, in order to meet deadlines and make maintenance quicker you also need your code to be readable, decoupled and generally easier to comprehend and work with. This talk will go over tips and exercises to help you identify trouble areas, refactor them and train you to write better code in future projects. Come make your code look and function better.
Caching and Scaling WordPress using Fragment CachingErick Hitter
Using what I’ve learned working on the WordPress.com VIP platform, this presentation discusses caching techniques applicable to WordPress installations of almost any size.
Presented February 18, 2012 at WordCamp Miami.
Original HTML5 slides are available at http://www.ethitter.com/2012/02/caching-and-scaling-wcmia/.
https://speakerdeck.com/willroth/50-laravel-tricks-in-50-minutes - origin
Laravel 5.1 raised the bar for framework documentation, but there's much, much more lurking beneath the surface. In this 50-minute session, we'll explore 50 (yes, 50!) high-leverage implementation tips & tricks that you just won't find in the docs: the IoC Container, Blade, Eloquent, Middleware, Routing, Commands, Queues, Events, Caching — we'll cover them all! Join us as we drink from the fire hose & learn to take advantage of everything that Laravel has to offer to build better software faster!
Design Patterns avec PHP 5.3, Symfony et PimpleHugo Hamon
Cette conférence présente deux grands motifs de conception : l'observateur et l'injection de dépendance. Ce sujet allie à la fois théorie et pratique. Le composant autonome EventDispatcher de Symfony ainsi que le conteneur d'injection de dépendance Pimple sont mis à l'honneur avec des exemples pratiques d'usage. Ces cas pratiques combinent du code de l'ORM Propel ainsi que le composant autonome Zend\Search\Lucene du Zend Framework 2
Italy shouldn't get all the credit.. Van Eyck figured out how to do oil painting (or at least perfect it) and realism started here in Flanders.
For Ms. Fuentes AP Art History Class
An overview of the main questions/design issues when starting to work with databases in Perl
- choosing a database
- matching DB datatypes to Perl datatypes
- DBI architecture (handles, drivers, etc.)
- steps of DBI interaction : prepare/execute/fetch
- ORM principles and difficulties, ORMs on CPAN
- a few examples with DBIx::DataModel
- performance issues
First given at YAPC::EU::2009 in Lisbon. Updated version given at FPW2011 in Paris and YAPC::EU::2011 in Riga
This is the eleventh set of slightly updated slides from a Perl programming course that I held some years ago.
I want to share it with everyone looking for intransitive Perl-knowledge.
A table of content for all presentations can be found at i-can.eu.
The source code for the examples and the presentations in ODP format are on https://github.com/kberov/PerlProgrammingCourse
Drupal isn't a content management system. It's an application development platform that happens to ship with a great CMS as it's default implementation. Look at any chart comparing features of development frameworks and you'll see user management and authentication, forms management and validation, data storage, database migrations, internationalization and translation, MVC model with flexible templating, unit testing, and caching. Sounds a lot like Drupal. We'll look at why Drupal is an ideal application development platform for apps beyond content management, talk about where Drupal can improve in these areas, and look at an example application.
Slow Database in your PHP stack? Don't blame the DBA!Harald Zeitlhofer
Your users complain about the bad performance of your app or website? Developers blame the database? How can we find the cause for the performance hotspot?
Far too often the database is held responsible for performance or scalability problems. It seems to be main contributor to the overall web request response time. However, in many cases it’s not the database itself, but the way, how the application is using the database! Too many database statements, inefficient queries and poor index selection are among the common problem patterns.
Based on real life examples, you will learn how to approach performance problems, how to figure out if the database is really to blame and how to end the finger pointing between developers and DBAs.
Slides from my talk at PHP conference Asia 2016 in Singapore
Redis is a NoSQL technology that rides a fine line between database and in-memory cache. Redis also offers "remote data structures", which gives it a significant advantage over other in-memory databases. This session will cover several PHP clients for Redis, and how to use them for caching, data modeling and generally improving application throughput.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
GridMate - End to end testing is a critical piece to ensure quality and avoid...ThomasParaiso2
End to end testing is a critical piece to ensure quality and avoid regressions. In this session, we share our journey building an E2E testing pipeline for GridMate components (LWC and Aura) using Cypress, JSForce, FakerJS…
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
1. Drupal II: The SQL
David Diers, Developer
Four Kitchens
Austin, TX
D.O - thebruce
@beautyhammer
2. What we’ll cover
Basics of the Drupal DB API
Using db_query
Using and building dynamic queries including
Criteria clauses, joins, sorting, sub-
selects, extenders, and tagging
How to work with result sets
3. Drupal and the DB
Drupal uses the DB to:
Store content - where
"content" is thought of very
broadly.
Store user or module
configurations
Store system values
Drupal retrieves these values
all of the time.
4. Drupal and DB Abstraction
What is DB Abstraction?
A way of uniformly interacting and leveraging
SQL commands with multiple types of database
products.
A structured way of dynamically constructing
SQL statements
DB Abstraction is nothing new for Drupal
5. Drupal 7 DB API uses PDO
In D7 the DB Abstraction layer got a face-lift
Built on PDO
PDO is PHPOOP
Drupal extends PDO classes
PDO used in many projects
6. Why learn the DB API?
Isn‟t most of this stuff in functions already?
Doesn‟t views do this for me?
Can‟t I just use raw SQL like they did in ye olde
days ™?
7. Why Learn the DB API?
Need a result set that you can‟t get or requires custom
views development?
Writing or supporting custom modules with their own
schema?
Need results from the contrib module‟s schema but there
isn‟t a function to do so?
Patching an existing modules‟ database functionality?
Need additional ways besides features, views, panels to
transfer configuration via update hooks?
Need to implement custom sql statements to improve the
performance of your site?
8. Using the DB API
2 Primary ways to interact with data in D7
dbquery – performant, limited transferability.
Dynamic queries - more complex, high
transferability, powerful, less performant.
9. db_query – the basics
IN SQL: IN db_query:
<?php
SELECT nid, title $type = „article‟;
FROM node $result = db_query("SELECT nid, title
WHERE type = „article‟; FROM {node} WHERE type =
:type", array(':type' => $type,));
10. db_query – the breakdown
$result = db_query("SELECT nid, title FROM {node} WHERE type = :type",
array(':type' => $type,));
db_query($query, $placeholders, $options)
enclose tables in { }
Placeholders start with ":"
EX: WHERE type = :type", array(':type' => 'page',))
Options array - 2 common ones are:
Target (default or slave)
Fetch (pdo fetch type)
http://druptest7.dev:8888/example_dbq
11. db_query d6 => d7
transitions
In transitioning D6 db_query to D7 be aware:
The syntax signature has changed –
• D6 parameters were the $query, followed by a
variable number of arguments or an array of query
substitutions.
• % syntax for placeholders
• Varied sql commands executed via db_query.
12. Dynamic sql – the basics
Dynamic Queries
Much more transportable.
You MUST use for (
INSERT, UPDATE, DELETE)
You may use for (SELECT)
• http://www.lullabot.com/articles/simplify-your-code-
with-drupal-7s-database-api ).
13. db_select – the basics
IN SQL: IN db_select:
<?php
SELECT nid, title $type = „article‟;
FROM node $query = db_select(„node‟, ‟n‟);
WHERE type = „article‟; $result = $query->fields(„n‟,
array(„nid‟,‟title‟)
->condition(„n.type‟,$type)
->execute();
14. db_select – the basics
(„node‟, „n‟) IN db_select:
Name of Table / Alias <?php
$type = „article‟;
(fields(„n‟, array(„nid‟, $query = db_select(„node‟, ‟n‟);
„title‟))
$result = $query->fields(„n‟,
array(„nid‟,‟title‟)
Alias, array of fields ->condition(„n.type‟,$type)
->execute();
Single quotes are
important for
transferability.
15. Dynamic Queries – of note
$query = db_select(„node‟, ‟n‟);
$result = $query->fields(„n‟, array(„nid‟,‟title‟)
->condition(„n.type‟,$type)
->execute();
Fluid Interface - allows method chaining
Query statements are executed by ->execute(); easy
to forget, but don't.
You‟ll get back a result set / statement object
16. Working with Result Sets
Use - foreach loop or
or - Specificaly get the next record
$record = $result->fetch(); // Use the default fetch
mode.
$record = $result->fetchObject(); // Fetch as a
stdClass object.
$record = $result->fetchAssoc(); // Fetch as an
associative array.
or - to get a single field
$record = $result->fetchField($column_index);
17. Which should I use?
Is your query static? Use db_query it is faster.
Does your query need to be constructed at run
time? Use dynamic queries
Do you need to INSERT, UPDATE, or DELETE?
Use Dynamic queries.
Are you querying the node table – Use Dynamic
queries to respect node access.
18. More with Dynamic Queries
How to add fields or select *
Conditional Statements
AND / OR
Sub-selects
JOINS
SORT
19. Fields and db_select
Adding fields to a query:
$query->fields('n', array('nid', 'title', 'created', 'uid'));
"select *" is fields with no field array indicated:
$query->fields('n');
http://druptest7.dev:8888/example_dyn
20. Conditional Statements
Signature: $query->condition($field, $value = NULL,
$operator = '=')
Default operator is SQL =
can take ANSI sql comparators <, >, LIKE, = >=
EX: $query->condition('nid',1)
EX: $query->condition('nid',1, '<>')
In or between:
EX: $query->condition('myfield', array(1, 2, 3), 'IN');
21. Conditional Statements
(more)
Nested Conditionals:
db_and() / db_or() / db_xor() are used to handle
nested conditionals such as:
->condition(db_or()
->condition('field2', 5)
->condition('field3', 6))
Testing for NULL:
$query->isNull('myfield');
$query->isNotNull('myfield');
22. An example from the field…
Original query:
$result = db_query('SELECT * FROM {users}
WHERE ((access <> 0 AND login <> 0 AND access
< (%d - %d)) OR (login = 0 AND created < (%d -
%d))) AND uid <> 1', REQUEST_TIME, $warn_time,
REQUEST_TIME, $warn_time);
24. Subselects
Subselects - form a query using dbtng then instead
of executing it -
use that query variable in a condition.
Most successful when one value is returned,
or a one column return value is used with an IN
clause.
$query->condition('myfield', $querysubselect, 'IN');
27. db_select Tagging
Tagging – lets alter hooks take action
ex: $query->addTag('node_access'); - this should be
implemented on all queries that retrieve nodes.
Node access query alter will then check to see if a
user can see the nodes in the result.
(http://druptest7.dev:8888/example_tag)
28. What about the others?
db_update, db_insert, db_delete
Similar syntax
Assemble and execute.
29. db_insert
Syntax: $query = db_insert('node', $options);
$nid = db_insert('node')
->fields(array(
'title' => ‟This Example',
'uid' => 1,
'created' => REQUEST_TIME,
))
->execute();
db_insert returns the auto-increment value defined by
hook_schema.
(http://druptest7.dev:8888/example_insert)
31. db_delete
Signature: $query = db_delete('node', $options);
$num_deleted = db_delete('node')
->condition('nid', 5)
->execute();
db_delete returns the number of rows deleted.
http://druptest7.dev:8888/example_delete
32. db_select extenders
Extenders - implements a decorator pattern, currently only two in core
TableSort and PagerQuery = adds the methods for these extension to
query
example:
$query = $query
->extend('TableSort')
->orderByHeader($header);
Put these near the start.
Not chainable, if you forget to return it to itself it will have odd results.
http://druptest7.dev:8888/example_extend
34. What is the ?
Now that you have Drupal DB Chops
You may start to consider…
To VIEWS or
not to
VIEWS
35. DB API an Alternative to
Views
Who will maintain the functionality?
Does it require a lot of custom views code?
Are you doing a lot of aggregated data work?
Do you need a highly tuned SQL statement for performance?
Do you need a lot of user facing, non programmer modifications,
will site builders be cloning views or modifying displays?
Are you integrating with other modules (panels, voting, etc)?
How complex are the changes you need to views default
queries/output?
To views or not to views (http://drupal.org/node/242311 )
36. Quick case study:
• Client wanted private comments
• Client wanted to see a listing of all comments
made against all nodes
• Views can do this but it is described as “hacky”
• Created a db_select with pager and table
extenders
37. Questions and Thank you!
David Diers, Developer
Four Kitchens
david.diers@fourkitchens.com
D.O - thebruce
@beautyhammer
Editor's Notes
Content – nodes, entitiesconfig - administrator, moduleconfiguraton, or user based configuration settingssystem – logs (watchdog), sessions, queue to be processed at next cron, class hashes
What is DB Abstraction?-> db implementations vary from product to product, ANSI sql implementations vary widelyDB Abstraction is nothing new – Just the way it is done.
It was built on PDO – PHP Data ObjectsPDO is written in PHPOOPDrupal implements extensions or interfaces of PDO classesPDO is in wide use across many projects (Symfony, Zend Framework, Magento)
2 Primary ways to interact with data in D7dbquery - performant but limited transferability.Dynamic queries - more complex, high transferability, powerful, less performant.
Let’s use this simple query of the node table
enclose tables in { } for db prefixarg 2 - use placeholders to avoid sql injection, start with ":"EX: WHERE type = :type", array(':type' => 'page',))arg3 – options array - 2 common ones are:target - default or slavefetch - pdo fetch type (the select statement will return into the fetch type specified. Can and should use object(default), assoc array, or a string class name.
In transitioning D6 db_query to D7 be aware:The syntax signature has changed –D6 took a single parameter – the $query, followed by a variable number of arguments or an array of query substitutions.D6 used the % syntax for placeholders instead of the “:” syntax.Functions other than select could be executed via db_query.
Let’s use this simple query of the node table
Let’s use this simple query of the node table
$query = db_select(‘node’, ’n’);$result = $query->fields(‘n’, array(‘nid’,’title’) ->condition(‘n.type’,$type) ->execute;Fluid Interface - allows chaining (because the results of each chainable method return an instance of the object itself)Not all methods are chainable so consult your documentation.$result = $query->execute();Query statements are executed by ->execute(); easy to forget, but don't.You’ll get back a result set / statement objectforeach ($result as $record) { //do something
Tagging - any dynamic select query can be tagged with one or more strings which then allows alter hooks to determine if they need to take action.Via hook_query_alter & hook_query_TAG_alterex: $query->addTag('node_access'); - this should be implemented on all queries that retrieve nodes.Node access query alter will then check to see if a user can see the nodes in the result.
Extenders - implements a decorator pattern, currently only two in coreDecorator pattern – allows the “decoration” of a classes functionality at run time, allowing you to change a single instance of a class with a set of functionalityTableSort and PagerQuery = adds the methods for these extension to queryexample:$query = $query->extend('TableSort')->orderByHeader($header);Put these near the start.Not chainable, if you forget to return it to itself it will have odd results.