Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -205,11 +205,11 @@ Mount before WP install: /wordpress ->
The database location depends on what you mount:

- **Auto-mounting wp-content or full WordPress**:
- Database: `<your-local-project>/wp-content/database/.ht.sqlite`
- Database directory: `<your-local-project>/wp-content/database/`
- ✅ **Persisted locally** in your project folder

- **Auto-mounting plugin/theme only**:
- Database: `<OS-TEMP-DIR>/playground-<id>/wordpress/wp-content/database/.ht.sqlite`
- Database directory: `<OS-TEMP-DIR>/playground-<id>/wordpress/wp-content/database/`
- ⚠️ **Lost when server stops** (temp directories are cleaned up)

- **Custom mounts**: Database location follows your mount configuration
Expand Down Expand Up @@ -254,7 +254,7 @@ project directory.
The database location depends on your configuration:

- **Default (automatic persistence)**:
- Database: `~/.wordpress-playground/sites/<path-hash>/wordpress/wp-content/database/.ht.sqlite`
- Database directory: `~/.wordpress-playground/sites/<path-hash>/wordpress/wp-content/database/`
- **Persisted automatically** between sessions
- **Full WordPress directory or explicit `/wordpress` mount**:
- Database: Follows the mounted WordPress directory
Expand Down
2 changes: 1 addition & 1 deletion packages/docs/site/docs/main/quick-start-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ Open **Export** from the Dock and use **Download as .zip**.

The exported file contains the current files, database, plugins, themes, uploads, and edits. You can restore it in Playground or host it on a server that supports PHP and SQLite.

The SQLite database file is included at `wp-content/database/.ht.sqlite`. Files starting with a dot are hidden by default on most operating systems, so you may need to enable hidden files in your file manager.
The SQLite database is included in `wp-content/database/`. When this directory contains `db-path.php`, that file returns the database path inside a randomized subdirectory. Older sites use `wp-content/database/.ht.sqlite`. Keep the whole `database` directory together when copying a site. Files starting with a dot are hidden by default on most operating systems, so you may need to enable hidden files in your file manager.

## Restore a ZIP

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@ import { Button, Icon, Flex, FlexItem } from '@wordpress/components';
import { download } from '@wordpress/icons';
import type { PlaygroundClient } from '@wp-playground/client';

const DATABASE_PATH = '/wordpress/wp-content/database/.ht.sqlite';

async function downloadDatabase(playground: PlaygroundClient): Promise<void> {
const fileExists = await playground.fileExists(DATABASE_PATH);
async function downloadDatabase(
playground: PlaygroundClient,
databasePath: string
): Promise<void> {
const fileExists = await playground.fileExists(databasePath);
if (!fileExists) {
throw new Error('Database file does not exist');
}

const buffer = await playground.readFileAsBuffer(DATABASE_PATH);
const buffer = await playground.readFileAsBuffer(databasePath);
const blob = new Blob([new Uint8Array(buffer)], {
type: 'application/x-sqlite3',
});
Expand All @@ -25,15 +26,19 @@ async function downloadDatabase(playground: PlaygroundClient): Promise<void> {

export function DownloadButton({
playground,
databasePath,
}: {
playground: PlaygroundClient | undefined;
databasePath: string | null;
}) {
return (
<Button
variant="secondary"
disabled={!playground}
disabled={!playground || !databasePath}
onClick={
playground ? () => downloadDatabase(playground) : undefined
playground && databasePath
? () => downloadDatabase(playground, databasePath)
: undefined
}
>
<Flex justify="space-between" gap={2} expanded={true}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,46 +1,62 @@
import { useState, useEffect } from 'react';
import type { PlaygroundClient } from '@wp-playground/client';
import {
getSqliteDatabasePath,
getSqliteDatabaseSize,
} from '@wp-playground/tools';
import { Notice, __experimentalVStack as VStack } from '@wordpress/components';
import { DownloadButton } from './download-button';
import { AdminerButton } from './adminer-button';
import { PhpMyAdminButton } from './phpmyadmin-button';
import css from './style.module.css';
import { formatBytes } from '../../../lib/utils/format-bytes';

const DATABASE_PATH = '/wordpress/wp-content/database/.ht.sqlite';

export function SiteDatabasePanel({
playground,
isBooting,
}: {
playground: PlaygroundClient | undefined;
isBooting: boolean;
}) {
const [databasePath, setDatabasePath] = useState<string | null>(null);
const [databaseSize, setDatabaseSize] = useState<number | null>(null);
const [isLoading, setIsLoading] = useState(isBooting || !!playground);

useEffect(() => {
setDatabasePath(null);
setDatabaseSize(null);
setIsLoading(isBooting || !!playground);
if (!playground) {
setDatabaseSize(null);
return;
}

let cancelled = false;

async function fetchDatabaseSize() {
if (!playground) return;

try {
const fileExists = await playground.fileExists(DATABASE_PATH);
const path = await getSqliteDatabasePath(playground);
if (cancelled) return;
setDatabasePath(path);
const fileExists = await playground.fileExists(path);
if (fileExists) {
const buffer =
await playground.readFileAsBuffer(DATABASE_PATH);
setDatabaseSize(buffer.byteLength);
} else {
setDatabaseSize(null);
const size = await getSqliteDatabaseSize(playground, path);
if (cancelled) return;
setDatabaseSize(size);
}
} catch {
setDatabaseSize(null);
if (!cancelled) setDatabaseSize(null);
} finally {
if (!cancelled) setIsLoading(false);
}
}

void fetchDatabaseSize();
}, [playground]);
return () => {
cancelled = true;
};
}, [playground, isBooting]);

return (
<VStack spacing={4}>
Expand Down Expand Up @@ -83,7 +99,10 @@ export function SiteDatabasePanel({
</span>
<span className={css.label}>SQLite database path:</span>
<span className={css.value}>
<code>{DATABASE_PATH}</code>
<code>
{databasePath ??
(isLoading ? 'Loading…' : 'Unavailable')}
</code>
</span>
{databaseSize !== null && (
<>
Expand All @@ -97,7 +116,10 @@ export function SiteDatabasePanel({
</VStack>

<div className={css.buttonGroup}>
<DownloadButton playground={playground} />
<DownloadButton
playground={playground}
databasePath={databasePath}
/>
<AdminerButton playground={playground} />
<PhpMyAdminButton playground={playground} />
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { updateSiteMetadata } from '../../../lib/state/redux/slice-sites';
import type { SiteMetadata } from '../../../lib/state/redux/slice-sites';
import { setSiteManagerOpen } from '../../../lib/state/redux/slice-ui';
import {
selectActiveSiteError,
useActiveSite,
useAppDispatch,
useAppSelector,
Expand Down Expand Up @@ -782,6 +783,7 @@ export function SiteInfoPanel({
clientInfo && !clientInfo.isDependentMode
? clientInfo.client
: undefined;
const bootError = useAppSelector(selectActiveSiteError);

// Resolve documentRoot from playground, or use fallback for direct OPFS access
useEffect(() => {
Expand Down Expand Up @@ -1011,6 +1013,9 @@ export function SiteInfoPanel({
>
<SiteDatabasePanel
playground={playground}
isBooting={
!clientInfo && !bootError
}
/>
</div>
<div
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
// @vitest-environment jsdom

import { playgroundAvailableInOpfs } from './boot-site-client';

// Avoid initializing the application store through boot dependencies.
vi.mock('./store', () => ({}));

describe('playgroundAvailableInOpfs', () => {
it.each([
['db-path.php', true],
['.ht.sqlite', true],
[undefined, false],
])(
'detects a site with database file %s',
async (databaseFile, expected) => {
const directory = {
async *keys() {
yield 'wp-config.php';
},
async getDirectoryHandle() {
return directory;
},
async getFileHandle(name: string) {
if (name !== 'wp-config.php' && name !== databaseFile) {
throw new DOMException('Missing file', 'NotFoundError');
}
return {};
},
} as unknown as FileSystemDirectoryHandle;

expect(await playgroundAvailableInOpfs(directory)).toBe(expected);
}
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,7 @@ export async function playgroundAvailableInOpfs(
/**
* Assume it's a Playground directory if these files exist:
* - wp-config.php
* - wp-content/database/.ht.sqlite
* - wp-content/database/db-path.php or the legacy .ht.sqlite file
*/
await dirHandle.getFileHandle('wp-config.php', { create: false });
const wpContent = await dirHandle.getDirectoryHandle('wp-content', {
Expand All @@ -714,7 +714,11 @@ export async function playgroundAvailableInOpfs(
const database = await wpContent.getDirectoryHandle('database', {
create: false,
});
await database.getFileHandle('.ht.sqlite', { create: false });
try {
await database.getFileHandle('db-path.php', { create: false });
} catch {
await database.getFileHandle('.ht.sqlite', { create: false });
}
} catch {
return false;
}
Expand Down
101 changes: 101 additions & 0 deletions packages/playground/tools/src/get-sqlite-database-path.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { loadNodeRuntime } from '@php-wasm/node';
import { RecommendedPHPVersion } from '@wp-playground/common';
import {
bootRequestHandler,
bootWordPress,
bootWordPressAndRequestHandler,
} from '@wp-playground/wordpress';
import { dirname, joinPaths } from '@php-wasm/util';
import {
getSqliteDriverModule,
getWordPressModule,
} from '@wp-playground/wordpress-builds';
import { getSqliteDatabasePath } from './get-sqlite-database-path';

describe('getSqliteDatabasePath', () => {
it('reads the active database from WordPress environment metadata', async () => {
await using handler = await bootWordPressAndRequestHandler({
createPhpRuntime: () => loadNodeRuntime(RecommendedPHPVersion),
siteUrl: 'http://playground.test',
wordPressZip: await getWordPressModule(),
sqliteIntegrationPluginZip: await getSqliteDriverModule(),
documentRoot: '/custom-root',
dataSqlPath: '/custom/database.sqlite',
});
const php = await handler.getPrimaryPhp();
const path = await getSqliteDatabasePath(php);
expect(php.isFile(path)).toBe(true);
expect(path).toBe('/custom/database.sqlite');
await php.run({
code: `<?php
require getenv('DOCUMENT_ROOT') . '/wp-load.php';
update_option('playground_database_path_test', 'active database');
`,
env: { DOCUMENT_ROOT: php.documentRoot },
});
const response = await php.run({
code: `<?php
$pdo = new PDO('sqlite:' . getenv('DATABASE_PATH'));
echo $pdo->query("SELECT option_value FROM wp_options WHERE option_name = 'playground_database_path_test'")->fetchColumn();
`,
env: { DATABASE_PATH: path },
});
expect(response.errors).toBe('');
expect(response.text).toBe('active database');
}, 30_000);

it.each([undefined, '/custom/database.sqlite'])(
'keeps the database accessible after a failed boot with dataSqlPath=%s',
async (dataSqlPath) => {
const options = {
createPhpRuntime: () => loadNodeRuntime(RecommendedPHPVersion),
siteUrl: 'http://playground.test',
wordPressZip: await getWordPressModule(),
sqliteIntegrationPluginZip: await getSqliteDriverModule(),
dataSqlPath,
};
await using saved = await bootWordPressAndRequestHandler(options);
const source = await saved.getPrimaryPhp();
const path = await getSqliteDatabasePath(source);
const database = source.readFileAsBuffer(path);
const discoveryPath = joinPaths(
source.documentRoot,
'wp-content/database/db-path.php'
);
await using reopened = await bootRequestHandler(options);
await expect(
bootWordPress(reopened, {
...options,
wordpressInstallMode:
'install-from-existing-files-if-needed',
hooks: {
beforeDatabaseSetup: async (php) => {
php.mkdir(dirname(path));
php.writeFile(path, database);
if (source.fileExists(discoveryPath)) {
php.writeFile(
discoveryPath,
source.readFileAsBuffer(discoveryPath)
);
}
php.mkdir('/wordpress/wp-content/mu-plugins');
php.writeFile(
'/wordpress/wp-content/mu-plugins/broken.php',
'<?php throw new Exception("A saved plugin failed");'
);
},
},
})
).rejects.toThrow('A saved plugin failed');

const php = await reopened.getPrimaryPhp();
expect(await getSqliteDatabasePath(php)).toBe(path);
expect(php.readFileAsBuffer(path).byteLength).toBeGreaterThan(0);

// An unrelated PHP request must not overwrite the saved database metadata.
await php.run({ code: '<?php echo "No WordPress loaded";' });
expect(await getSqliteDatabasePath(php)).toBe(path);
},
30_000
);
});
27 changes: 27 additions & 0 deletions packages/playground/tools/src/get-sqlite-database-path.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { UniversalPHP } from '@php-wasm/universal';

export async function getSqliteDatabasePath(
php: UniversalPHP
): Promise<string> {
const response = await php.runStream({
code: `<?php
$wp_env = require '/internal/shared/wp-env.php';
if ($wp_env['db']['type'] !== 'sqlite') {
throw new RuntimeException('The site does not use SQLite.');
}
echo $wp_env['db']['path'];
`,
});
const [path, errors, exitCode] = await Promise.all([
response.stdoutText,
response.stderrText,
response.exitCode,
]);
if (exitCode !== 0) {
throw new Error(errors || 'Could not read the SQLite database path.');
}
if (path === '') {
throw new Error('The SQLite database path is invalid.');
}
return path;
}
Loading
Loading