netapi32: Default to CP_UTF8 when WINEUNIXCP is not set.
[wine.git] / dlls / msi / database.c
blobc84fd1f6440d8b68eb01a8bbff3a0febfedb43d3
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
22 #include <stdio.h>
24 #define COBJMACROS
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "msipriv.h"
34 #include "objidl.h"
35 #include "objbase.h"
36 #include "msiserver.h"
37 #include "query.h"
39 #include "initguid.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(msi);
44 * .MSI file format
46 * An .msi file is a structured storage file.
47 * It contains a number of streams.
48 * A stream for each table in the database.
49 * Two streams for the string table in the database.
50 * Any binary data in a table is a reference to a stream.
53 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
55 static void free_transforms( MSIDATABASE *db )
57 while( !list_empty( &db->transforms ) )
59 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ), MSITRANSFORM, entry );
60 list_remove( &t->entry );
61 IStorage_Release( t->stg );
62 msi_free( t );
66 static void free_streams( MSIDATABASE *db )
68 UINT i;
69 for (i = 0; i < db->num_streams; i++)
71 if (db->streams[i].stream) IStream_Release( db->streams[i].stream );
73 msi_free( db->streams );
76 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
78 MSITRANSFORM *t;
80 t = msi_alloc( sizeof *t );
81 t->stg = stg;
82 IStorage_AddRef( stg );
83 list_add_head( &db->transforms, &t->entry );
86 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
88 MSIDATABASE *db = (MSIDATABASE *) arg;
90 msi_free(db->path);
91 free_streams( db );
92 free_cached_tables( db );
93 free_transforms( db );
94 if (db->strings) msi_destroy_stringtable( db->strings );
95 IStorage_Release( db->storage );
96 if (db->deletefile)
98 DeleteFileW( db->deletefile );
99 msi_free( db->deletefile );
101 msi_free( db->tempfolder );
104 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
106 HRESULT hr;
108 hr = IStorage_SetClass( stg, clsid );
109 if (FAILED( hr ))
111 WARN("failed to set class id 0x%08x\n", hr);
112 return hr;
115 /* create the _Tables stream */
116 hr = write_stream_data( stg, L"_Tables", NULL, 0, TRUE );
117 if (FAILED( hr ))
119 WARN("failed to create _Tables stream 0x%08x\n", hr);
120 return hr;
123 hr = msi_init_string_table( stg );
124 if (FAILED( hr ))
126 WARN("failed to initialize string table 0x%08x\n", hr);
127 return hr;
130 hr = IStorage_Commit( stg, 0 );
131 if (FAILED( hr ))
133 WARN("failed to commit changes 0x%08x\n", hr);
134 return hr;
137 return S_OK;
140 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
142 IStorage *stg = NULL;
143 HRESULT r;
144 MSIDATABASE *db = NULL;
145 UINT ret = ERROR_FUNCTION_FAILED;
146 LPCWSTR save_path;
147 UINT mode;
148 STATSTG stat;
149 BOOL created = FALSE, patch = FALSE;
150 WCHAR path[MAX_PATH];
152 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
154 if( !pdb )
155 return ERROR_INVALID_PARAMETER;
157 save_path = szDBPath;
158 if ( IS_INTMSIDBOPEN(szPersist) )
160 mode = LOWORD(szPersist);
162 else
164 if (!CopyFileW( szDBPath, szPersist, FALSE ))
165 return ERROR_OPEN_FAILED;
167 szDBPath = szPersist;
168 mode = MSI_OPEN_TRANSACT;
169 created = TRUE;
172 if ((mode & MSI_OPEN_PATCHFILE) == MSI_OPEN_PATCHFILE)
174 TRACE("Database is a patch\n");
175 mode &= ~MSI_OPEN_PATCHFILE;
176 patch = TRUE;
179 if( mode == MSI_OPEN_READONLY )
181 r = StgOpenStorage( szDBPath, NULL,
182 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
184 else if( mode == MSI_OPEN_CREATE )
186 r = StgCreateDocfile( szDBPath,
187 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
189 if( SUCCEEDED(r) )
190 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
191 created = TRUE;
193 else if( mode == MSI_OPEN_CREATEDIRECT )
195 r = StgCreateDocfile( szDBPath,
196 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
198 if( SUCCEEDED(r) )
199 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
200 created = TRUE;
202 else if( mode == MSI_OPEN_TRANSACT )
204 r = StgOpenStorage( szDBPath, NULL,
205 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
207 else if( mode == MSI_OPEN_DIRECT )
209 r = StgOpenStorage( szDBPath, NULL,
210 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
212 else
214 ERR("unknown flag %x\n",mode);
215 return ERROR_INVALID_PARAMETER;
218 if( FAILED( r ) || !stg )
220 WARN("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
221 return ERROR_FUNCTION_FAILED;
224 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
225 if( FAILED( r ) )
227 FIXME("Failed to stat storage\n");
228 goto end;
231 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
232 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
233 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
235 ERR("storage GUID is not a MSI database GUID %s\n",
236 debugstr_guid(&stat.clsid) );
237 goto end;
240 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
242 ERR("storage GUID is not the MSI patch GUID %s\n",
243 debugstr_guid(&stat.clsid) );
244 ret = ERROR_OPEN_FAILED;
245 goto end;
248 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
249 MSI_CloseDatabase );
250 if( !db )
252 FIXME("Failed to allocate a handle\n");
253 goto end;
256 if (!wcschr( save_path, '\\' ))
258 GetCurrentDirectoryW( MAX_PATH, path );
259 lstrcatW( path, L"\\" );
260 lstrcatW( path, save_path );
262 else
263 lstrcpyW( path, save_path );
265 db->path = strdupW( path );
266 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
267 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
269 if( TRACE_ON( msi ) )
270 enum_stream_names( stg );
272 db->storage = stg;
273 db->mode = mode;
274 if (created)
275 db->deletefile = strdupW( szDBPath );
276 list_init( &db->tables );
277 list_init( &db->transforms );
279 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
280 if( !db->strings )
281 goto end;
283 ret = ERROR_SUCCESS;
285 msiobj_addref( &db->hdr );
286 IStorage_AddRef( stg );
287 *pdb = db;
289 end:
290 if( db )
291 msiobj_release( &db->hdr );
292 if( stg )
293 IStorage_Release( stg );
295 return ret;
298 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
300 MSIDATABASE *db;
301 UINT ret;
303 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
305 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
306 if( ret == ERROR_SUCCESS )
308 *phDB = alloc_msihandle( &db->hdr );
309 if (! *phDB)
310 ret = ERROR_NOT_ENOUGH_MEMORY;
311 msiobj_release( &db->hdr );
314 return ret;
317 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
319 HRESULT r = ERROR_FUNCTION_FAILED;
320 LPWSTR szwDBPath = NULL, szwPersist = NULL;
322 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
324 if( szDBPath )
326 szwDBPath = strdupAtoW( szDBPath );
327 if( !szwDBPath )
328 goto end;
331 if( !IS_INTMSIDBOPEN(szPersist) )
333 szwPersist = strdupAtoW( szPersist );
334 if( !szwPersist )
335 goto end;
337 else
338 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
340 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
342 end:
343 if( !IS_INTMSIDBOPEN(szPersist) )
344 msi_free( szwPersist );
345 msi_free( szwDBPath );
347 return r;
350 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
352 HANDLE file;
353 LPSTR data = NULL;
354 LPWSTR wdata = NULL;
355 DWORD read, size = 0;
357 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
358 if (file == INVALID_HANDLE_VALUE)
359 return NULL;
361 size = GetFileSize( file, NULL );
362 if (!(data = msi_alloc( size ))) goto done;
364 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
366 while (!data[size - 1]) size--;
367 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
368 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
370 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
371 wdata[*len] = 0;
374 done:
375 CloseHandle( file );
376 msi_free( data );
377 return wdata;
380 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
382 LPWSTR ptr = *line, save;
383 DWORD i, count = 1, chars_left = *len;
385 *entries = NULL;
387 /* stay on this line */
388 while (chars_left && *ptr != '\n')
390 /* entries are separated by tabs */
391 if (*ptr == '\t')
392 count++;
394 ptr++;
395 chars_left--;
398 *entries = msi_alloc(count * sizeof(LPWSTR));
399 if (!*entries)
400 return;
402 /* store pointers into the data */
403 chars_left = *len;
404 for (i = 0, ptr = *line; i < count; i++)
406 while (chars_left && *ptr == '\r')
408 ptr++;
409 chars_left--;
411 save = ptr;
413 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
415 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
416 if (ptr > *line && *ptr == '\x19' && *(ptr - 1) == '\x11')
418 *ptr = '\n';
419 *(ptr - 1) = '\r';
421 ptr++;
422 chars_left--;
425 /* NULL-separate the data */
426 if (*ptr == '\n' || *ptr == '\r')
428 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
430 *(ptr++) = 0;
431 chars_left--;
434 else if (*ptr)
436 *(ptr++) = 0;
437 chars_left--;
439 (*entries)[i] = save;
442 /* move to the next line if there's more, else EOF */
443 *line = ptr;
444 *len = chars_left;
445 if (num_entries)
446 *num_entries = count;
449 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
451 LPWSTR prelude;
452 DWORD size;
454 size = ARRAY_SIZE(L"CREATE TABLE `%s` ( ") + lstrlenW(table) - 2;
455 prelude = msi_alloc(size * sizeof(WCHAR));
456 if (!prelude)
457 return NULL;
459 swprintf(prelude, size, L"CREATE TABLE `%s` ( ", table);
460 return prelude;
463 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
465 LPWSTR columns, p;
466 LPCWSTR type;
467 DWORD sql_size = 1, i, len;
468 WCHAR expanded[128], *ptr;
469 WCHAR size[10], comma[2], extra[30];
471 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
472 if (!columns)
473 return NULL;
475 for (i = 0; i < num_columns; i++)
477 type = NULL;
478 comma[1] = size[0] = extra[0] = '\0';
480 if (i == num_columns - 1)
481 comma[0] = '\0';
482 else
483 comma[0] = ',';
485 ptr = &types[i][1];
486 len = wcstol(ptr, NULL, 10);
487 extra[0] = '\0';
489 switch (types[i][0])
491 case 'l':
492 lstrcpyW(extra, L" NOT NULL");
493 /* fall through */
494 case 'L':
495 lstrcatW(extra, L" LOCALIZABLE");
496 type = L"CHAR";
497 swprintf(size, ARRAY_SIZE(size), L"(%s)", ptr);
498 break;
499 case 's':
500 lstrcpyW(extra, L" NOT NULL");
501 /* fall through */
502 case 'S':
503 type = L"CHAR";
504 swprintf(size, ARRAY_SIZE(size), L"(%s)", ptr);
505 break;
506 case 'i':
507 lstrcpyW(extra, L" NOT NULL");
508 /* fall through */
509 case 'I':
510 if (len <= 2)
511 type = L"INT";
512 else if (len == 4)
513 type = L"LONG";
514 else
516 WARN("invalid int width %u\n", len);
517 msi_free(columns);
518 return NULL;
520 break;
521 case 'v':
522 lstrcpyW(extra, L" NOT NULL");
523 /* fall through */
524 case 'V':
525 type = L"OBJECT";
526 break;
527 default:
528 ERR("Unknown type: %c\n", types[i][0]);
529 msi_free(columns);
530 return NULL;
533 swprintf(expanded, ARRAY_SIZE(expanded), L"`%s` %s%s%s%s ", columns_data[i], type, size, extra, comma);
534 sql_size += lstrlenW(expanded);
536 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
537 if (!p)
539 msi_free(columns);
540 return NULL;
542 columns = p;
544 lstrcatW(columns, expanded);
547 return columns;
550 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
552 LPWSTR postlude, keys, ptr;
553 DWORD size, i;
555 for (i = 0, size = 1; i < num_keys; i++)
556 size += lstrlenW(L"`%s`, ") + lstrlenW(primary_keys[i]) - 2;
558 keys = msi_alloc(size * sizeof(WCHAR));
559 if (!keys)
560 return NULL;
562 for (i = 0, ptr = keys; i < num_keys; i++)
564 ptr += swprintf(ptr, size - (ptr - keys), L"`%s`, ", primary_keys[i]);
567 /* remove final ', ' */
568 *(ptr - 2) = '\0';
570 size = lstrlenW(L"PRIMARY KEY %s)") + size - 1;
571 postlude = msi_alloc(size * sizeof(WCHAR));
572 if (!postlude)
573 goto done;
575 swprintf(postlude, size, L"PRIMARY KEY %s)", keys);
577 done:
578 msi_free(keys);
579 return postlude;
582 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
584 UINT r = ERROR_OUTOFMEMORY;
585 DWORD size;
586 MSIQUERY *view;
587 LPWSTR create_sql = NULL;
588 LPWSTR prelude, columns_sql, postlude;
590 prelude = msi_build_createsql_prelude(labels[0]);
591 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
592 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
594 if (!prelude || !columns_sql || !postlude)
595 goto done;
597 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
598 create_sql = msi_alloc(size * sizeof(WCHAR));
599 if (!create_sql)
600 goto done;
602 lstrcpyW(create_sql, prelude);
603 lstrcatW(create_sql, columns_sql);
604 lstrcatW(create_sql, postlude);
606 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
607 if (r != ERROR_SUCCESS)
608 goto done;
610 r = MSI_ViewExecute(view, NULL);
611 MSI_ViewClose(view);
612 msiobj_release(&view->hdr);
614 done:
615 msi_free(prelude);
616 msi_free(columns_sql);
617 msi_free(postlude);
618 msi_free(create_sql);
619 return r;
622 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
624 DWORD len;
625 LPWSTR fullname, ptr;
627 len = lstrlenW(path) + lstrlenW(name) + 1;
628 fullname = msi_alloc(len*sizeof(WCHAR));
629 if (!fullname)
630 return NULL;
632 lstrcpyW( fullname, path );
634 /* chop off extension from path */
635 ptr = wcsrchr(fullname, '.');
636 if (!ptr)
638 msi_free (fullname);
639 return NULL;
641 *ptr++ = '\\';
642 lstrcpyW( ptr, name );
643 return fullname;
646 static UINT construct_record(DWORD num_columns, LPWSTR *types,
647 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
649 UINT i;
651 *rec = MSI_CreateRecord(num_columns);
652 if (!*rec)
653 return ERROR_OUTOFMEMORY;
655 for (i = 0; i < num_columns; i++)
657 switch (types[i][0])
659 case 'L': case 'l': case 'S': case 's':
660 MSI_RecordSetStringW(*rec, i + 1, data[i]);
661 break;
662 case 'I': case 'i':
663 if (*data[i])
664 MSI_RecordSetInteger(*rec, i + 1, wcstol(data[i], NULL, 10));
665 break;
666 case 'V': case 'v':
667 if (*data[i])
669 UINT r;
670 LPWSTR file = msi_import_stream_filename(path, data[i]);
671 if (!file)
672 return ERROR_FUNCTION_FAILED;
674 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
675 msi_free (file);
676 if (r != ERROR_SUCCESS)
677 return ERROR_FUNCTION_FAILED;
679 break;
680 default:
681 ERR("Unhandled column type: %c\n", types[i][0]);
682 msiobj_release(&(*rec)->hdr);
683 return ERROR_FUNCTION_FAILED;
687 return ERROR_SUCCESS;
690 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
691 LPWSTR *labels, LPWSTR **records,
692 int num_columns, int num_records,
693 LPWSTR path)
695 UINT r;
696 int i;
697 MSIQUERY *view;
698 MSIRECORD *rec;
700 r = MSI_OpenQuery(db, &view, L"SELECT * FROM `%s`", labels[0]);
701 if (r != ERROR_SUCCESS)
702 return r;
704 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
706 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
707 msiobj_release(&rec->hdr);
708 if (r != ERROR_SUCCESS)
709 goto done;
712 for (i = 0; i < num_records; i++)
714 r = construct_record(num_columns, types, records[i], path, &rec);
715 if (r != ERROR_SUCCESS)
716 goto done;
718 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
719 if (r != ERROR_SUCCESS)
721 msiobj_release(&rec->hdr);
722 goto done;
725 msiobj_release(&rec->hdr);
728 done:
729 msiobj_release(&view->hdr);
730 return r;
733 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
735 UINT r;
736 DWORD len, i, num_labels, num_types, num_columns, num_records = 0;
737 WCHAR **columns, **types, **labels, *path, *ptr, *data, ***records = NULL, ***temp_records;
739 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
741 if (!folder || !file)
742 return ERROR_INVALID_PARAMETER;
744 len = lstrlenW(folder) + lstrlenW(L"\\") + lstrlenW(file) + 1;
745 path = msi_alloc( len * sizeof(WCHAR) );
746 if (!path)
747 return ERROR_OUTOFMEMORY;
749 lstrcpyW( path, folder );
750 lstrcatW( path, L"\\" );
751 lstrcatW( path, file );
753 data = msi_read_text_archive( path, &len );
754 if (!data)
756 msi_free(path);
757 return ERROR_FUNCTION_FAILED;
760 ptr = data;
761 msi_parse_line( &ptr, &columns, &num_columns, &len );
762 msi_parse_line( &ptr, &types, &num_types, &len );
763 msi_parse_line( &ptr, &labels, &num_labels, &len );
765 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
766 num_types == 2 && !wcscmp( types[1], L"_ForceCodepage" ))
768 r = msi_set_string_table_codepage( db->strings, wcstol( types[0], NULL, 10 ) );
769 goto done;
772 if (num_columns != num_types)
774 r = ERROR_FUNCTION_FAILED;
775 goto done;
778 records = msi_alloc(sizeof(WCHAR **));
779 if (!records)
781 r = ERROR_OUTOFMEMORY;
782 goto done;
785 /* read in the table records */
786 while (len)
788 msi_parse_line( &ptr, &records[num_records], NULL, &len );
790 num_records++;
791 temp_records = msi_realloc(records, (num_records + 1) * sizeof(WCHAR **));
792 if (!temp_records)
794 r = ERROR_OUTOFMEMORY;
795 goto done;
797 records = temp_records;
800 if (!wcscmp(labels[0], L"_SummaryInformation"))
802 r = msi_add_suminfo( db, records, num_records, num_columns );
803 if (r != ERROR_SUCCESS)
805 r = ERROR_FUNCTION_FAILED;
806 goto done;
809 else
811 if (!TABLE_Exists(db, labels[0]))
813 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
814 if (r != ERROR_SUCCESS)
816 r = ERROR_FUNCTION_FAILED;
817 goto done;
821 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
824 done:
825 msi_free(path);
826 msi_free(data);
827 msi_free(columns);
828 msi_free(types);
829 msi_free(labels);
831 for (i = 0; i < num_records; i++)
832 msi_free(records[i]);
834 msi_free(records);
835 return r;
838 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
840 MSIDATABASE *db;
841 UINT r;
843 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
845 if (!(db = msihandle2msiinfo(handle, MSIHANDLETYPE_DATABASE)))
846 return ERROR_INVALID_HANDLE;
848 r = MSI_DatabaseImport( db, szFolder, szFilename );
849 msiobj_release( &db->hdr );
850 return r;
853 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
854 LPCSTR szFolder, LPCSTR szFilename )
856 LPWSTR path = NULL, file = NULL;
857 UINT r = ERROR_OUTOFMEMORY;
859 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
861 if( szFolder )
863 path = strdupAtoW( szFolder );
864 if( !path )
865 goto end;
868 if( szFilename )
870 file = strdupAtoW( szFilename );
871 if( !file )
872 goto end;
875 r = MsiDatabaseImportW( handle, path, file );
877 end:
878 msi_free( path );
879 msi_free( file );
881 return r;
884 static UINT msi_export_field( HANDLE handle, MSIRECORD *row, UINT field )
886 char *buffer;
887 BOOL ret;
888 DWORD sz = 0x100;
889 UINT r;
891 buffer = msi_alloc( sz );
892 if (!buffer)
893 return ERROR_OUTOFMEMORY;
895 r = MSI_RecordGetStringA( row, field, buffer, &sz );
896 if (r == ERROR_MORE_DATA)
898 char *tmp;
900 sz++; /* leave room for NULL terminator */
901 tmp = msi_realloc( buffer, sz );
902 if (!tmp)
904 msi_free( buffer );
905 return ERROR_OUTOFMEMORY;
907 buffer = tmp;
909 r = MSI_RecordGetStringA( row, field, buffer, &sz );
910 if (r != ERROR_SUCCESS)
912 msi_free( buffer );
913 return r;
916 else if (r != ERROR_SUCCESS)
918 msi_free( buffer );
919 return r;
922 ret = WriteFile( handle, buffer, sz, &sz, NULL );
923 msi_free( buffer );
924 return ret ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
927 static UINT msi_export_stream( const WCHAR *folder, const WCHAR *table, MSIRECORD *row, UINT field, UINT start )
929 WCHAR stream[MAX_STREAM_NAME_LEN + 1], *path;
930 DWORD sz, read_size, write_size;
931 char buffer[1024];
932 HANDLE file;
933 UINT len, r;
935 sz = ARRAY_SIZE( stream );
936 r = MSI_RecordGetStringW( row, start, stream, &sz );
937 if (r != ERROR_SUCCESS)
938 return r;
940 len = sz + lstrlenW( folder ) + lstrlenW( table ) + ARRAY_SIZE( L"%s\\%s" ) + 1;
941 if (!(path = msi_alloc( len * sizeof(WCHAR) )))
942 return ERROR_OUTOFMEMORY;
944 len = swprintf( path, len, L"%s\\%s", folder, table );
945 if (!CreateDirectoryW( path, NULL ) && GetLastError() != ERROR_ALREADY_EXISTS)
947 msi_free( path );
948 return ERROR_FUNCTION_FAILED;
951 path[len++] = '\\';
952 lstrcpyW( path + len, stream );
953 file = CreateFileW( path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
954 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
955 msi_free( path );
956 if (file == INVALID_HANDLE_VALUE)
957 return ERROR_FUNCTION_FAILED;
959 read_size = sizeof(buffer);
960 while (read_size == sizeof(buffer))
962 r = MSI_RecordReadStream( row, field, buffer, &read_size );
963 if (r != ERROR_SUCCESS)
965 CloseHandle( file );
966 return r;
968 if (!WriteFile( file, buffer, read_size, &write_size, NULL ) || read_size != write_size)
970 CloseHandle( file );
971 return ERROR_WRITE_FAULT;
974 CloseHandle( file );
975 return r;
978 struct row_export_info
980 HANDLE handle;
981 const WCHAR *folder;
982 const WCHAR *table;
985 static UINT msi_export_record( struct row_export_info *row_export_info, MSIRECORD *row, UINT start )
987 HANDLE handle = row_export_info->handle;
988 UINT i, count, r = ERROR_SUCCESS;
989 const char *sep;
990 DWORD sz;
992 count = MSI_RecordGetFieldCount( row );
993 for (i = start; i <= count; i++)
995 r = msi_export_field( handle, row, i );
996 if (r == ERROR_INVALID_PARAMETER)
998 r = msi_export_stream( row_export_info->folder, row_export_info->table, row, i, start );
999 if (r != ERROR_SUCCESS)
1000 return r;
1002 /* exporting a binary stream, repeat the "Name" field */
1003 r = msi_export_field( handle, row, start );
1004 if (r != ERROR_SUCCESS)
1005 return r;
1007 else if (r != ERROR_SUCCESS)
1008 return r;
1010 sep = (i < count) ? "\t" : "\r\n";
1011 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1012 return ERROR_FUNCTION_FAILED;
1014 return r;
1017 static UINT msi_export_row( MSIRECORD *row, void *arg )
1019 return msi_export_record( arg, row, 1 );
1022 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
1024 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
1025 char data[sizeof(fmt) + 10];
1026 DWORD sz = sprintf( data, fmt, codepage );
1028 if (!WriteFile(handle, data, sz, &sz, NULL))
1029 return ERROR_FUNCTION_FAILED;
1031 return ERROR_SUCCESS;
1034 static UINT msi_export_summaryinformation( MSIDATABASE *db, HANDLE handle )
1036 static const char header[] = "PropertyId\tValue\r\n"
1037 "i2\tl255\r\n"
1038 "_SummaryInformation\tPropertyId\r\n";
1039 DWORD sz = ARRAY_SIZE(header) - 1;
1041 if (!WriteFile(handle, header, sz, &sz, NULL))
1042 return ERROR_WRITE_FAULT;
1044 return msi_export_suminfo( db, handle );
1047 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table, LPCWSTR folder, LPCWSTR file )
1049 MSIRECORD *rec = NULL;
1050 MSIQUERY *view = NULL;
1051 WCHAR *filename;
1052 HANDLE handle;
1053 UINT len, r;
1055 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1056 debugstr_w(folder), debugstr_w(file) );
1058 if (!folder || !file)
1059 return ERROR_INVALID_PARAMETER;
1061 len = lstrlenW(folder) + lstrlenW(file) + 2;
1062 filename = msi_alloc(len * sizeof (WCHAR));
1063 if (!filename)
1064 return ERROR_OUTOFMEMORY;
1066 lstrcpyW( filename, folder );
1067 lstrcatW( filename, L"\\" );
1068 lstrcatW( filename, file );
1070 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1071 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1072 msi_free( filename );
1073 if (handle == INVALID_HANDLE_VALUE)
1074 return ERROR_FUNCTION_FAILED;
1076 if (!wcscmp( table, L"_ForceCodepage" ))
1078 UINT codepage = msi_get_string_table_codepage( db->strings );
1079 r = msi_export_forcecodepage( handle, codepage );
1080 goto done;
1083 if (!wcscmp( table, L"_SummaryInformation" ))
1085 r = msi_export_summaryinformation( db, handle );
1086 goto done;
1089 r = MSI_OpenQuery( db, &view, L"SELECT * FROM %s", table );
1090 if (r == ERROR_SUCCESS)
1092 struct row_export_info row_export_info = { handle, folder, table };
1094 /* write out row 1, the column names */
1095 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1096 if (r == ERROR_SUCCESS)
1098 msi_export_record( &row_export_info, rec, 1 );
1099 msiobj_release( &rec->hdr );
1102 /* write out row 2, the column types */
1103 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1104 if (r == ERROR_SUCCESS)
1106 msi_export_record( &row_export_info, rec, 1 );
1107 msiobj_release( &rec->hdr );
1110 /* write out row 3, the table name + keys */
1111 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1112 if (r == ERROR_SUCCESS)
1114 MSI_RecordSetStringW( rec, 0, table );
1115 msi_export_record( &row_export_info, rec, 0 );
1116 msiobj_release( &rec->hdr );
1119 /* write out row 4 onwards, the data */
1120 r = MSI_IterateRecords( view, 0, msi_export_row, &row_export_info );
1121 msiobj_release( &view->hdr );
1124 done:
1125 CloseHandle( handle );
1126 return r;
1129 /***********************************************************************
1130 * MsiExportDatabaseW [MSI.@]
1132 * Writes a file containing the table data as tab separated ASCII.
1134 * The format is as follows:
1136 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1137 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1138 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1140 * Followed by the data, starting at row 1 with one row per line
1142 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1144 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1145 LPCWSTR szFolder, LPCWSTR szFilename )
1147 MSIDATABASE *db;
1148 UINT r;
1150 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1151 debugstr_w(szFolder), debugstr_w(szFilename));
1153 if (!(db = msihandle2msiinfo(handle, MSIHANDLETYPE_DATABASE)))
1154 return ERROR_INVALID_HANDLE;
1156 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1157 msiobj_release( &db->hdr );
1158 return r;
1161 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1162 LPCSTR szFolder, LPCSTR szFilename )
1164 LPWSTR path = NULL, file = NULL, table = NULL;
1165 UINT r = ERROR_OUTOFMEMORY;
1167 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1168 debugstr_a(szFolder), debugstr_a(szFilename));
1170 if( szTable )
1172 table = strdupAtoW( szTable );
1173 if( !table )
1174 goto end;
1177 if( szFolder )
1179 path = strdupAtoW( szFolder );
1180 if( !path )
1181 goto end;
1184 if( szFilename )
1186 file = strdupAtoW( szFilename );
1187 if( !file )
1188 goto end;
1191 r = MsiDatabaseExportW( handle, table, path, file );
1193 end:
1194 msi_free( table );
1195 msi_free( path );
1196 msi_free( file );
1198 return r;
1201 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1202 LPCSTR szTableName)
1204 UINT r;
1205 LPWSTR table;
1207 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1208 debugstr_a(szTableName));
1210 table = strdupAtoW(szTableName);
1211 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1213 msi_free(table);
1214 return r;
1217 typedef struct _tagMERGETABLE
1219 struct list entry;
1220 struct list rows;
1221 LPWSTR name;
1222 DWORD numconflicts;
1223 LPWSTR *columns;
1224 DWORD numcolumns;
1225 LPWSTR *types;
1226 DWORD numtypes;
1227 LPWSTR *labels;
1228 DWORD numlabels;
1229 } MERGETABLE;
1231 typedef struct _tagMERGEROW
1233 struct list entry;
1234 MSIRECORD *data;
1235 } MERGEROW;
1237 typedef struct _tagMERGEDATA
1239 MSIDATABASE *db;
1240 MSIDATABASE *merge;
1241 MERGETABLE *curtable;
1242 MSIQUERY *curview;
1243 struct list *tabledata;
1244 } MERGEDATA;
1246 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1248 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1249 ((type2[0] == 'l') || (type2[0] == 's')))
1250 return TRUE;
1252 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1253 ((type2[0] == 'L') || (type2[0] == 'S')))
1254 return TRUE;
1256 return !wcscmp( type1, type2 );
1259 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1261 MSIRECORD *dbrec, *mergerec;
1262 UINT r, i, count;
1264 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1265 if (r != ERROR_SUCCESS)
1266 return r;
1268 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1269 if (r != ERROR_SUCCESS)
1271 msiobj_release(&dbrec->hdr);
1272 return r;
1275 count = MSI_RecordGetFieldCount(dbrec);
1276 for (i = 1; i <= count; i++)
1278 if (!MSI_RecordGetString(mergerec, i))
1279 break;
1281 if (wcscmp( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1283 r = ERROR_DATATYPE_MISMATCH;
1284 goto done;
1288 msiobj_release(&dbrec->hdr);
1289 msiobj_release(&mergerec->hdr);
1290 dbrec = mergerec = NULL;
1292 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1293 if (r != ERROR_SUCCESS)
1294 return r;
1296 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1297 if (r != ERROR_SUCCESS)
1299 msiobj_release(&dbrec->hdr);
1300 return r;
1303 count = MSI_RecordGetFieldCount(dbrec);
1304 for (i = 1; i <= count; i++)
1306 if (!MSI_RecordGetString(mergerec, i))
1307 break;
1309 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1310 MSI_RecordGetString(mergerec, i)))
1312 r = ERROR_DATATYPE_MISMATCH;
1313 break;
1317 done:
1318 msiobj_release(&dbrec->hdr);
1319 msiobj_release(&mergerec->hdr);
1321 return r;
1324 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1325 LPCWSTR table)
1327 MSIRECORD *dbrec, *mergerec = NULL;
1328 UINT r, i, count;
1330 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1331 if (r != ERROR_SUCCESS)
1332 return r;
1334 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1335 if (r != ERROR_SUCCESS)
1336 goto done;
1338 count = MSI_RecordGetFieldCount(dbrec);
1339 if (count != MSI_RecordGetFieldCount(mergerec))
1341 r = ERROR_DATATYPE_MISMATCH;
1342 goto done;
1345 for (i = 1; i <= count; i++)
1347 if (wcscmp( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1349 r = ERROR_DATATYPE_MISMATCH;
1350 goto done;
1354 done:
1355 msiobj_release(&dbrec->hdr);
1356 msiobj_release(&mergerec->hdr);
1358 return r;
1361 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1363 MSIRECORD *colnames;
1364 LPWSTR str, val;
1365 UINT r, i = 0, sz = 0;
1366 int cmp;
1368 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1369 if (r != ERROR_SUCCESS)
1370 return NULL;
1374 str = msi_dup_record_field(colnames, ++i);
1375 cmp = wcscmp( key, str );
1376 msi_free(str);
1377 } while (cmp);
1379 msiobj_release(&colnames->hdr);
1381 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1382 if (r != ERROR_SUCCESS)
1383 return NULL;
1384 sz++;
1386 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1388 /* quote string record fields */
1389 sz += 2;
1390 val = msi_alloc(sz * sizeof(WCHAR));
1391 if (!val)
1392 return NULL;
1394 lstrcpyW(val, L"'");
1395 r = MSI_RecordGetStringW(rec, i, val + 1, &sz);
1396 lstrcpyW(val + 1 + sz, L"'");
1398 else
1400 /* do not quote integer record fields */
1401 val = msi_alloc(sz * sizeof(WCHAR));
1402 if (!val)
1403 return NULL;
1405 r = MSI_RecordGetStringW(rec, i, val, &sz);
1408 if (r != ERROR_SUCCESS)
1410 ERR("failed to get string!\n");
1411 msi_free(val);
1412 return NULL;
1415 return val;
1418 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1419 LPWSTR table, MSIRECORD *rec)
1421 LPWSTR query = NULL, clause = NULL, val;
1422 LPCWSTR setptr, key;
1423 DWORD size, oldsize;
1424 MSIRECORD *keys;
1425 UINT r, i, count;
1427 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1428 if (r != ERROR_SUCCESS)
1429 return NULL;
1431 clause = msi_alloc_zero(sizeof(WCHAR));
1432 if (!clause)
1433 goto done;
1435 size = 1;
1436 count = MSI_RecordGetFieldCount(keys);
1437 for (i = 1; i <= count; i++)
1439 key = MSI_RecordGetString(keys, i);
1440 val = get_key_value(view, key, rec);
1442 if (i == count)
1443 setptr = L"`%s` = %s ";
1444 else
1445 setptr = L"`%s` = %s AND ";
1447 oldsize = size;
1448 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1449 clause = msi_realloc(clause, size * sizeof (WCHAR));
1450 if (!clause)
1452 msi_free(val);
1453 goto done;
1456 swprintf(clause + oldsize - 1, size - (oldsize - 1), setptr, key, val);
1457 msi_free(val);
1460 size = lstrlenW(L"SELECT * FROM `%s` WHERE %s") + lstrlenW(table) + lstrlenW(clause) + 1;
1461 query = msi_alloc(size * sizeof(WCHAR));
1462 if (!query)
1463 goto done;
1465 swprintf(query, size, L"SELECT * FROM `%s` WHERE %s", table, clause);
1467 done:
1468 msi_free(clause);
1469 msiobj_release(&keys->hdr);
1470 return query;
1473 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1475 MERGEDATA *data = param;
1476 MERGETABLE *table = data->curtable;
1477 MERGEROW *mergerow;
1478 MSIQUERY *dbview = NULL;
1479 MSIRECORD *row = NULL;
1480 LPWSTR query = NULL;
1481 UINT r = ERROR_SUCCESS;
1483 if (TABLE_Exists(data->db, table->name))
1485 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1486 if (!query)
1487 return ERROR_OUTOFMEMORY;
1489 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1490 if (r != ERROR_SUCCESS)
1491 goto done;
1493 r = MSI_ViewExecute(dbview, NULL);
1494 if (r != ERROR_SUCCESS)
1495 goto done;
1497 r = MSI_ViewFetch(dbview, &row);
1498 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1500 table->numconflicts++;
1501 goto done;
1503 else if (r != ERROR_NO_MORE_ITEMS)
1504 goto done;
1506 r = ERROR_SUCCESS;
1509 mergerow = msi_alloc(sizeof(MERGEROW));
1510 if (!mergerow)
1512 r = ERROR_OUTOFMEMORY;
1513 goto done;
1516 mergerow->data = MSI_CloneRecord(rec);
1517 if (!mergerow->data)
1519 r = ERROR_OUTOFMEMORY;
1520 msi_free(mergerow);
1521 goto done;
1524 list_add_tail(&table->rows, &mergerow->entry);
1526 done:
1527 msi_free(query);
1528 msiobj_release(&row->hdr);
1529 msiobj_release(&dbview->hdr);
1530 return r;
1533 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1535 UINT r, i, count;
1536 MSIRECORD *prec = NULL;
1538 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1539 if (r != ERROR_SUCCESS)
1540 return r;
1542 count = MSI_RecordGetFieldCount(prec);
1543 *numlabels = count + 1;
1544 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1545 if (!*labels)
1547 r = ERROR_OUTOFMEMORY;
1548 goto end;
1551 (*labels)[0] = strdupW(table);
1552 for (i=1; i<=count; i++ )
1554 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1557 end:
1558 msiobj_release( &prec->hdr );
1559 return r;
1562 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1564 UINT r, i, count;
1565 MSIRECORD *prec = NULL;
1567 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1568 if (r != ERROR_SUCCESS)
1569 return r;
1571 count = MSI_RecordGetFieldCount(prec);
1572 *columns = msi_alloc(count*sizeof(LPWSTR));
1573 if (!*columns)
1575 r = ERROR_OUTOFMEMORY;
1576 goto end;
1579 for (i=1; i<=count; i++ )
1581 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1584 *numcolumns = count;
1586 end:
1587 msiobj_release( &prec->hdr );
1588 return r;
1591 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1593 UINT r, i, count;
1594 MSIRECORD *prec = NULL;
1596 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1597 if (r != ERROR_SUCCESS)
1598 return r;
1600 count = MSI_RecordGetFieldCount(prec);
1601 *types = msi_alloc(count*sizeof(LPWSTR));
1602 if (!*types)
1604 r = ERROR_OUTOFMEMORY;
1605 goto end;
1608 *numtypes = count;
1609 for (i=1; i<=count; i++ )
1611 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1614 end:
1615 msiobj_release( &prec->hdr );
1616 return r;
1619 static void merge_free_rows(MERGETABLE *table)
1621 struct list *item, *cursor;
1623 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1625 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1627 list_remove(&row->entry);
1628 msiobj_release(&row->data->hdr);
1629 msi_free(row);
1633 static void free_merge_table(MERGETABLE *table)
1635 UINT i;
1637 if (table->labels != NULL)
1639 for (i = 0; i < table->numlabels; i++)
1640 msi_free(table->labels[i]);
1642 msi_free(table->labels);
1645 if (table->columns != NULL)
1647 for (i = 0; i < table->numcolumns; i++)
1648 msi_free(table->columns[i]);
1650 msi_free(table->columns);
1653 if (table->types != NULL)
1655 for (i = 0; i < table->numtypes; i++)
1656 msi_free(table->types[i]);
1658 msi_free(table->types);
1661 msi_free(table->name);
1662 merge_free_rows(table);
1664 msi_free(table);
1667 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1669 UINT r;
1670 MERGETABLE *table;
1671 MSIQUERY *mergeview = NULL;
1673 table = msi_alloc_zero(sizeof(MERGETABLE));
1674 if (!table)
1676 *ptable = NULL;
1677 return ERROR_OUTOFMEMORY;
1680 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1681 if (r != ERROR_SUCCESS)
1682 goto err;
1684 r = MSI_OpenQuery(db, &mergeview, L"SELECT * FROM `%s`", name);
1685 if (r != ERROR_SUCCESS)
1686 goto err;
1688 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1689 if (r != ERROR_SUCCESS)
1690 goto err;
1692 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1693 if (r != ERROR_SUCCESS)
1694 goto err;
1696 list_init(&table->rows);
1698 table->name = strdupW(name);
1699 table->numconflicts = 0;
1701 msiobj_release(&mergeview->hdr);
1702 *ptable = table;
1703 return ERROR_SUCCESS;
1705 err:
1706 msiobj_release(&mergeview->hdr);
1707 free_merge_table(table);
1708 *ptable = NULL;
1709 return r;
1712 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1714 MERGEDATA *data = param;
1715 MERGETABLE *table;
1716 MSIQUERY *dbview = NULL;
1717 MSIQUERY *mergeview = NULL;
1718 LPCWSTR name;
1719 UINT r;
1721 name = MSI_RecordGetString(rec, 1);
1723 r = MSI_OpenQuery(data->merge, &mergeview, L"SELECT * FROM `%s`", name);
1724 if (r != ERROR_SUCCESS)
1725 goto done;
1727 if (TABLE_Exists(data->db, name))
1729 r = MSI_OpenQuery(data->db, &dbview, L"SELECT * FROM `%s`", name);
1730 if (r != ERROR_SUCCESS)
1731 goto done;
1733 r = merge_verify_colnames(dbview, mergeview);
1734 if (r != ERROR_SUCCESS)
1735 goto done;
1737 r = merge_verify_primary_keys(data->db, data->merge, name);
1738 if (r != ERROR_SUCCESS)
1739 goto done;
1742 r = msi_get_merge_table(data->merge, name, &table);
1743 if (r != ERROR_SUCCESS)
1744 goto done;
1746 data->curtable = table;
1747 data->curview = mergeview;
1748 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1749 if (r != ERROR_SUCCESS)
1751 free_merge_table(table);
1752 goto done;
1755 list_add_tail(data->tabledata, &table->entry);
1757 done:
1758 msiobj_release(&dbview->hdr);
1759 msiobj_release(&mergeview->hdr);
1760 return r;
1763 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1764 struct list *tabledata)
1766 MSIQUERY *view;
1767 MERGEDATA data;
1768 UINT r;
1770 r = MSI_DatabaseOpenViewW(merge, L"SELECT * FROM `_Tables`", &view);
1771 if (r != ERROR_SUCCESS)
1772 return r;
1774 data.db = db;
1775 data.merge = merge;
1776 data.tabledata = tabledata;
1777 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1778 msiobj_release(&view->hdr);
1779 return r;
1782 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1784 UINT r;
1785 MERGEROW *row;
1786 MSIVIEW *tv;
1788 if (!TABLE_Exists(db, table->name))
1790 r = msi_add_table_to_db(db, table->columns, table->types,
1791 table->labels, table->numlabels, table->numcolumns);
1792 if (r != ERROR_SUCCESS)
1793 return ERROR_FUNCTION_FAILED;
1796 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1798 r = TABLE_CreateView(db, table->name, &tv);
1799 if (r != ERROR_SUCCESS)
1800 return r;
1802 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1803 tv->ops->delete(tv);
1805 if (r != ERROR_SUCCESS)
1806 return r;
1809 return ERROR_SUCCESS;
1812 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1813 LPWSTR table, DWORD numconflicts)
1815 UINT r;
1816 MSIQUERY *view;
1818 if (!TABLE_Exists(db, error))
1820 r = MSI_OpenQuery(db, &view, L"CREATE TABLE `%s` (`Table` CHAR(255) NOT NULL, `NumRowMergeConflicts` SHORT "
1821 "NOT NULL PRIMARY KEY `Table`)" , error);
1822 if (r != ERROR_SUCCESS)
1823 return r;
1825 r = MSI_ViewExecute(view, NULL);
1826 msiobj_release(&view->hdr);
1827 if (r != ERROR_SUCCESS)
1828 return r;
1831 r = MSI_OpenQuery(db, &view, L"INSERT INTO `%s` (`Table`, `NumRowMergeConflicts`) VALUES ('%s', %d)", error,
1832 table, numconflicts);
1833 if (r != ERROR_SUCCESS)
1834 return r;
1836 r = MSI_ViewExecute(view, NULL);
1837 msiobj_release(&view->hdr);
1838 return r;
1841 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge, LPCWSTR szTableName)
1843 struct list tabledata = LIST_INIT(tabledata);
1844 struct list *item, *cursor;
1845 MSIDATABASE *db, *merge;
1846 MERGETABLE *table;
1847 BOOL conflicts;
1848 UINT r;
1850 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge, debugstr_w(szTableName));
1852 if (szTableName && !*szTableName)
1853 return ERROR_INVALID_TABLE;
1855 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1856 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1857 if (!db || !merge)
1859 r = ERROR_INVALID_HANDLE;
1860 goto done;
1863 r = gather_merge_data(db, merge, &tabledata);
1864 if (r != ERROR_SUCCESS)
1865 goto done;
1867 conflicts = FALSE;
1868 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1870 if (table->numconflicts)
1872 conflicts = TRUE;
1874 r = update_merge_errors(db, szTableName, table->name,
1875 table->numconflicts);
1876 if (r != ERROR_SUCCESS)
1877 break;
1879 else
1881 r = merge_table(db, table);
1882 if (r != ERROR_SUCCESS)
1883 break;
1887 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1889 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1890 list_remove(&table->entry);
1891 free_merge_table(table);
1894 if (conflicts)
1895 r = ERROR_FUNCTION_FAILED;
1897 done:
1898 msiobj_release(&db->hdr);
1899 msiobj_release(&merge->hdr);
1900 return r;
1903 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1905 MSIDBSTATE ret = MSIDBSTATE_READ;
1906 MSIDATABASE *db;
1908 TRACE("%d\n", handle);
1910 if (!(db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE )))
1911 return MSIDBSTATE_ERROR;
1913 if (db->mode != MSI_OPEN_READONLY )
1914 ret = MSIDBSTATE_WRITE;
1915 msiobj_release( &db->hdr );
1917 return ret;
1920 MSICONDITION __cdecl s_remote_DatabaseIsTablePersistent(MSIHANDLE db, LPCWSTR table)
1922 return MsiDatabaseIsTablePersistentW(db, table);
1925 UINT __cdecl s_remote_DatabaseGetPrimaryKeys(MSIHANDLE db, LPCWSTR table, struct wire_record **rec)
1927 MSIHANDLE handle;
1928 UINT r = MsiDatabaseGetPrimaryKeysW(db, table, &handle);
1929 *rec = NULL;
1930 if (!r)
1931 *rec = marshal_record(handle);
1932 MsiCloseHandle(handle);
1933 return r;
1936 UINT __cdecl s_remote_DatabaseGetSummaryInformation(MSIHANDLE db, UINT updatecount, MSIHANDLE *suminfo)
1938 return MsiGetSummaryInformationW(db, NULL, updatecount, suminfo);
1941 UINT __cdecl s_remote_DatabaseOpenView(MSIHANDLE db, LPCWSTR query, MSIHANDLE *view)
1943 return MsiDatabaseOpenViewW(db, query, view);