mirror of
https://github.com/withastro/astro.git
synced 2025-02-03 22:29:08 -05:00
feat: add indexes from collectionToTable
This commit is contained in:
parent
bda07ec94e
commit
67a68e737d
1 changed files with 18 additions and 2 deletions
|
@ -11,7 +11,7 @@ import {
|
||||||
type NumberField,
|
type NumberField,
|
||||||
type TextField,
|
type TextField,
|
||||||
} from './types.js';
|
} from './types.js';
|
||||||
import { type LibSQLDatabase, drizzle } from 'drizzle-orm/libsql';
|
import { drizzle } from 'drizzle-orm/libsql';
|
||||||
import { bold } from 'kleur/colors';
|
import { bold } from 'kleur/colors';
|
||||||
import {
|
import {
|
||||||
type SQL,
|
type SQL,
|
||||||
|
@ -26,8 +26,10 @@ import {
|
||||||
integer,
|
integer,
|
||||||
sqliteTable,
|
sqliteTable,
|
||||||
text,
|
text,
|
||||||
|
index,
|
||||||
type SQLiteTable,
|
type SQLiteTable,
|
||||||
type SQLiteColumnBuilderBase,
|
type SQLiteColumnBuilderBase,
|
||||||
|
type IndexBuilder,
|
||||||
} from 'drizzle-orm/sqlite-core';
|
} from 'drizzle-orm/sqlite-core';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import type { AstroIntegrationLogger } from 'astro';
|
import type { AstroIntegrationLogger } from 'astro';
|
||||||
|
@ -276,10 +278,24 @@ export function collectionToTable(
|
||||||
for (const [fieldName, field] of Object.entries(collection.fields)) {
|
for (const [fieldName, field] of Object.entries(collection.fields)) {
|
||||||
columns[fieldName] = columnMapper(fieldName, field, isJsonSerializable);
|
columns[fieldName] = columnMapper(fieldName, field, isJsonSerializable);
|
||||||
}
|
}
|
||||||
const table = sqliteTable(name, columns);
|
const table = sqliteTable(name, columns, (ormTable) => {
|
||||||
|
const indexes: Record<string, IndexBuilder> = {};
|
||||||
|
for (const [indexName, indexProps] of Object.entries(collection.indexes ?? {})) {
|
||||||
|
const onColNames = Array.isArray(indexProps.on) ? indexProps.on : [indexProps.on];
|
||||||
|
const onCols = onColNames.map((colName) => ormTable[colName]);
|
||||||
|
if (!atLeastOne(onCols)) continue;
|
||||||
|
|
||||||
|
indexes[indexName] = index(indexName).on(...onCols);
|
||||||
|
}
|
||||||
|
return indexes;
|
||||||
|
});
|
||||||
return table;
|
return table;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function atLeastOne<T>(arr: T[]): arr is [T, ...T[]] {
|
||||||
|
return arr.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
function columnMapper(fieldName: string, field: DBField, isJsonSerializable: boolean) {
|
function columnMapper(fieldName: string, field: DBField, isJsonSerializable: boolean) {
|
||||||
let c: ReturnType<
|
let c: ReturnType<
|
||||||
| typeof text
|
| typeof text
|
||||||
|
|
Loading…
Add table
Reference in a new issue