0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-04-14 23:51:49 -05:00

cleanup old copy paste code

This commit is contained in:
Fred K. Schott 2024-01-25 03:33:37 -08:00
parent d0102e6725
commit ebda4e913c
3 changed files with 29 additions and 108 deletions
packages/db/src

View file

@ -142,7 +142,6 @@ async function pushData({
const insert = db.insert(table).values(await collection.data());
queries.push(insert.toSQL());
}
console.log(queries);
const url = new URL('/db/query', getRemoteDatabaseUrl());
const requestBody: InStatement[] = queries.map((q) => ({
sql: q.sql,

View file

@ -15,7 +15,7 @@ import type {
import { SQLiteAsyncDialect } from 'drizzle-orm/sqlite-core';
import { customAlphabet } from 'nanoid';
import prompts from 'prompts';
import { hasPrimaryKey } from '../internal.js';
import { getCreateTableQuery, getModifiers, hasDefault, hasPrimaryKey, schemaTypeToSqlType } from '../internal.js';
const sqlite = new SQLiteAsyncDialect();
const genTempTableName = customAlphabet('abcdefghijklmnopqrstuvwxyz', 10);
@ -401,56 +401,6 @@ function getRecreateTableQueries({
];
}
export function getCreateTableQuery(collectionName: string, collection: DBCollection) {
let query = `CREATE TABLE ${sqlite.escapeName(collectionName)} (`;
const colQueries = [];
const colHasPrimaryKey = Object.entries(collection.fields).find(
([, field]) => hasPrimaryKey(field)
);
if (!colHasPrimaryKey) {
colQueries.push('_id INTEGER PRIMARY KEY');
}
for (const [columnName, column] of Object.entries(collection.fields)) {
const colQuery = `${sqlite.escapeName(columnName)} ${schemaTypeToSqlType(
column.type
)}${getModifiers(columnName, column)}`;
colQueries.push(colQuery);
}
query += colQueries.join(', ') + ')';
return query;
}
function getModifiers(fieldName: string, field: DBField) {
let modifiers = '';
if (hasPrimaryKey(field)) {
modifiers += ' PRIMARY KEY';
}
if (!field.optional) {
modifiers += ' NOT NULL';
}
if (field.unique) {
modifiers += ' UNIQUE';
}
if (hasDefault(field)) {
modifiers += ` DEFAULT ${getDefaultValueSql(fieldName, field)}`;
}
return modifiers;
}
function schemaTypeToSqlType(type: FieldType): 'text' | 'integer' {
switch (type) {
case 'date':
case 'text':
case 'json':
return 'text';
case 'number':
case 'boolean':
return 'integer';
}
}
function isEmpty(obj: Record<string, unknown>) {
return Object.keys(obj).length === 0;
}
@ -488,7 +438,7 @@ function canRecreateTableWithoutDataLoss(
updated: UpdatedFields
): DataLossResponse {
for (const [fieldName, a] of Object.entries(added)) {
if (hasPrimaryKey(a) && a.type !== 'number') {
if (hasPrimaryKey(a) && a.type !== 'number' && !hasDefault(a)) {
return { dataLoss: true, fieldName, reason: 'added-required' };
}
if (!a.optional && !hasDefault(a)) {
@ -571,50 +521,10 @@ type DBFieldWithDefault =
| WithDefaultDefined<BooleanField>
| WithDefaultDefined<JsonField>;
// Type narrowing the default fails on union types, so use a type guard
function hasDefault(field: DBField): field is DBFieldWithDefault {
if (field.default !== undefined) {
return true;
}
if (hasPrimaryKey(field) && field.type === 'number') {
return true;
}
return false;
}
function hasRuntimeDefault(field: DBField): field is DBFieldWithDefault {
return field.type === 'date' && field.default === 'now';
}
function getDefaultValueSql(columnName: string, column: DBFieldWithDefault): string {
switch (column.type) {
case 'boolean':
return column.default ? 'TRUE' : 'FALSE';
case 'number':
return `${column.default || 'AUTOINCREMENT'}`;
case 'text':
return sqlite.escapeString(column.default);
case 'date':
return column.default === 'now' ? 'CURRENT_TIMESTAMP' : sqlite.escapeString(column.default);
case 'json': {
let stringified = '';
try {
stringified = JSON.stringify(column.default);
} catch (e) {
// eslint-disable-next-line no-console
console.log(
`Invalid default value for column ${color.bold(
columnName
)}. Defaults must be valid JSON when using the \`json()\` type.`
);
process.exit(0);
}
return sqlite.escapeString(stringified);
}
}
}
function objShallowEqual(a: Record<string, unknown>, b: Record<string, unknown>) {
if (Object.keys(a).length !== Object.keys(b).length) return false;
for (const [key, value] of Object.entries(a)) {

View file

@ -126,7 +126,13 @@ export async function setupDbTables({
export function getCreateTableQuery(collectionName: string, collection: DBCollection) {
let query = `CREATE TABLE ${sqlite.escapeName(collectionName)} (`;
const colQueries = ['"id" text PRIMARY KEY'];
const colQueries = [];
const colHasPrimaryKey = Object.entries(collection.fields).find(
([, field]) => hasPrimaryKey(field)
);
if (!colHasPrimaryKey) {
colQueries.push('_id INTEGER PRIMARY KEY');
}
for (const [columnName, column] of Object.entries(collection.fields)) {
const colQuery = `${sqlite.escapeName(columnName)} ${schemaTypeToSqlType(
column.type
@ -138,7 +144,7 @@ export function getCreateTableQuery(collectionName: string, collection: DBCollec
return query;
}
function schemaTypeToSqlType(type: FieldType): 'text' | 'integer' {
export function schemaTypeToSqlType(type: FieldType): 'text' | 'integer' {
switch (type) {
case 'date':
case 'text':
@ -150,20 +156,24 @@ function schemaTypeToSqlType(type: FieldType): 'text' | 'integer' {
}
}
function getModifiers(columnName: string, column: DBField) {
export function getModifiers(fieldName: string, field: DBField) {
let modifiers = '';
if (!column.optional) {
if (hasPrimaryKey(field)) {
return ' PRIMARY KEY';
}
if (!field.optional) {
modifiers += ' NOT NULL';
}
if (column.unique) {
if (field.unique) {
modifiers += ' UNIQUE';
}
if (hasDefault(column)) {
modifiers += ` DEFAULT ${getDefaultValueSql(columnName, column)}`;
if (hasDefault(field)) {
modifiers += ` DEFAULT ${getDefaultValueSql(fieldName, field)}`;
}
return modifiers;
}
// Using `DBField` will not narrow `default` based on the column `type`
// Handle each field separately
type WithDefaultDefined<T extends DBField> = T & Required<Pick<T, 'default'>>;
@ -175,8 +185,14 @@ type DBFieldWithDefault =
| WithDefaultDefined<JsonField>;
// Type narrowing the default fails on union types, so use a type guard
function hasDefault(field: DBField): field is DBFieldWithDefault {
return field.default !== undefined;
export function hasDefault(field: DBField): field is DBFieldWithDefault {
if (field.default !== undefined) {
return true;
}
if (hasPrimaryKey(field) && field.type === 'number') {
return true;
}
return false;
}
function getDefaultValueSql(columnName: string, column: DBFieldWithDefault): string {
@ -184,7 +200,7 @@ function getDefaultValueSql(columnName: string, column: DBFieldWithDefault): str
case 'boolean':
return column.default ? 'TRUE' : 'FALSE';
case 'number':
return `${column.default}`;
return `${column.default || 'AUTOINCREMENT'}`;
case 'text':
return sqlite.escapeString(column.default);
case 'date':
@ -195,7 +211,7 @@ function getDefaultValueSql(columnName: string, column: DBFieldWithDefault): str
stringified = JSON.stringify(column.default);
} catch (e) {
// eslint-disable-next-line no-console
console.info(
console.log(
`Invalid default value for column ${bold(
columnName
)}. Defaults must be valid JSON when using the \`json()\` type.`
@ -208,10 +224,6 @@ function getDefaultValueSql(columnName: string, column: DBFieldWithDefault): str
}
}
function generateId() {
return nanoid(12);
}
const dateType = customType<{ data: Date; driverData: string }>({
dataType() {
return 'text';